您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

lib-jitsi-meet.js 995KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (__filename){
  3. /* global Strophe, $, Promise */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var AuthenticationEvents = require("./service/authentication/AuthenticationEvents");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  13. var JitsiParticipant = require("./JitsiParticipant");
  14. var Statistics = require("./modules/statistics/statistics");
  15. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  16. var JitsiTrackEvents = require("./JitsiTrackEvents");
  17. var Settings = require("./modules/settings/Settings");
  18. /**
  19. * Creates a JitsiConference object with the given name and properties.
  20. * Note: this constructor is not a part of the public API (objects should be
  21. * created using JitsiConnection.createConference).
  22. * @param options.config properties / settings related to the conference that will be created.
  23. * @param options.name the name of the conference
  24. * @param options.connection the JitsiConnection object for this JitsiConference.
  25. * @constructor
  26. */
  27. function JitsiConference(options) {
  28. if(!options.name || options.name.toLowerCase() !== options.name) {
  29. logger.error("Invalid conference name (no conference name passed or it"
  30. + "contains invalid characters like capital letters)!");
  31. return;
  32. }
  33. this.options = options;
  34. this.connection = this.options.connection;
  35. this.xmpp = this.connection.xmpp;
  36. this.eventEmitter = new EventEmitter();
  37. var confID = this.options.name + '@' + this.xmpp.options.hosts.muc;
  38. this.settings = new Settings(confID);
  39. this.room = this.xmpp.createRoom(this.options.name, this.options.config,
  40. this.settings);
  41. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  42. this.rtc = new RTC(this.room, options);
  43. this.statistics = new Statistics({
  44. disableAudioLevels: RTC.options.disableAudioLevels,
  45. callStatsID: this.options.config.callStatsID,
  46. callStatsSecret: this.options.config.callStatsSecret,
  47. disableThirdPartyRequests: this.options.config.disableThirdPartyRequests
  48. });
  49. setupListeners(this);
  50. JitsiMeetJS._gumFailedHandler.push(function(error) {
  51. this.statistics.sendGetUserMediaFailed(error);
  52. }.bind(this));
  53. this.participants = {};
  54. this.lastDominantSpeaker = null;
  55. this.dtmfManager = null;
  56. this.somebodySupportsDTMF = false;
  57. this.authEnabled = false;
  58. this.authIdentity;
  59. this.startAudioMuted = false;
  60. this.startVideoMuted = false;
  61. this.startMutedPolicy = {audio: false, video: false};
  62. }
  63. /**
  64. * Joins the conference.
  65. * @param password {string} the password
  66. */
  67. JitsiConference.prototype.join = function (password) {
  68. if(this.room)
  69. this.room.join(password);
  70. };
  71. /**
  72. * Check if joined to the conference.
  73. */
  74. JitsiConference.prototype.isJoined = function () {
  75. return this.room && this.room.joined;
  76. };
  77. /**
  78. * Leaves the conference.
  79. */
  80. JitsiConference.prototype.leave = function () {
  81. if(this.xmpp && this.room)
  82. this.xmpp.leaveRoom(this.room.roomjid);
  83. this.room = null;
  84. };
  85. /**
  86. * Returns name of this conference.
  87. */
  88. JitsiConference.prototype.getName = function () {
  89. return this.options.name;
  90. };
  91. /**
  92. * Check if authentication is enabled for this conference.
  93. */
  94. JitsiConference.prototype.isAuthEnabled = function () {
  95. return this.authEnabled;
  96. };
  97. /**
  98. * Check if user is logged in.
  99. */
  100. JitsiConference.prototype.isLoggedIn = function () {
  101. return !!this.authIdentity;
  102. };
  103. /**
  104. * Get authorized login.
  105. */
  106. JitsiConference.prototype.getAuthLogin = function () {
  107. return this.authIdentity;
  108. };
  109. /**
  110. * Check if external authentication is enabled for this conference.
  111. */
  112. JitsiConference.prototype.isExternalAuthEnabled = function () {
  113. return this.room && this.room.moderator.isExternalAuthEnabled();
  114. };
  115. /**
  116. * Get url for external authentication.
  117. * @param {boolean} [urlForPopup] if true then return url for login popup,
  118. * else url of login page.
  119. * @returns {Promise}
  120. */
  121. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  122. return new Promise(function (resolve, reject) {
  123. if (!this.isExternalAuthEnabled()) {
  124. reject();
  125. return;
  126. }
  127. if (urlForPopup) {
  128. this.room.moderator.getPopupLoginUrl(resolve, reject);
  129. } else {
  130. this.room.moderator.getLoginUrl(resolve, reject);
  131. }
  132. }.bind(this));
  133. };
  134. /**
  135. * Returns the local tracks.
  136. */
  137. JitsiConference.prototype.getLocalTracks = function () {
  138. if (this.rtc) {
  139. return this.rtc.localStreams;
  140. } else {
  141. return [];
  142. }
  143. };
  144. /**
  145. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  146. * in JitsiConferenceEvents.
  147. * @param eventId the event ID.
  148. * @param handler handler for the event.
  149. *
  150. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  151. */
  152. JitsiConference.prototype.on = function (eventId, handler) {
  153. if(this.eventEmitter)
  154. this.eventEmitter.on(eventId, handler);
  155. };
  156. /**
  157. * Removes event listener
  158. * @param eventId the event ID.
  159. * @param [handler] optional, the specific handler to unbind
  160. *
  161. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  162. */
  163. JitsiConference.prototype.off = function (eventId, handler) {
  164. if(this.eventEmitter)
  165. this.eventEmitter.removeListener(eventId, handler);
  166. };
  167. // Common aliases for event emitter
  168. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  169. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  170. /**
  171. * Receives notifications from another participants for commands / custom events
  172. * (send by sendPresenceCommand method).
  173. * @param command {String} the name of the command
  174. * @param handler {Function} handler for the command
  175. */
  176. JitsiConference.prototype.addCommandListener = function (command, handler) {
  177. if(this.room)
  178. this.room.addPresenceListener(command, handler);
  179. };
  180. /**
  181. * Removes command listener
  182. * @param command {String} the name of the command
  183. */
  184. JitsiConference.prototype.removeCommandListener = function (command) {
  185. if(this.room)
  186. this.room.removePresenceListener(command);
  187. };
  188. /**
  189. * Sends text message to the other participants in the conference
  190. * @param message the text message.
  191. */
  192. JitsiConference.prototype.sendTextMessage = function (message) {
  193. if(this.room)
  194. this.room.sendMessage(message);
  195. };
  196. /**
  197. * Send presence command.
  198. * @param name the name of the command.
  199. * @param values Object with keys and values that will be send.
  200. **/
  201. JitsiConference.prototype.sendCommand = function (name, values) {
  202. if(this.room) {
  203. this.room.addToPresence(name, values);
  204. this.room.sendPresence();
  205. }
  206. };
  207. /**
  208. * Send presence command one time.
  209. * @param name the name of the command.
  210. * @param values Object with keys and values that will be send.
  211. **/
  212. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  213. this.sendCommand(name, values);
  214. this.removeCommand(name);
  215. };
  216. /**
  217. * Send presence command.
  218. * @param name the name of the command.
  219. * @param values Object with keys and values that will be send.
  220. * @param persistent if false the command will be sent only one time
  221. **/
  222. JitsiConference.prototype.removeCommand = function (name) {
  223. if(this.room)
  224. this.room.removeFromPresence(name);
  225. };
  226. /**
  227. * Sets the display name for this conference.
  228. * @param name the display name to set
  229. */
  230. JitsiConference.prototype.setDisplayName = function(name) {
  231. if(this.room){
  232. // remove previously set nickname
  233. this.room.removeFromPresence("nick");
  234. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  235. this.room.sendPresence();
  236. }
  237. };
  238. /**
  239. * Adds JitsiLocalTrack object to the conference.
  240. * @param track the JitsiLocalTrack object.
  241. */
  242. JitsiConference.prototype.addTrack = function (track) {
  243. this.room.addStream(track.getOriginalStream(), function () {
  244. this.rtc.addLocalStream(track);
  245. if (track.startMuted) {
  246. track.mute();
  247. }
  248. track.muteHandler = this._fireMuteChangeEvent.bind(this, track);
  249. track.stopHandler = this.removeTrack.bind(this, track);
  250. track.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  251. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  252. track.muteHandler);
  253. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED,
  254. track.stopHandler);
  255. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  256. track.audioLevelHandler);
  257. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  258. }.bind(this));
  259. };
  260. /**
  261. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  262. * @param audioLevel the audio level
  263. */
  264. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  265. this.eventEmitter.emit(
  266. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  267. this.myUserId(), audioLevel);
  268. };
  269. /**
  270. * Fires TRACK_MUTE_CHANGED change conference event.
  271. * @param track the JitsiTrack object related to the event.
  272. */
  273. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  274. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  275. };
  276. /**
  277. * Removes JitsiLocalTrack object to the conference.
  278. * @param track the JitsiLocalTrack object.
  279. */
  280. JitsiConference.prototype.removeTrack = function (track) {
  281. if(!this.room){
  282. if(this.rtc)
  283. this.rtc.removeLocalStream(track);
  284. return;
  285. }
  286. this.room.removeStream(track.getOriginalStream(), function(){
  287. this.rtc.removeLocalStream(track);
  288. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  289. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, track.stopHandler);
  290. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  291. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  292. }.bind(this));
  293. };
  294. /**
  295. * Get role of the local user.
  296. * @returns {string} user role: 'moderator' or 'none'
  297. */
  298. JitsiConference.prototype.getRole = function () {
  299. return this.room.role;
  300. };
  301. /**
  302. * Check if local user is moderator.
  303. * @returns {boolean} true if local user is moderator, false otherwise.
  304. */
  305. JitsiConference.prototype.isModerator = function () {
  306. return this.room.isModerator();
  307. };
  308. /**
  309. * Set password for the room.
  310. * @param {string} password new password for the room.
  311. * @returns {Promise}
  312. */
  313. JitsiConference.prototype.lock = function (password) {
  314. if (!this.isModerator()) {
  315. return Promise.reject();
  316. }
  317. var conference = this;
  318. return new Promise(function (resolve, reject) {
  319. conference.room.lockRoom(password || "", function () {
  320. resolve();
  321. }, function (err) {
  322. reject(err);
  323. }, function () {
  324. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  325. });
  326. });
  327. };
  328. /**
  329. * Remove password from the room.
  330. * @returns {Promise}
  331. */
  332. JitsiConference.prototype.unlock = function () {
  333. return this.lock();
  334. };
  335. /**
  336. * Elects the participant with the given id to be the selected participant or the speaker.
  337. * @param id the identifier of the participant
  338. */
  339. JitsiConference.prototype.selectParticipant = function(participantId) {
  340. if (this.rtc) {
  341. this.rtc.selectedEndpoint(participantId);
  342. }
  343. };
  344. /**
  345. *
  346. * @param id the identifier of the participant
  347. */
  348. JitsiConference.prototype.pinParticipant = function(participantId) {
  349. if (this.rtc) {
  350. this.rtc.pinEndpoint(participantId);
  351. }
  352. };
  353. /**
  354. * Returns the list of participants for this conference.
  355. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  356. */
  357. JitsiConference.prototype.getParticipants = function() {
  358. return Object.keys(this.participants).map(function (key) {
  359. return this.participants[key];
  360. }, this);
  361. };
  362. /**
  363. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  364. * undefined if there isn't one).
  365. * @param id the id of the participant.
  366. */
  367. JitsiConference.prototype.getParticipantById = function(id) {
  368. return this.participants[id];
  369. };
  370. /**
  371. * Kick participant from this conference.
  372. * @param {string} id id of the participant to kick
  373. */
  374. JitsiConference.prototype.kickParticipant = function (id) {
  375. var participant = this.getParticipantById(id);
  376. if (!participant) {
  377. return;
  378. }
  379. this.room.kick(participant.getJid());
  380. };
  381. /**
  382. * Kick participant from this conference.
  383. * @param {string} id id of the participant to kick
  384. */
  385. JitsiConference.prototype.muteParticipant = function (id) {
  386. var participant = this.getParticipantById(id);
  387. if (!participant) {
  388. return;
  389. }
  390. this.room.muteParticipant(participant.getJid(), true);
  391. };
  392. JitsiConference.prototype.onMemberJoined = function (jid, nick, role) {
  393. var id = Strophe.getResourceFromJid(jid);
  394. if (id === 'focus' || this.myUserId() === id) {
  395. return;
  396. }
  397. var participant = new JitsiParticipant(jid, this, nick);
  398. participant._role = role;
  399. this.participants[id] = participant;
  400. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  401. this.xmpp.connection.disco.info(
  402. jid, "node", function(iq) {
  403. participant._supportsDTMF = $(iq).find(
  404. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  405. this.updateDTMFSupport();
  406. }.bind(this)
  407. );
  408. };
  409. JitsiConference.prototype.onMemberLeft = function (jid) {
  410. var id = Strophe.getResourceFromJid(jid);
  411. if (id === 'focus' || this.myUserId() === id) {
  412. return;
  413. }
  414. var participant = this.participants[id];
  415. delete this.participants[id];
  416. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  417. };
  418. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  419. var id = Strophe.getResourceFromJid(jid);
  420. var participant = this.getParticipantById(id);
  421. if (!participant) {
  422. return;
  423. }
  424. participant._role = role;
  425. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  426. };
  427. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  428. var id = Strophe.getResourceFromJid(jid);
  429. var participant = this.getParticipantById(id);
  430. if (!participant) {
  431. return;
  432. }
  433. participant._displayName = displayName;
  434. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  435. };
  436. JitsiConference.prototype.onTrackAdded = function (track) {
  437. var id = track.getParticipantId();
  438. var participant = this.getParticipantById(id);
  439. if (!participant) {
  440. return;
  441. }
  442. // add track to JitsiParticipant
  443. participant._tracks.push(track);
  444. var emitter = this.eventEmitter;
  445. track.addEventListener(
  446. JitsiTrackEvents.TRACK_STOPPED,
  447. function () {
  448. // remove track from JitsiParticipant
  449. var pos = participant._tracks.indexOf(track);
  450. if (pos > -1) {
  451. participant._tracks.splice(pos, 1);
  452. }
  453. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  454. }
  455. );
  456. track.addEventListener(
  457. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  458. function () {
  459. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  460. }
  461. );
  462. track.addEventListener(
  463. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  464. function (audioLevel) {
  465. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  466. }
  467. );
  468. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  469. };
  470. JitsiConference.prototype.updateDTMFSupport = function () {
  471. var somebodySupportsDTMF = false;
  472. var participants = this.getParticipants();
  473. // check if at least 1 participant supports DTMF
  474. for (var i = 0; i < participants.length; i += 1) {
  475. if (participants[i].supportsDTMF()) {
  476. somebodySupportsDTMF = true;
  477. break;
  478. }
  479. }
  480. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  481. this.somebodySupportsDTMF = somebodySupportsDTMF;
  482. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  483. }
  484. };
  485. /**
  486. * Allows to check if there is at least one user in the conference
  487. * that supports DTMF.
  488. * @returns {boolean} true if somebody supports DTMF, false otherwise
  489. */
  490. JitsiConference.prototype.isDTMFSupported = function () {
  491. return this.somebodySupportsDTMF;
  492. };
  493. /**
  494. * Returns the local user's ID
  495. * @return {string} local user's ID
  496. */
  497. JitsiConference.prototype.myUserId = function () {
  498. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  499. };
  500. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  501. if (!this.dtmfManager) {
  502. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  503. if (!connection) {
  504. logger.warn("cannot sendTones: no conneciton");
  505. return;
  506. }
  507. var tracks = this.getLocalTracks().filter(function (track) {
  508. return track.isAudioTrack();
  509. });
  510. if (!tracks.length) {
  511. logger.warn("cannot sendTones: no local audio stream");
  512. return;
  513. }
  514. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  515. }
  516. this.dtmfManager.sendTones(tones, duration, pause);
  517. };
  518. /**
  519. * Returns true if the recording is supproted and false if not.
  520. */
  521. JitsiConference.prototype.isRecordingSupported = function () {
  522. if(this.room)
  523. return this.room.isRecordingSupported();
  524. return false;
  525. };
  526. /**
  527. * Returns null if the recording is not supported, "on" if the recording started
  528. * and "off" if the recording is not started.
  529. */
  530. JitsiConference.prototype.getRecordingState = function () {
  531. if(this.room)
  532. return this.room.getRecordingState();
  533. return "off";
  534. }
  535. /**
  536. * Returns the url of the recorded video.
  537. */
  538. JitsiConference.prototype.getRecordingURL = function () {
  539. if(this.room)
  540. return this.room.getRecordingURL();
  541. return null;
  542. }
  543. /**
  544. * Starts/stops the recording
  545. */
  546. JitsiConference.prototype.toggleRecording = function (options) {
  547. if(this.room)
  548. return this.room.toggleRecording(options, function (status, error) {
  549. this.eventEmitter.emit(
  550. JitsiConferenceEvents.RECORDING_STATE_CHANGED, status, error);
  551. }.bind(this));
  552. this.eventEmitter.emit(
  553. JitsiConferenceEvents.RECORDING_STATE_CHANGED, "error",
  554. new Error("The conference is not created yet!"));
  555. }
  556. /**
  557. * Returns true if the SIP calls are supported and false otherwise
  558. */
  559. JitsiConference.prototype.isSIPCallingSupported = function () {
  560. if(this.room)
  561. return this.room.isSIPCallingSupported();
  562. return false;
  563. }
  564. /**
  565. * Dials a number.
  566. * @param number the number
  567. */
  568. JitsiConference.prototype.dial = function (number) {
  569. if(this.room)
  570. return this.room.dial(number);
  571. return new Promise(function(resolve, reject){
  572. reject(new Error("The conference is not created yet!"))});
  573. }
  574. /**
  575. * Hangup an existing call
  576. */
  577. JitsiConference.prototype.hangup = function () {
  578. if(this.room)
  579. return this.room.hangup();
  580. return new Promise(function(resolve, reject){
  581. reject(new Error("The conference is not created yet!"))});
  582. }
  583. /**
  584. * Returns the phone number for joining the conference.
  585. */
  586. JitsiConference.prototype.getPhoneNumber = function () {
  587. if(this.room)
  588. return this.room.getPhoneNumber();
  589. return null;
  590. }
  591. /**
  592. * Returns the pin for joining the conference with phone.
  593. */
  594. JitsiConference.prototype.getPhonePin = function () {
  595. if(this.room)
  596. return this.room.getPhonePin();
  597. return null;
  598. }
  599. /**
  600. * Returns the connection state for the current room. Its ice connection state
  601. * for its session.
  602. */
  603. JitsiConference.prototype.getConnectionState = function () {
  604. if(this.room)
  605. return this.room.getConnectionState();
  606. return null;
  607. }
  608. /**
  609. * Make all new participants mute their audio/video on join.
  610. * @param policy {Object} object with 2 boolean properties for video and audio:
  611. * @param {boolean} audio if audio should be muted.
  612. * @param {boolean} video if video should be muted.
  613. */
  614. JitsiConference.prototype.setStartMutedPolicy = function (policy) {
  615. if (!this.isModerator()) {
  616. return;
  617. }
  618. this.startMutedPolicy = policy;
  619. this.room.removeFromPresence("startmuted");
  620. this.room.addToPresence("startmuted", {
  621. attributes: {
  622. audio: policy.audio,
  623. video: policy.video,
  624. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  625. }
  626. });
  627. this.room.sendPresence();
  628. };
  629. /**
  630. * Returns current start muted policy
  631. * @returns {Object} with 2 proprties - audio and video.
  632. */
  633. JitsiConference.prototype.getStartMutedPolicy = function () {
  634. return this.startMutedPolicy;
  635. };
  636. /**
  637. * Check if audio is muted on join.
  638. */
  639. JitsiConference.prototype.isStartAudioMuted = function () {
  640. return this.startAudioMuted;
  641. };
  642. /**
  643. * Check if video is muted on join.
  644. */
  645. JitsiConference.prototype.isStartVideoMuted = function () {
  646. return this.startVideoMuted;
  647. };
  648. /**
  649. * Get object with internal logs.
  650. */
  651. JitsiConference.prototype.getLogs = function () {
  652. var data = this.xmpp.getJingleLog();
  653. var metadata = {};
  654. metadata.time = new Date();
  655. metadata.url = window.location.href;
  656. metadata.ua = navigator.userAgent;
  657. var log = this.xmpp.getXmppLog();
  658. if (log) {
  659. metadata.xmpp = log;
  660. }
  661. data.metadata = metadata;
  662. return data;
  663. };
  664. /**
  665. * Sends the given feedback through CallStats if enabled.
  666. *
  667. * @param overallFeedback an integer between 1 and 5 indicating the
  668. * user feedback
  669. * @param detailedFeedback detailed feedback from the user. Not yet used
  670. */
  671. JitsiConference.prototype.sendFeedback =
  672. function(overallFeedback, detailedFeedback){
  673. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  674. }
  675. /**
  676. * Returns true if the callstats integration is enabled, otherwise returns
  677. * false.
  678. *
  679. * @returns true if the callstats integration is enabled, otherwise returns
  680. * false.
  681. */
  682. JitsiConference.prototype.isCallstatsEnabled = function () {
  683. return this.statistics.isCallstatsEnabled();
  684. }
  685. /**
  686. * Setups the listeners needed for the conference.
  687. * @param conference the conference
  688. */
  689. function setupListeners(conference) {
  690. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  691. conference.rtc.onIncommingCall(event);
  692. conference.statistics.startRemoteStats(event.peerconnection);
  693. });
  694. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  695. function (data, sid, thessrc) {
  696. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  697. if (track) {
  698. conference.onTrackAdded(track);
  699. }
  700. }
  701. );
  702. conference.room.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS,
  703. function (value) {
  704. conference.rtc.setAudioMute(value);
  705. }
  706. );
  707. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  708. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  709. });
  710. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  711. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  712. });
  713. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  714. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  715. });
  716. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  717. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  718. });
  719. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  720. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  721. });
  722. conference.room.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  723. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE);
  724. });
  725. // FIXME
  726. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  727. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  728. // });
  729. conference.room.addListener(XMPPEvents.KICKED, function () {
  730. conference.eventEmitter.emit(JitsiConferenceEvents.KICKED);
  731. });
  732. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  733. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  734. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  735. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  736. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  737. });
  738. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  739. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  740. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  741. });
  742. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  743. function () {
  744. conference.eventEmitter.emit(
  745. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  746. });
  747. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  748. conference.eventEmitter.emit(
  749. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  750. });
  751. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  752. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  753. });
  754. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  755. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  756. });
  757. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  758. conference.authEnabled = authEnabled;
  759. conference.authIdentity = authIdentity;
  760. });
  761. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  762. var id = Strophe.getResourceFromJid(jid);
  763. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  764. });
  765. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  766. if(conference.lastDominantSpeaker !== id && conference.room) {
  767. conference.lastDominantSpeaker = id;
  768. conference.eventEmitter.emit(JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED, id);
  769. }
  770. });
  771. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  772. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  773. });
  774. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  775. function (lastNEndpoints, endpointsEnteringLastN) {
  776. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  777. lastNEndpoints, endpointsEnteringLastN);
  778. });
  779. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  780. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  781. });
  782. conference.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS,
  783. function (audioMuted, videoMuted) {
  784. conference.startAudioMuted = audioMuted;
  785. conference.startVideoMuted = videoMuted;
  786. // mute existing local tracks because this is initial mute from
  787. // Jicofo
  788. conference.getLocalTracks().forEach(function (track) {
  789. if (conference.startAudioMuted && track.isAudioTrack()) {
  790. track.mute();
  791. }
  792. if (conference.startVideoMuted && track.isVideoTrack()) {
  793. track.mute();
  794. }
  795. });
  796. conference.eventEmitter.emit(JitsiConferenceEvents.STARTED_MUTED);
  797. });
  798. conference.room.addPresenceListener("startmuted", function (data, from) {
  799. var isModerator = false;
  800. if (conference.myUserId() === from && conference.isModerator()) {
  801. isModerator = true;
  802. } else {
  803. var participant = conference.getParticipantById(from);
  804. if (participant && participant.isModerator()) {
  805. isModerator = true;
  806. }
  807. }
  808. if (!isModerator) {
  809. return;
  810. }
  811. var startAudioMuted = data.attributes.audio === 'true';
  812. var startVideoMuted = data.attributes.video === 'true';
  813. var updated = false;
  814. if (startAudioMuted !== conference.startMutedPolicy.audio) {
  815. conference.startMutedPolicy.audio = startAudioMuted;
  816. updated = true;
  817. }
  818. if (startVideoMuted !== conference.startMutedPolicy.video) {
  819. conference.startMutedPolicy.video = startVideoMuted;
  820. updated = true;
  821. }
  822. if (updated) {
  823. conference.eventEmitter.emit(
  824. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  825. conference.startMutedPolicy
  826. );
  827. }
  828. });
  829. if(conference.statistics) {
  830. //FIXME: Maybe remove event should not be associated with the conference.
  831. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  832. var userId = null;
  833. var jid = conference.room.getJidBySSRC(ssrc);
  834. if (!jid)
  835. return;
  836. conference.rtc.setAudioLevel(jid, level);
  837. });
  838. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  839. function () {
  840. conference.statistics.dispose();
  841. });
  842. // FIXME: Maybe we should move this.
  843. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  844. // conference.room.updateDeviceAvailability(devices);
  845. // });
  846. conference.room.addListener(XMPPEvents.PEERCONNECTION_READY,
  847. function (session) {
  848. conference.statistics.startCallStats(
  849. session, conference.settings);
  850. });
  851. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED,
  852. function () {
  853. conference.statistics.sendSetupFailedEvent();
  854. });
  855. conference.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED,
  856. function (track) {
  857. if(!track.isLocal())
  858. return;
  859. var type = (track.getType() === "audio")? "audio" : "video";
  860. conference.statistics.sendMuteEvent(track.isMuted(), type);
  861. });
  862. conference.room.addListener(XMPPEvents.CREATE_OFFER_FAILED, function (e, pc) {
  863. conference.statistics.sendCreateOfferFailed(e, pc);
  864. });
  865. conference.room.addListener(XMPPEvents.CREATE_ANSWER_FAILED, function (e, pc) {
  866. conference.statistics.sendCreateAnswerFailed(e, pc);
  867. });
  868. conference.room.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  869. function (e, pc) {
  870. conference.statistics.sendSetLocalDescFailed(e, pc);
  871. }
  872. );
  873. conference.room.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  874. function (e, pc) {
  875. conference.statistics.sendSetRemoteDescFailed(e, pc);
  876. }
  877. );
  878. conference.room.addListener(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  879. function (e, pc) {
  880. conference.statistics.sendAddIceCandidateFailed(e, pc);
  881. }
  882. );
  883. }
  884. }
  885. module.exports = JitsiConference;
  886. }).call(this,"/JitsiConference.js")
  887. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/settings/Settings":21,"./modules/statistics/statistics":25,"./service/RTC/RTCEvents":132,"./service/authentication/AuthenticationEvents":134,"./service/xmpp/XMPPEvents":138,"events":45,"jitsi-meet-logger":49}],2:[function(require,module,exports){
  888. /**
  889. * Enumeration with the errors for the conference.
  890. * @type {{string: string}}
  891. */
  892. var JitsiConferenceErrors = {
  893. /**
  894. * Indicates that a password is required in order to join the conference.
  895. */
  896. PASSWORD_REQUIRED: "conference.passwordRequired",
  897. /**
  898. * Indicates that client must be authenticated to create the conference.
  899. */
  900. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  901. /**
  902. * Indicates that password cannot be set for this conference.
  903. */
  904. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  905. /**
  906. * Indicates that a connection error occurred when trying to join a
  907. * conference.
  908. */
  909. CONNECTION_ERROR: "conference.connectionError",
  910. /**
  911. * Indicates that the conference setup failed.
  912. */
  913. SETUP_FAILED: "conference.setup_failed",
  914. /**
  915. * Indicates that there is no available videobridge.
  916. */
  917. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  918. /**
  919. * Many more errors TBD here.
  920. */
  921. };
  922. module.exports = JitsiConferenceErrors;
  923. },{}],3:[function(require,module,exports){
  924. /**
  925. * Enumeration with the events for the conference.
  926. * @type {{string: string}}
  927. */
  928. var JitsiConferenceEvents = {
  929. /**
  930. * A new media track was added to the conference.
  931. */
  932. TRACK_ADDED: "conference.trackAdded",
  933. /**
  934. * The media track was removed from the conference.
  935. */
  936. TRACK_REMOVED: "conference.trackRemoved",
  937. /**
  938. * The dominant speaker was changed.
  939. */
  940. DOMINANT_SPEAKER_CHANGED: "conference.dominantSpeaker",
  941. /**
  942. * A new user joinned the conference.
  943. */
  944. USER_JOINED: "conference.userJoined",
  945. /**
  946. * A user has left the conference.
  947. */
  948. USER_LEFT: "conference.userLeft",
  949. /**
  950. * User role changed.
  951. */
  952. USER_ROLE_CHANGED: "conference.roleChanged",
  953. /**
  954. * New text message was received.
  955. */
  956. MESSAGE_RECEIVED: "conference.messageReceived",
  957. /**
  958. * A user has changed it display name
  959. */
  960. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  961. /**
  962. * A participant avatar has changed.
  963. */
  964. AVATAR_CHANGED: "conference.avatarChanged",
  965. /**
  966. * New connection statistics are received.
  967. */
  968. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  969. /**
  970. * The Last N set is changed.
  971. */
  972. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  973. /**
  974. * You are included / excluded in somebody's last N set
  975. */
  976. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  977. /**
  978. * A media track ( attached to the conference) mute status was changed.
  979. */
  980. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  981. /**
  982. * Audio levels of a media track ( attached to the conference) was changed.
  983. */
  984. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  985. /**
  986. * Indicates that the connection to the conference has been interrupted
  987. * for some reason.
  988. */
  989. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  990. /**
  991. * Indicates that the connection to the conference has been restored.
  992. */
  993. CONNECTION_RESTORED: "conference.connectionRestored",
  994. /**
  995. * Indicates that conference failed.
  996. */
  997. CONFERENCE_FAILED: "conference.failed",
  998. /**
  999. * Indicates that conference has been joined.
  1000. */
  1001. CONFERENCE_JOINED: "conference.joined",
  1002. /**
  1003. * Indicates that conference has been left.
  1004. */
  1005. CONFERENCE_LEFT: "conference.left",
  1006. /**
  1007. * You are kicked from the conference.
  1008. */
  1009. KICKED: "conferenece.kicked",
  1010. /**
  1011. * Indicates that start muted settings changed.
  1012. */
  1013. START_MUTED_POLICY_CHANGED: "conference.start_muted_policy_changed",
  1014. /**
  1015. * Indicates that the local user has started muted.
  1016. */
  1017. STARTED_MUTED: "conference.started_muted",
  1018. /**
  1019. * Indicates that DTMF support changed.
  1020. */
  1021. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  1022. /**
  1023. * Indicates that recording state changed.
  1024. */
  1025. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  1026. /**
  1027. * Indicates that phone number changed.
  1028. */
  1029. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  1030. };
  1031. module.exports = JitsiConferenceEvents;
  1032. },{}],4:[function(require,module,exports){
  1033. var JitsiConference = require("./JitsiConference");
  1034. var XMPP = require("./modules/xmpp/xmpp");
  1035. /**
  1036. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  1037. * JitsiConference interface.
  1038. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  1039. * @param token the JWT token used to authenticate with the server(optional)
  1040. * @param options Object with properties / settings related to connection with the server.
  1041. * @constructor
  1042. */
  1043. function JitsiConnection(appID, token, options) {
  1044. this.appID = appID;
  1045. this.token = token;
  1046. this.options = options;
  1047. this.xmpp = new XMPP(options);
  1048. this.conferences = {};
  1049. }
  1050. /**
  1051. * Connect the client with the server.
  1052. * @param options {object} connecting options (for example authentications parameters).
  1053. */
  1054. JitsiConnection.prototype.connect = function (options) {
  1055. if(!options)
  1056. options = {};
  1057. this.xmpp.connect(options.id, options.password);
  1058. }
  1059. /**
  1060. * Disconnect the client from the server.
  1061. */
  1062. JitsiConnection.prototype.disconnect = function () {
  1063. this.xmpp.disconnect();
  1064. }
  1065. /**
  1066. * This method allows renewal of the tokens if they are expiring.
  1067. * @param token the new token.
  1068. */
  1069. JitsiConnection.prototype.setToken = function (token) {
  1070. this.token = token;
  1071. }
  1072. /**
  1073. * Creates and joins new conference.
  1074. * @param name the name of the conference; if null - a generated name will be
  1075. * provided from the api
  1076. * @param options Object with properties / settings related to the conference
  1077. * that will be created.
  1078. * @returns {JitsiConference} returns the new conference object.
  1079. */
  1080. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  1081. this.conferences[name] = new JitsiConference({name: name, config: options,
  1082. connection: this});
  1083. return this.conferences[name];
  1084. }
  1085. /**
  1086. * Subscribes the passed listener to the event.
  1087. * @param event {JitsiConnectionEvents} the connection event.
  1088. * @param listener {Function} the function that will receive the event
  1089. */
  1090. JitsiConnection.prototype.addEventListener = function (event, listener) {
  1091. this.xmpp.addListener(event, listener);
  1092. }
  1093. /**
  1094. * Unsubscribes the passed handler.
  1095. * @param event {JitsiConnectionEvents} the connection event.
  1096. * @param listener {Function} the function that will receive the event
  1097. */
  1098. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  1099. this.xmpp.removeListener(event, listener);
  1100. }
  1101. module.exports = JitsiConnection;
  1102. },{"./JitsiConference":1,"./modules/xmpp/xmpp":43}],5:[function(require,module,exports){
  1103. /**
  1104. * Enumeration with the errors for the connection.
  1105. * @type {{string: string}}
  1106. */
  1107. var JitsiConnectionErrors = {
  1108. /**
  1109. * Indicates that a password is required in order to join the conference.
  1110. */
  1111. PASSWORD_REQUIRED: "connection.passwordRequired",
  1112. /**
  1113. * Indicates that a connection error occurred when trying to join a
  1114. * conference.
  1115. */
  1116. CONNECTION_ERROR: "connection.connectionError",
  1117. /**
  1118. * Not specified errors.
  1119. */
  1120. OTHER_ERROR: "connection.otherError"
  1121. };
  1122. module.exports = JitsiConnectionErrors;
  1123. },{}],6:[function(require,module,exports){
  1124. /**
  1125. * Enumeration with the events for the connection.
  1126. * @type {{string: string}}
  1127. */
  1128. var JitsiConnnectionEvents = {
  1129. /**
  1130. * Indicates that the connection has been failed for some reason.
  1131. */
  1132. CONNECTION_FAILED: "connection.connectionFailed",
  1133. /**
  1134. * Indicates that the connection has been established.
  1135. */
  1136. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  1137. /**
  1138. * Indicates that the connection has been disconnected.
  1139. */
  1140. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  1141. /**
  1142. * Indicates that the perfomed action cannot be executed because the
  1143. * connection is not in the correct state(connected, disconnected, etc.)
  1144. */
  1145. WRONG_STATE: "connection.wrongState"
  1146. };
  1147. module.exports = JitsiConnnectionEvents;
  1148. },{}],7:[function(require,module,exports){
  1149. var JitsiConnection = require("./JitsiConnection");
  1150. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  1151. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  1152. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  1153. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  1154. var JitsiTrackEvents = require("./JitsiTrackEvents");
  1155. var JitsiTrackErrors = require("./JitsiTrackErrors");
  1156. var Logger = require("jitsi-meet-logger");
  1157. var RTC = require("./modules/RTC/RTC");
  1158. var Statistics = require("./modules/statistics/statistics");
  1159. var Resolutions = require("./service/RTC/Resolutions");
  1160. function getLowerResolution(resolution) {
  1161. if(!Resolutions[resolution])
  1162. return null;
  1163. var order = Resolutions[resolution].order;
  1164. var res = null;
  1165. var resName = null;
  1166. for(var i in Resolutions) {
  1167. var tmp = Resolutions[i];
  1168. if (!res || (res.order < tmp.order && tmp.order < order)) {
  1169. resName = i;
  1170. res = tmp;
  1171. }
  1172. }
  1173. return resName;
  1174. }
  1175. /**
  1176. * Namespace for the interface of Jitsi Meet Library.
  1177. */
  1178. var LibJitsiMeet = {
  1179. JitsiConnection: JitsiConnection,
  1180. events: {
  1181. conference: JitsiConferenceEvents,
  1182. connection: JitsiConnectionEvents,
  1183. track: JitsiTrackEvents
  1184. },
  1185. errors: {
  1186. conference: JitsiConferenceErrors,
  1187. connection: JitsiConnectionErrors,
  1188. track: JitsiTrackErrors
  1189. },
  1190. logLevels: Logger.levels,
  1191. /**
  1192. * Array of functions that will receive the GUM error.
  1193. */
  1194. _gumFailedHandler: [],
  1195. init: function (options) {
  1196. return RTC.init(options || {});
  1197. },
  1198. /**
  1199. * Returns whether the desktop sharing is enabled or not.
  1200. * @returns {boolean}
  1201. */
  1202. isDesktopSharingEnabled: function () {
  1203. return RTC.isDesktopSharingEnabled();
  1204. },
  1205. setLogLevel: function (level) {
  1206. Logger.setLogLevel(level);
  1207. },
  1208. /**
  1209. * Creates the media tracks and returns them trough the callback.
  1210. * @param options Object with properties / settings specifying the tracks which should be created.
  1211. * should be created or some additional configurations about resolution for example.
  1212. * @param {Array} options.devices the devices that will be requested
  1213. * @param {string} options.resolution resolution constraints
  1214. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1215. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1216. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1217. * @param {string} options.cameraDeviceId
  1218. * @param {string} options.micDeviceId
  1219. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  1220. * A promise that returns an array of created JitsiTracks if resolved,
  1221. * or a JitsiConferenceError if rejected.
  1222. */
  1223. createLocalTracks: function (options) {
  1224. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  1225. function(tracks) {
  1226. if(!RTC.options.disableAudioLevels)
  1227. for(var i = 0; i < tracks.length; i++) {
  1228. var track = tracks[i];
  1229. var mStream = track.getOriginalStream();
  1230. if(track.getType() === "audio"){
  1231. Statistics.startLocalStats(mStream,
  1232. track.setAudioLevel.bind(track));
  1233. track.addEventListener(
  1234. JitsiTrackEvents.TRACK_STOPPED,
  1235. function(){
  1236. Statistics.stopLocalStats(mStream);
  1237. });
  1238. }
  1239. }
  1240. return tracks;
  1241. }).catch(function (error) {
  1242. this._gumFailedHandler.forEach(function (handler) {
  1243. handler(error);
  1244. });
  1245. Statistics.sendGetUserMediaFailed(error);
  1246. if(error === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
  1247. var oldResolution = options.resolution || '360';
  1248. var newResolution = getLowerResolution(oldResolution);
  1249. if(newResolution === null)
  1250. return Promise.reject(error);
  1251. options.resolution = newResolution;
  1252. return LibJitsiMeet.createLocalTracks(options);
  1253. }
  1254. return Promise.reject(error);
  1255. }.bind(this));
  1256. },
  1257. /**
  1258. * Checks if its possible to enumerate available cameras/micropones.
  1259. * @returns {boolean} true if available, false otherwise.
  1260. */
  1261. isDeviceListAvailable: function () {
  1262. return RTC.isDeviceListAvailable();
  1263. },
  1264. /**
  1265. * Returns true if changing the camera / microphone device is supported and
  1266. * false if not.
  1267. * @returns {boolean} true if available, false otherwise.
  1268. */
  1269. isDeviceChangeAvailable: function () {
  1270. return RTC.isDeviceChangeAvailable();
  1271. },
  1272. enumerateDevices: function (callback) {
  1273. RTC.enumerateDevices(callback);
  1274. }
  1275. };
  1276. //Setups the promise object.
  1277. window.Promise = window.Promise || require("es6-promise").Promise;
  1278. module.exports = LibJitsiMeet;
  1279. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":25,"./service/RTC/Resolutions":133,"es6-promise":47,"jitsi-meet-logger":49}],8:[function(require,module,exports){
  1280. /* global Strophe */
  1281. /**
  1282. * Represents a participant in (a member of) a conference.
  1283. */
  1284. function JitsiParticipant(jid, conference, displayName){
  1285. this._jid = jid;
  1286. this._id = Strophe.getResourceFromJid(jid);
  1287. this._conference = conference;
  1288. this._displayName = displayName;
  1289. this._supportsDTMF = false;
  1290. this._tracks = [];
  1291. this._role = 'none';
  1292. }
  1293. /**
  1294. * @returns {JitsiConference} The conference that this participant belongs to.
  1295. */
  1296. JitsiParticipant.prototype.getConference = function() {
  1297. return this._conference;
  1298. };
  1299. /**
  1300. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1301. */
  1302. JitsiParticipant.prototype.getTracks = function() {
  1303. return this._tracks;
  1304. };
  1305. /**
  1306. * @returns {String} The ID of this participant.
  1307. */
  1308. JitsiParticipant.prototype.getId = function() {
  1309. return this._id;
  1310. };
  1311. /**
  1312. * @returns {String} The JID of this participant.
  1313. */
  1314. JitsiParticipant.prototype.getJid = function() {
  1315. return this._jid;
  1316. };
  1317. /**
  1318. * @returns {String} The human-readable display name of this participant.
  1319. */
  1320. JitsiParticipant.prototype.getDisplayName = function() {
  1321. return this._displayName;
  1322. };
  1323. /**
  1324. * @returns {Boolean} Whether this participant is a moderator or not.
  1325. */
  1326. JitsiParticipant.prototype.isModerator = function() {
  1327. return this._role === 'moderator';
  1328. };
  1329. // Gets a link to an etherpad instance advertised by the participant?
  1330. //JitsiParticipant.prototype.getEtherpad = function() {
  1331. //
  1332. //}
  1333. /*
  1334. * @returns {Boolean} Whether this participant has muted their audio.
  1335. */
  1336. JitsiParticipant.prototype.isAudioMuted = function() {
  1337. return this.getTracks().reduce(function (track, isAudioMuted) {
  1338. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1339. }, true);
  1340. };
  1341. /*
  1342. * @returns {Boolean} Whether this participant has muted their video.
  1343. */
  1344. JitsiParticipant.prototype.isVideoMuted = function() {
  1345. return this.getTracks().reduce(function (track, isVideoMuted) {
  1346. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1347. }, true);
  1348. };
  1349. /*
  1350. * @returns {???} The latest statistics reported by this participant
  1351. * (i.e. info used to populate the GSM bars)
  1352. * TODO: do we expose this or handle it internally?
  1353. */
  1354. JitsiParticipant.prototype.getLatestStats = function() {
  1355. };
  1356. /**
  1357. * @returns {String} The role of this participant.
  1358. */
  1359. JitsiParticipant.prototype.getRole = function() {
  1360. return this._role;
  1361. };
  1362. /*
  1363. * @returns {Boolean} Whether this participant is
  1364. * the conference focus (i.e. jicofo).
  1365. */
  1366. JitsiParticipant.prototype.isFocus = function() {
  1367. };
  1368. /*
  1369. * @returns {Boolean} Whether this participant is
  1370. * a conference recorder (i.e. jirecon).
  1371. */
  1372. JitsiParticipant.prototype.isRecorder = function() {
  1373. };
  1374. /*
  1375. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1376. */
  1377. JitsiParticipant.prototype.isSipGateway = function() {
  1378. };
  1379. /**
  1380. * @returns {Boolean} Whether this participant
  1381. * is currently sharing their screen.
  1382. */
  1383. JitsiParticipant.prototype.isScreenSharing = function() {
  1384. };
  1385. /**
  1386. * @returns {String} The user agent of this participant
  1387. * (i.e. browser userAgent string).
  1388. */
  1389. JitsiParticipant.prototype.getUserAgent = function() {
  1390. };
  1391. /**
  1392. * Kicks the participant from the conference (requires certain privileges).
  1393. */
  1394. JitsiParticipant.prototype.kick = function() {
  1395. };
  1396. /**
  1397. * Asks this participant to mute themselves.
  1398. */
  1399. JitsiParticipant.prototype.askToMute = function() {
  1400. };
  1401. JitsiParticipant.prototype.supportsDTMF = function () {
  1402. return this._supportsDTMF;
  1403. };
  1404. module.exports = JitsiParticipant;
  1405. },{}],9:[function(require,module,exports){
  1406. module.exports = {
  1407. /**
  1408. * Returns JitsiTrackErrors based on the error object passed by GUM
  1409. * @param error the error
  1410. * @param {Array} devices Array with the requested devices
  1411. */
  1412. parseError: function (error, devices) {
  1413. devices = devices || [];
  1414. if (typeof error == "object" && error.constraintName && error.name
  1415. && (error.name == "ConstraintNotSatisfiedError" ||
  1416. error.name == "OverconstrainedError") &&
  1417. (error.constraintName == "minWidth" ||
  1418. error.constraintName == "maxWidth" ||
  1419. error.constraintName == "minHeight" ||
  1420. error.constraintName == "maxHeight") &&
  1421. devices.indexOf("video") !== -1) {
  1422. return this.UNSUPPORTED_RESOLUTION;
  1423. } else if(typeof error === "object" && error.type === "jitsiError") {
  1424. return error.errorObject;
  1425. } else {
  1426. return this.GENERAL;
  1427. }
  1428. },
  1429. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1430. FIREFOX_EXTENSION_NEEDED: "gum.firefox_extension_needed",
  1431. GENERAL: "gum.general"
  1432. };
  1433. },{}],10:[function(require,module,exports){
  1434. var JitsiTrackEvents = {
  1435. /**
  1436. * A media track mute status was changed.
  1437. */
  1438. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1439. /**
  1440. * Audio levels of a this track was changed.
  1441. */
  1442. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1443. /**
  1444. * The media track was removed to the conference.
  1445. */
  1446. TRACK_STOPPED: "track.stopped"
  1447. };
  1448. module.exports = JitsiTrackEvents;
  1449. },{}],11:[function(require,module,exports){
  1450. (function (__filename){
  1451. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1452. function JitsiDTMFManager (localAudio, peerConnection) {
  1453. var tracks = localAudio._getTracks();
  1454. if (!tracks.length) {
  1455. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1456. }
  1457. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1458. logger.debug("Initialized DTMFSender");
  1459. }
  1460. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1461. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1462. };
  1463. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1464. },{"jitsi-meet-logger":49}],12:[function(require,module,exports){
  1465. (function (__filename){
  1466. /* global config, APP, Strophe */
  1467. // cache datachannels to avoid garbage collection
  1468. // https://code.google.com/p/chromium/issues/detail?id=405545
  1469. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1470. var RTCEvents = require("../../service/RTC/RTCEvents");
  1471. /**
  1472. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1473. * @param peerConnection WebRTC peer connection instance.
  1474. */
  1475. function DataChannels(peerConnection, emitter) {
  1476. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1477. this.eventEmitter = emitter;
  1478. this._dataChannels = [];
  1479. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1480. // Although it's not a requirement to open separate channels from both bridge
  1481. // and peer as single channel can be used for sending and receiving data.
  1482. // So either channel opened by the bridge or the one opened here is enough
  1483. // for communication with the bridge.
  1484. /*var dataChannelOptions =
  1485. {
  1486. reliable: true
  1487. };
  1488. var dataChannel
  1489. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1490. // Can be used only when is in open state
  1491. dataChannel.onopen = function ()
  1492. {
  1493. dataChannel.send("My channel !!!");
  1494. };
  1495. dataChannel.onmessage = function (event)
  1496. {
  1497. var msgData = event.data;
  1498. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1499. };*/
  1500. };
  1501. /**
  1502. * Callback triggered by PeerConnection when new data channel is opened
  1503. * on the bridge.
  1504. * @param event the event info object.
  1505. */
  1506. DataChannels.prototype.onDataChannel = function (event) {
  1507. var dataChannel = event.channel;
  1508. var self = this;
  1509. var lastSelectedEndpoint = null;
  1510. dataChannel.onopen = function () {
  1511. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1512. // Code sample for sending string and/or binary data
  1513. // Sends String message to the bridge
  1514. //dataChannel.send("Hello bridge!");
  1515. // Sends 12 bytes binary message to the bridge
  1516. //dataChannel.send(new ArrayBuffer(12));
  1517. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1518. // when the data channel becomes available, tell the bridge about video
  1519. // selections so that it can do adaptive simulcast,
  1520. // we want the notification to trigger even if userJid is undefined,
  1521. // or null.
  1522. self.handleSelectedEndpointEvent(self.lastSelectedEndpoint);
  1523. };
  1524. dataChannel.onerror = function (error) {
  1525. logger.error("Data Channel Error:", error, dataChannel);
  1526. };
  1527. dataChannel.onmessage = function (event) {
  1528. var data = event.data;
  1529. // JSON
  1530. var obj;
  1531. try {
  1532. obj = JSON.parse(data);
  1533. }
  1534. catch (e) {
  1535. logger.error(
  1536. "Failed to parse data channel message as JSON: ",
  1537. data,
  1538. dataChannel);
  1539. }
  1540. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1541. var colibriClass = obj.colibriClass;
  1542. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1543. // Endpoint ID from the Videobridge.
  1544. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1545. logger.info(
  1546. "Data channel new dominant speaker event: ",
  1547. dominantSpeakerEndpoint);
  1548. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1549. }
  1550. else if ("InLastNChangeEvent" === colibriClass) {
  1551. var oldValue = obj.oldValue;
  1552. var newValue = obj.newValue;
  1553. // Make sure that oldValue and newValue are of type boolean.
  1554. var type;
  1555. if ((type = typeof oldValue) !== 'boolean') {
  1556. if (type === 'string') {
  1557. oldValue = (oldValue == "true");
  1558. } else {
  1559. oldValue = new Boolean(oldValue).valueOf();
  1560. }
  1561. }
  1562. if ((type = typeof newValue) !== 'boolean') {
  1563. if (type === 'string') {
  1564. newValue = (newValue == "true");
  1565. } else {
  1566. newValue = new Boolean(newValue).valueOf();
  1567. }
  1568. }
  1569. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1570. }
  1571. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1572. // The new/latest list of last-n endpoint IDs.
  1573. var lastNEndpoints = obj.lastNEndpoints;
  1574. // The list of endpoint IDs which are entering the list of
  1575. // last-n at this time i.e. were not in the old list of last-n
  1576. // endpoint IDs.
  1577. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1578. logger.info(
  1579. "Data channel new last-n event: ",
  1580. lastNEndpoints, endpointsEnteringLastN, obj);
  1581. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1582. lastNEndpoints, endpointsEnteringLastN, obj);
  1583. }
  1584. else {
  1585. logger.debug("Data channel JSON-formatted message: ", obj);
  1586. // The received message appears to be appropriately formatted
  1587. // (i.e. is a JSON object which assigns a value to the mandatory
  1588. // property colibriClass) so don't just swallow it, expose it to
  1589. // public consumption.
  1590. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1591. }
  1592. }
  1593. };
  1594. dataChannel.onclose = function () {
  1595. logger.info("The Data Channel closed", dataChannel);
  1596. var idx = self._dataChannels.indexOf(dataChannel);
  1597. if (idx > -1)
  1598. self._dataChannels = self._dataChannels.splice(idx, 1);
  1599. };
  1600. this._dataChannels.push(dataChannel);
  1601. };
  1602. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1603. this.lastSelectedEndpoint = userResource;
  1604. this._onXXXEndpointChanged("selected", userResource);
  1605. }
  1606. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1607. this._onXXXEndpointChanged("pinnned", userResource);
  1608. }
  1609. /**
  1610. * Notifies Videobridge about a change in the value of a specific
  1611. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1612. *
  1613. * @param xxx the name of the endpoint-related property whose value changed
  1614. * @param userResource the new value of the endpoint-related property after the
  1615. * change
  1616. */
  1617. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1618. // Derive the correct words from xxx such as selected and Selected, pinned
  1619. // and Pinned.
  1620. var head = xxx.charAt(0);
  1621. var tail = xxx.substring(1);
  1622. var lower = head.toLowerCase() + tail;
  1623. var upper = head.toUpperCase() + tail;
  1624. // Notify Videobridge about the specified endpoint change.
  1625. console.log(lower + ' endpoint changed: ', userResource);
  1626. this._some(function (dataChannel) {
  1627. if (dataChannel.readyState == 'open') {
  1628. console.log(
  1629. 'sending ' + lower
  1630. + ' endpoint changed notification to the bridge: ',
  1631. userResource);
  1632. var jsonObject = {};
  1633. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1634. jsonObject[lower + "Endpoint"]
  1635. = (userResource ? userResource : null);
  1636. dataChannel.send(JSON.stringify(jsonObject));
  1637. return true;
  1638. }
  1639. });
  1640. }
  1641. DataChannels.prototype._some = function (callback, thisArg) {
  1642. var dataChannels = this._dataChannels;
  1643. if (dataChannels && dataChannels.length !== 0) {
  1644. if (thisArg)
  1645. return dataChannels.some(callback, thisArg);
  1646. else
  1647. return dataChannels.some(callback);
  1648. } else {
  1649. return false;
  1650. }
  1651. }
  1652. module.exports = DataChannels;
  1653. }).call(this,"/modules/RTC/DataChannels.js")
  1654. },{"../../service/RTC/RTCEvents":132,"jitsi-meet-logger":49}],13:[function(require,module,exports){
  1655. var JitsiTrack = require("./JitsiTrack");
  1656. var RTCBrowserType = require("./RTCBrowserType");
  1657. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1658. var RTCUtils = require("./RTCUtils");
  1659. /**
  1660. * Represents a single media track (either audio or video).
  1661. * @constructor
  1662. */
  1663. function JitsiLocalTrack(stream, videoType,
  1664. resolution)
  1665. {
  1666. this.videoType = videoType;
  1667. this.dontFireRemoveEvent = false;
  1668. this.resolution = resolution;
  1669. this.startMuted = false;
  1670. var self = this;
  1671. JitsiTrack.call(this, null, stream,
  1672. function () {
  1673. if(!this.dontFireRemoveEvent)
  1674. this.eventEmitter.emit(
  1675. JitsiTrackEvents.TRACK_STOPPED);
  1676. this.dontFireRemoveEvent = false;
  1677. }.bind(this));
  1678. }
  1679. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1680. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1681. /**
  1682. * Mutes / unmutes the track.
  1683. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1684. */
  1685. JitsiLocalTrack.prototype._setMute = function (mute) {
  1686. if (this.isMuted() === mute) {
  1687. return;
  1688. }
  1689. if(!this.rtc) {
  1690. this.startMuted = mute;
  1691. return;
  1692. }
  1693. var isAudio = this.type === JitsiTrack.AUDIO;
  1694. this.dontFireRemoveEvent = false;
  1695. if ((window.location.protocol != "https:") ||
  1696. (isAudio) || this.videoType === "desktop" ||
  1697. // FIXME FF does not support 'removeStream' method used to mute
  1698. RTCBrowserType.isFirefox()) {
  1699. var tracks = this._getTracks();
  1700. for (var idx = 0; idx < tracks.length; idx++) {
  1701. tracks[idx].enabled = !mute;
  1702. }
  1703. if(isAudio)
  1704. this.rtc.room.setAudioMute(mute);
  1705. else
  1706. this.rtc.room.setVideoMute(mute);
  1707. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1708. } else {
  1709. if (mute) {
  1710. this.dontFireRemoveEvent = true;
  1711. this.rtc.room.removeStream(this.stream, function () {});
  1712. RTCUtils.stopMediaStream(this.stream);
  1713. if(isAudio)
  1714. this.rtc.room.setAudioMute(mute);
  1715. else
  1716. this.rtc.room.setVideoMute(mute);
  1717. this.stream = null;
  1718. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1719. //FIXME: Maybe here we should set the SRC for the containers to something
  1720. } else {
  1721. var self = this;
  1722. RTCUtils.obtainAudioAndVideoPermissions({
  1723. devices: (isAudio ? ["audio"] : ["video"]),
  1724. resolution: self.resolution})
  1725. .then(function (streams) {
  1726. var stream = null;
  1727. for(var i = 0; i < streams.length; i++) {
  1728. stream = streams[i];
  1729. if(stream.type === self.type) {
  1730. self.stream = stream.stream;
  1731. self.videoType = stream.videoType;
  1732. break;
  1733. }
  1734. }
  1735. if(!stream)
  1736. return;
  1737. for(var i = 0; i < self.containers.length; i++)
  1738. {
  1739. RTCUtils.attachMediaStream(
  1740. self.containers[i], self.stream);
  1741. }
  1742. self.rtc.room.addStream(stream.stream,
  1743. function () {
  1744. if(isAudio)
  1745. self.rtc.room.setAudioMute(mute);
  1746. else
  1747. self.rtc.room.setVideoMute(mute);
  1748. self.eventEmitter.emit(
  1749. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1750. });
  1751. });
  1752. }
  1753. }
  1754. }
  1755. /**
  1756. * Stops sending the media track. And removes it from the HTML.
  1757. * NOTE: Works for local tracks only.
  1758. */
  1759. JitsiLocalTrack.prototype.stop = function () {
  1760. if(!this.stream)
  1761. return;
  1762. if(this.rtc)
  1763. this.rtc.room.removeStream(this.stream, function () {});
  1764. RTCUtils.stopMediaStream(this.stream);
  1765. this.detach();
  1766. }
  1767. /**
  1768. * Returns <tt>true</tt> - if the stream is muted
  1769. * and <tt>false</tt> otherwise.
  1770. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1771. * and <tt>false</tt> otherwise.
  1772. */
  1773. JitsiLocalTrack.prototype.isMuted = function () {
  1774. if (!this.stream)
  1775. return true;
  1776. var tracks = [];
  1777. var isAudio = this.type === JitsiTrack.AUDIO;
  1778. if (isAudio) {
  1779. tracks = this.stream.getAudioTracks();
  1780. } else {
  1781. if (!this.isActive())
  1782. return true;
  1783. tracks = this.stream.getVideoTracks();
  1784. }
  1785. for (var idx = 0; idx < tracks.length; idx++) {
  1786. if(tracks[idx].enabled)
  1787. return false;
  1788. }
  1789. return true;
  1790. };
  1791. /**
  1792. * Private method. Updates rtc property of the track.
  1793. * @param rtc the rtc instance.
  1794. */
  1795. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1796. this.rtc = rtc;
  1797. };
  1798. /**
  1799. * Return true;
  1800. */
  1801. JitsiLocalTrack.prototype.isLocal = function () {
  1802. return true;
  1803. }
  1804. module.exports = JitsiLocalTrack;
  1805. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1806. var JitsiTrack = require("./JitsiTrack");
  1807. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1808. /**
  1809. * Represents a single media track (either audio or video).
  1810. * @param RTC the rtc instance.
  1811. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1812. * @param sid sid for the Media Stream
  1813. * @param ssrc ssrc for the Media Stream
  1814. * @param eventEmitter the event emitter
  1815. * @constructor
  1816. */
  1817. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1818. JitsiTrack.call(this, RTC, data.stream,
  1819. function () {
  1820. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1821. }.bind(this), data.type);
  1822. this.rtc = RTC;
  1823. this.sid = sid;
  1824. this.stream = data.stream;
  1825. this.peerjid = data.peerjid;
  1826. this.videoType = data.videoType;
  1827. this.ssrc = ssrc;
  1828. this.muted = false;
  1829. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1830. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1831. this.muted = true;
  1832. }
  1833. }
  1834. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1835. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1836. /**
  1837. * Sets current muted status and fires an events for the change.
  1838. * @param value the muted status.
  1839. */
  1840. JitsiRemoteTrack.prototype.setMute = function (value) {
  1841. if(this.muted === value)
  1842. return;
  1843. this.stream.muted = value;
  1844. this.muted = value;
  1845. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1846. };
  1847. /**
  1848. * Returns the current muted status of the track.
  1849. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1850. */
  1851. JitsiRemoteTrack.prototype.isMuted = function () {
  1852. return this.muted;
  1853. };
  1854. /**
  1855. * Returns the participant id which owns the track.
  1856. * @returns {string} the id of the participants.
  1857. */
  1858. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1859. return Strophe.getResourceFromJid(this.peerjid);
  1860. };
  1861. /**
  1862. * Return false;
  1863. */
  1864. JitsiRemoteTrack.prototype.isLocal = function () {
  1865. return false;
  1866. };
  1867. delete JitsiRemoteTrack.prototype.stop;
  1868. module.exports = JitsiRemoteTrack;
  1869. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1870. var RTCBrowserType = require("./RTCBrowserType");
  1871. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1872. var EventEmitter = require("events");
  1873. var RTC = require("./RTCUtils");
  1874. /**
  1875. * This implements 'onended' callback normally fired by WebRTC after the stream
  1876. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1877. * @param jitsiTrack our track object holding the original WebRTC stream object
  1878. * to which 'onended' handling will be added.
  1879. */
  1880. function implementOnEndedHandling(jitsiTrack) {
  1881. var stream = jitsiTrack.getOriginalStream();
  1882. if(!stream)
  1883. return;
  1884. var originalStop = stream.stop;
  1885. stream.stop = function () {
  1886. originalStop.apply(stream);
  1887. if (jitsiTrack.isActive()) {
  1888. stream.onended();
  1889. }
  1890. };
  1891. }
  1892. /**
  1893. * Adds onended/oninactive handler to a MediaStream.
  1894. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1895. * @param handler the handler
  1896. */
  1897. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1898. if(RTCBrowserType.isTemasysPluginUsed()) {
  1899. // themasys
  1900. //FIXME: Seems that not working properly.
  1901. if(mediaStream.onended) {
  1902. mediaStream.onended = handler;
  1903. } else if(mediaStream.addEventListener) {
  1904. mediaStream.addEventListener('ended', function () {
  1905. handler(mediaStream);
  1906. });
  1907. } else if(mediaStream.attachEvent) {
  1908. mediaStream.attachEvent('ended', function () {
  1909. handler(mediaStream);
  1910. });
  1911. }
  1912. }
  1913. else {
  1914. if(typeof mediaStream.active !== "undefined")
  1915. mediaStream.oninactive = handler;
  1916. else
  1917. mediaStream.onended = handler;
  1918. }
  1919. }
  1920. /**
  1921. * Represents a single media track (either audio or video).
  1922. * @constructor
  1923. * @param rtc the rtc instance
  1924. * @param stream the stream
  1925. * @param streamInactiveHandler the function that will handle
  1926. * onended/oninactive events of the stream.
  1927. * @param type optionally a type can be specified.
  1928. * This is the case where we are creating a dummy track with no stream
  1929. * Currently this happens when a remote side is starting with video muted
  1930. */
  1931. function JitsiTrack(rtc, stream, streamInactiveHandler, type)
  1932. {
  1933. /**
  1934. * Array with the HTML elements that are displaying the streams.
  1935. * @type {Array}
  1936. */
  1937. this.containers = [];
  1938. this.rtc = rtc;
  1939. this.stream = stream;
  1940. this.eventEmitter = new EventEmitter();
  1941. this.audioLevel = -1;
  1942. this.type = type || (this.stream.getVideoTracks().length > 0)?
  1943. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1944. if(this.type == JitsiTrack.AUDIO) {
  1945. this._getTracks = function () {
  1946. return this.stream.getAudioTracks();
  1947. }.bind(this);
  1948. } else {
  1949. this._getTracks = function () {
  1950. return this.stream.getVideoTracks();
  1951. }.bind(this);
  1952. }
  1953. if (RTCBrowserType.isFirefox() && this.stream) {
  1954. implementOnEndedHandling(this);
  1955. }
  1956. if(stream)
  1957. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1958. }
  1959. /**
  1960. * JitsiTrack video type.
  1961. * @type {string}
  1962. */
  1963. JitsiTrack.VIDEO = "video";
  1964. /**
  1965. * JitsiTrack audio type.
  1966. * @type {string}
  1967. */
  1968. JitsiTrack.AUDIO = "audio";
  1969. /**
  1970. * Returns the type (audio or video) of this track.
  1971. */
  1972. JitsiTrack.prototype.getType = function() {
  1973. return this.type;
  1974. };
  1975. /**
  1976. * Check if this is audiotrack.
  1977. */
  1978. JitsiTrack.prototype.isAudioTrack = function () {
  1979. return this.getType() === JitsiTrack.AUDIO;
  1980. };
  1981. /**
  1982. * Check if this is videotrack.
  1983. */
  1984. JitsiTrack.prototype.isVideoTrack = function () {
  1985. return this.getType() === JitsiTrack.VIDEO;
  1986. };
  1987. /**
  1988. * Returns the RTCMediaStream from the browser (?).
  1989. */
  1990. JitsiTrack.prototype.getOriginalStream = function() {
  1991. return this.stream;
  1992. }
  1993. /**
  1994. * Mutes the track.
  1995. */
  1996. JitsiTrack.prototype.mute = function () {
  1997. this._setMute(true);
  1998. }
  1999. /**
  2000. * Unmutes the stream.
  2001. */
  2002. JitsiTrack.prototype.unmute = function () {
  2003. this._setMute(false);
  2004. }
  2005. /**
  2006. * Attaches the MediaStream of this track to an HTML container (?).
  2007. * Adds the container to the list of containers that are displaying the track.
  2008. * @param container the HTML container
  2009. */
  2010. JitsiTrack.prototype.attach = function (container) {
  2011. if(this.stream)
  2012. require("./RTCUtils").attachMediaStream(container, this.stream);
  2013. this.containers.push(container);
  2014. }
  2015. /**
  2016. * Removes the track from the passed HTML container.
  2017. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  2018. */
  2019. JitsiTrack.prototype.detach = function (container) {
  2020. for(var i = 0; i < this.containers.length; i++)
  2021. {
  2022. if(this.containers[i].is(container))
  2023. {
  2024. this.containers.splice(i,1);
  2025. }
  2026. if(!container)
  2027. {
  2028. this.containers[i].find(">video").remove();
  2029. }
  2030. }
  2031. if(container)
  2032. $(container).find(">video").remove();
  2033. }
  2034. /**
  2035. * Stops sending the media track. And removes it from the HTML.
  2036. * NOTE: Works for local tracks only.
  2037. */
  2038. JitsiTrack.prototype.stop = function () {
  2039. }
  2040. /**
  2041. * Returns true if this is a video track and the source of the video is a
  2042. * screen capture as opposed to a camera.
  2043. */
  2044. JitsiTrack.prototype.isScreenSharing = function(){
  2045. }
  2046. /**
  2047. * Returns id of the track.
  2048. * @returns {string} id of the track or null if this is fake track.
  2049. */
  2050. JitsiTrack.prototype._getId = function () {
  2051. var tracks = this.stream.getTracks();
  2052. if(!tracks || tracks.length === 0)
  2053. return null;
  2054. return tracks[0].id;
  2055. };
  2056. /**
  2057. * Returns id of the track.
  2058. * @returns {string} id of the track or null if this is fake track.
  2059. */
  2060. JitsiTrack.prototype.getId = function () {
  2061. return RTC.getStreamID(this.stream);
  2062. };
  2063. /**
  2064. * Checks whether the MediaStream is avtive/not ended.
  2065. * When there is no check for active we don't have information and so
  2066. * will return that stream is active (in case of FF).
  2067. * @returns {boolean} whether MediaStream is active.
  2068. */
  2069. JitsiTrack.prototype.isActive = function () {
  2070. if((typeof this.stream.active !== "undefined"))
  2071. return this.stream.active;
  2072. else
  2073. return true;
  2074. };
  2075. /**
  2076. * Attaches a handler for events(For example - "audio level changed".).
  2077. * All possible event are defined in JitsiTrackEvents.
  2078. * @param eventId the event ID.
  2079. * @param handler handler for the event.
  2080. */
  2081. JitsiTrack.prototype.on = function (eventId, handler) {
  2082. if(this.eventEmitter)
  2083. this.eventEmitter.on(eventId, handler);
  2084. }
  2085. /**
  2086. * Removes event listener
  2087. * @param eventId the event ID.
  2088. * @param [handler] optional, the specific handler to unbind
  2089. */
  2090. JitsiTrack.prototype.off = function (eventId, handler) {
  2091. if(this.eventEmitter)
  2092. this.eventEmitter.removeListener(eventId, handler);
  2093. }
  2094. // Common aliases for event emitter
  2095. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  2096. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  2097. /**
  2098. * Sets the audio level for the stream
  2099. * @param audioLevel the new audio level
  2100. */
  2101. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  2102. if(this.audioLevel !== audioLevel) {
  2103. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  2104. audioLevel);
  2105. this.audioLevel = audioLevel;
  2106. }
  2107. }
  2108. module.exports = JitsiTrack;
  2109. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":45}],16:[function(require,module,exports){
  2110. /* global APP */
  2111. var EventEmitter = require("events");
  2112. var RTCBrowserType = require("./RTCBrowserType");
  2113. var RTCUtils = require("./RTCUtils.js");
  2114. var JitsiTrack = require("./JitsiTrack");
  2115. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  2116. var DataChannels = require("./DataChannels");
  2117. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  2118. var DesktopSharingEventTypes
  2119. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2120. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  2121. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  2122. function createLocalTracks(streams) {
  2123. var newStreams = []
  2124. for (var i = 0; i < streams.length; i++) {
  2125. var localStream = new JitsiLocalTrack(streams[i].stream,
  2126. streams[i].videoType, streams[i].resolution);
  2127. newStreams.push(localStream);
  2128. if (streams[i].isMuted === true)
  2129. localStream.setMute(true);
  2130. }
  2131. return newStreams;
  2132. }
  2133. function RTC(room, options) {
  2134. this.room = room;
  2135. this.localStreams = [];
  2136. //FIXME: we should start removing those streams.
  2137. //FIXME: We should support multiple streams per jid.
  2138. this.remoteStreams = {};
  2139. this.localAudio = null;
  2140. this.localVideo = null;
  2141. this.eventEmitter = new EventEmitter();
  2142. var self = this;
  2143. this.options = options || {};
  2144. room.addPresenceListener("videomuted", function (values, from) {
  2145. if(self.remoteStreams[from]) {
  2146. // If there is no video track, but we receive it is muted,
  2147. // we need to create a dummy track which we will mute, so we can
  2148. // notify interested about the muting
  2149. if(!self.remoteStreams[from][JitsiTrack.VIDEO]) {
  2150. self.createRemoteStream(
  2151. {peerjid:room.roomjid + "/" + from,
  2152. videoType:"camera",
  2153. type:JitsiTrack.VIDEO},
  2154. null, null);
  2155. }
  2156. self.remoteStreams[from][JitsiTrack.VIDEO]
  2157. .setMute(values.value == "true");
  2158. }
  2159. });
  2160. room.addPresenceListener("audiomuted", function (values, from) {
  2161. if(self.remoteStreams[from]) {
  2162. self.remoteStreams[from][JitsiTrack.AUDIO]
  2163. .setMute(values.value == "true");
  2164. }
  2165. });
  2166. }
  2167. /**
  2168. * Creates the local MediaStreams.
  2169. * @param {Object} [options] optional parameters
  2170. * @param {Array} options.devices the devices that will be requested
  2171. * @param {string} options.resolution resolution constraints
  2172. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2173. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2174. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2175. * @param {string} options.cameraDeviceId
  2176. * @param {string} options.micDeviceId
  2177. * @returns {*} Promise object that will receive the new JitsiTracks
  2178. */
  2179. RTC.obtainAudioAndVideoPermissions = function (options) {
  2180. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  2181. }
  2182. RTC.prototype.onIncommingCall = function(event) {
  2183. if(this.options.config.openSctp)
  2184. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  2185. for(var i = 0; i < this.localStreams.length; i++)
  2186. if(this.localStreams[i])
  2187. {
  2188. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  2189. }
  2190. }
  2191. RTC.prototype.selectedEndpoint = function (id) {
  2192. if(this.dataChannels)
  2193. this.dataChannels.handleSelectedEndpointEvent(id);
  2194. }
  2195. RTC.prototype.pinEndpoint = function (id) {
  2196. if(this.dataChannels)
  2197. this.dataChannels.handlePinnedEndpointEvent(id);
  2198. }
  2199. RTC.prototype.addListener = function (type, listener) {
  2200. this.eventEmitter.on(type, listener);
  2201. };
  2202. RTC.prototype.removeListener = function (eventType, listener) {
  2203. this.eventEmitter.removeListener(eventType, listener);
  2204. };
  2205. RTC.addListener = function (eventType, listener) {
  2206. RTCUtils.addListener(eventType, listener);
  2207. }
  2208. RTC.removeListener = function (eventType, listener) {
  2209. RTCUtils.removeListener(eventType, listener)
  2210. }
  2211. RTC.isRTCReady = function () {
  2212. return RTCUtils.isRTCReady();
  2213. }
  2214. RTC.init = function (options) {
  2215. this.options = options || {};
  2216. return RTCUtils.init(this.options);
  2217. }
  2218. RTC.getDeviceAvailability = function () {
  2219. return RTCUtils.getDeviceAvailability();
  2220. }
  2221. RTC.prototype.addLocalStream = function (stream) {
  2222. this.localStreams.push(stream);
  2223. stream._setRTC(this);
  2224. if (stream.type == "audio") {
  2225. this.localAudio = stream;
  2226. } else {
  2227. this.localVideo = stream;
  2228. }
  2229. };
  2230. /**
  2231. * Set mute for all local audio streams attached to the conference.
  2232. * @param value the mute value
  2233. */
  2234. RTC.prototype.setAudioMute = function (value) {
  2235. for(var i = 0; i < this.localStreams.length; i++) {
  2236. var stream = this.localStreams[i];
  2237. if(stream.getType() !== "audio") {
  2238. continue;
  2239. }
  2240. stream._setMute(value);
  2241. }
  2242. }
  2243. RTC.prototype.removeLocalStream = function (track) {
  2244. var pos = this.localStreams.indexOf(track);
  2245. if (pos > -1) {
  2246. this.localStreams.splice(pos, 1);
  2247. }
  2248. };
  2249. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  2250. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  2251. if(!data.peerjid)
  2252. return;
  2253. var jid = Strophe.getResourceFromJid(data.peerjid);
  2254. if(!this.remoteStreams[jid]) {
  2255. this.remoteStreams[jid] = {};
  2256. }
  2257. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  2258. return remoteStream;
  2259. };
  2260. RTC.getPCConstraints = function () {
  2261. return RTCUtils.pc_constraints;
  2262. };
  2263. RTC.attachMediaStream = function (elSelector, stream) {
  2264. RTCUtils.attachMediaStream(elSelector, stream);
  2265. };
  2266. RTC.getStreamID = function (stream) {
  2267. return RTCUtils.getStreamID(stream);
  2268. };
  2269. RTC.getVideoSrc = function (element) {
  2270. return RTCUtils.getVideoSrc(element);
  2271. };
  2272. /**
  2273. * Returns true if retrieving the the list of input devices is supported and
  2274. * false if not.
  2275. */
  2276. RTC.isDeviceListAvailable = function () {
  2277. return RTCUtils.isDeviceListAvailable();
  2278. };
  2279. /**
  2280. * Returns true if changing the camera / microphone device is supported and
  2281. * false if not.
  2282. */
  2283. RTC.isDeviceChangeAvailable = function () {
  2284. return RTCUtils.isDeviceChangeAvailable();
  2285. }
  2286. /**
  2287. * Allows to receive list of available cameras/microphones.
  2288. * @param {function} callback would receive array of devices as an argument
  2289. */
  2290. RTC.enumerateDevices = function (callback) {
  2291. RTCUtils.enumerateDevices(callback);
  2292. };
  2293. RTC.setVideoSrc = function (element, src) {
  2294. RTCUtils.setVideoSrc(element, src);
  2295. };
  2296. /**
  2297. * A method to handle stopping of the stream.
  2298. * One point to handle the differences in various implementations.
  2299. * @param mediaStream MediaStream object to stop.
  2300. */
  2301. RTC.stopMediaStream = function (mediaStream) {
  2302. RTCUtils.stopMediaStream(mediaStream);
  2303. };
  2304. /**
  2305. * Returns whether the desktop sharing is enabled or not.
  2306. * @returns {boolean}
  2307. */
  2308. RTC.isDesktopSharingEnabled = function () {
  2309. return RTCUtils.isDesktopSharingEnabled();
  2310. }
  2311. RTC.prototype.getVideoElementName = function () {
  2312. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  2313. };
  2314. RTC.prototype.dispose = function() {
  2315. };
  2316. RTC.prototype.switchVideoStreams = function (newStream) {
  2317. this.localVideo.stream = newStream;
  2318. this.localStreams = [];
  2319. //in firefox we have only one stream object
  2320. if (this.localAudio.getOriginalStream() != newStream)
  2321. this.localStreams.push(this.localAudio);
  2322. this.localStreams.push(this.localVideo);
  2323. };
  2324. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2325. if(!jid)
  2326. return;
  2327. var resource = Strophe.getResourceFromJid(jid);
  2328. if(this.remoteStreams[resource] && this.remoteStreams[resource][JitsiTrack.AUDIO])
  2329. this.remoteStreams[resource][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2330. }
  2331. module.exports = RTC;
  2332. },{"../../service/RTC/MediaStreamTypes":131,"../../service/RTC/RTCEvents.js":132,"../../service/desktopsharing/DesktopSharingEventTypes":135,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":45}],17:[function(require,module,exports){
  2333. var currentBrowser;
  2334. var browserVersion;
  2335. var isAndroid;
  2336. var RTCBrowserType = {
  2337. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2338. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2339. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2340. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2341. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2342. getBrowserType: function () {
  2343. return currentBrowser;
  2344. },
  2345. isChrome: function () {
  2346. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2347. },
  2348. isOpera: function () {
  2349. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2350. },
  2351. isFirefox: function () {
  2352. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2353. },
  2354. isIExplorer: function () {
  2355. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2356. },
  2357. isSafari: function () {
  2358. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2359. },
  2360. isTemasysPluginUsed: function () {
  2361. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2362. },
  2363. getFirefoxVersion: function () {
  2364. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2365. },
  2366. getChromeVersion: function () {
  2367. return RTCBrowserType.isChrome() ? browserVersion : null;
  2368. },
  2369. usesPlanB: function() {
  2370. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2371. RTCBrowserType.isTemasysPluginUsed();
  2372. },
  2373. usesUnifiedPlan: function() {
  2374. return RTCBrowserType.isFirefox();
  2375. },
  2376. /**
  2377. * Whether the browser is running on an android device.
  2378. */
  2379. isAndroid: function() {
  2380. return isAndroid;
  2381. }
  2382. // Add version getters for other browsers when needed
  2383. };
  2384. // detectOpera() must be called before detectChrome() !!!
  2385. // otherwise Opera wil be detected as Chrome
  2386. function detectChrome() {
  2387. if (navigator.webkitGetUserMedia) {
  2388. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2389. var userAgent = navigator.userAgent.toLowerCase();
  2390. // We can assume that user agent is chrome, because it's
  2391. // enforced when 'ext' streaming method is set
  2392. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2393. console.log("This appears to be Chrome, ver: " + ver);
  2394. return ver;
  2395. }
  2396. return null;
  2397. }
  2398. function detectOpera() {
  2399. var userAgent = navigator.userAgent;
  2400. if (userAgent.match(/Opera|OPR/)) {
  2401. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2402. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2403. console.info("This appears to be Opera, ver: " + version);
  2404. return version;
  2405. }
  2406. return null;
  2407. }
  2408. function detectFirefox() {
  2409. if (navigator.mozGetUserMedia) {
  2410. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2411. var version = parseInt(
  2412. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2413. console.log('This appears to be Firefox, ver: ' + version);
  2414. return version;
  2415. }
  2416. return null;
  2417. }
  2418. function detectSafari() {
  2419. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2420. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2421. console.info("This appears to be Safari");
  2422. // FIXME detect Safari version when needed
  2423. return 1;
  2424. }
  2425. return null;
  2426. }
  2427. function detectIE() {
  2428. var version;
  2429. var ua = window.navigator.userAgent;
  2430. var msie = ua.indexOf('MSIE ');
  2431. if (msie > 0) {
  2432. // IE 10 or older => return version number
  2433. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2434. }
  2435. var trident = ua.indexOf('Trident/');
  2436. if (!version && trident > 0) {
  2437. // IE 11 => return version number
  2438. var rv = ua.indexOf('rv:');
  2439. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2440. }
  2441. var edge = ua.indexOf('Edge/');
  2442. if (!version && edge > 0) {
  2443. // IE 12 => return version number
  2444. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2445. }
  2446. if (version) {
  2447. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2448. console.info("This appears to be IExplorer, ver: " + version);
  2449. }
  2450. return version;
  2451. }
  2452. function detectBrowser() {
  2453. var version;
  2454. var detectors = [
  2455. detectOpera,
  2456. detectChrome,
  2457. detectFirefox,
  2458. detectIE,
  2459. detectSafari
  2460. ];
  2461. // Try all browser detectors
  2462. for (var i = 0; i < detectors.length; i++) {
  2463. version = detectors[i]();
  2464. if (version)
  2465. return version;
  2466. }
  2467. console.warn("Browser type defaults to Safari ver 1");
  2468. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2469. return 1;
  2470. }
  2471. browserVersion = detectBrowser();
  2472. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2473. module.exports = RTCBrowserType;
  2474. },{}],18:[function(require,module,exports){
  2475. (function (__filename){
  2476. /* global config, require, attachMediaStream, getUserMedia,
  2477. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2478. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2479. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2480. */
  2481. /* jshint -W101 */
  2482. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2483. var RTCBrowserType = require("./RTCBrowserType");
  2484. var Resolutions = require("../../service/RTC/Resolutions");
  2485. var RTCEvents = require("../../service/RTC/RTCEvents");
  2486. var AdapterJS = require("./adapter.screenshare");
  2487. var SDPUtil = require("../xmpp/SDPUtil");
  2488. var EventEmitter = require("events");
  2489. var screenObtainer = require("./ScreenObtainer");
  2490. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2491. var eventEmitter = new EventEmitter();
  2492. var devices = {
  2493. audio: true,
  2494. video: true
  2495. };
  2496. var rtcReady = false;
  2497. function setResolutionConstraints(constraints, resolution) {
  2498. var isAndroid = RTCBrowserType.isAndroid();
  2499. if (Resolutions[resolution]) {
  2500. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2501. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2502. }
  2503. else if (isAndroid) {
  2504. // FIXME can't remember if the purpose of this was to always request
  2505. // low resolution on Android ? if yes it should be moved up front
  2506. constraints.video.mandatory.minWidth = 320;
  2507. constraints.video.mandatory.minHeight = 240;
  2508. constraints.video.mandatory.maxFrameRate = 15;
  2509. }
  2510. if (constraints.video.mandatory.minWidth)
  2511. constraints.video.mandatory.maxWidth =
  2512. constraints.video.mandatory.minWidth;
  2513. if (constraints.video.mandatory.minHeight)
  2514. constraints.video.mandatory.maxHeight =
  2515. constraints.video.mandatory.minHeight;
  2516. }
  2517. /**
  2518. * @param {string[]} um required user media types
  2519. *
  2520. * @param {Object} [options={}] optional parameters
  2521. * @param {string} options.resolution
  2522. * @param {number} options.bandwidth
  2523. * @param {number} options.fps
  2524. * @param {string} options.desktopStream
  2525. * @param {string} options.cameraDeviceId
  2526. * @param {string} options.micDeviceId
  2527. * @param {bool} firefox_fake_device
  2528. */
  2529. function getConstraints(um, options) {
  2530. var constraints = {audio: false, video: false};
  2531. if (um.indexOf('video') >= 0) {
  2532. // same behaviour as true
  2533. constraints.video = { mandatory: {}, optional: [] };
  2534. if (options.cameraDeviceId) {
  2535. constraints.video.optional.push({
  2536. sourceId: options.cameraDeviceId
  2537. });
  2538. }
  2539. constraints.video.optional.push({ googLeakyBucket: true });
  2540. setResolutionConstraints(constraints, options.resolution);
  2541. }
  2542. if (um.indexOf('audio') >= 0) {
  2543. if (!RTCBrowserType.isFirefox()) {
  2544. // same behaviour as true
  2545. constraints.audio = { mandatory: {}, optional: []};
  2546. if (options.micDeviceId) {
  2547. constraints.audio.optional.push({
  2548. sourceId: options.micDeviceId
  2549. });
  2550. }
  2551. // if it is good enough for hangouts...
  2552. constraints.audio.optional.push(
  2553. {googEchoCancellation: true},
  2554. {googAutoGainControl: true},
  2555. {googNoiseSupression: true},
  2556. {googHighpassFilter: true},
  2557. {googNoisesuppression2: true},
  2558. {googEchoCancellation2: true},
  2559. {googAutoGainControl2: true}
  2560. );
  2561. } else {
  2562. if (options.micDeviceId) {
  2563. constraints.audio = {
  2564. mandatory: {},
  2565. optional: [{
  2566. sourceId: options.micDeviceId
  2567. }]};
  2568. } else {
  2569. constraints.audio = true;
  2570. }
  2571. }
  2572. }
  2573. if (um.indexOf('screen') >= 0) {
  2574. if (RTCBrowserType.isChrome()) {
  2575. constraints.video = {
  2576. mandatory: {
  2577. chromeMediaSource: "screen",
  2578. googLeakyBucket: true,
  2579. maxWidth: window.screen.width,
  2580. maxHeight: window.screen.height,
  2581. maxFrameRate: 3
  2582. },
  2583. optional: []
  2584. };
  2585. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2586. constraints.video = {
  2587. optional: [
  2588. {
  2589. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2590. }
  2591. ]
  2592. };
  2593. } else if (RTCBrowserType.isFirefox()) {
  2594. constraints.video = {
  2595. mozMediaSource: "window",
  2596. mediaSource: "window"
  2597. };
  2598. } else {
  2599. logger.error(
  2600. "'screen' WebRTC media source is supported only in Chrome" +
  2601. " and with Temasys plugin");
  2602. }
  2603. }
  2604. if (um.indexOf('desktop') >= 0) {
  2605. constraints.video = {
  2606. mandatory: {
  2607. chromeMediaSource: "desktop",
  2608. chromeMediaSourceId: options.desktopStream,
  2609. googLeakyBucket: true,
  2610. maxWidth: window.screen.width,
  2611. maxHeight: window.screen.height,
  2612. maxFrameRate: 3
  2613. },
  2614. optional: []
  2615. };
  2616. }
  2617. if (options.bandwidth) {
  2618. if (!constraints.video) {
  2619. //same behaviour as true
  2620. constraints.video = {mandatory: {}, optional: []};
  2621. }
  2622. constraints.video.optional.push({bandwidth: options.bandwidth});
  2623. }
  2624. if (options.fps) {
  2625. // for some cameras it might be necessary to request 30fps
  2626. // so they choose 30fps mjpg over 10fps yuy2
  2627. if (!constraints.video) {
  2628. // same behaviour as true;
  2629. constraints.video = {mandatory: {}, optional: []};
  2630. }
  2631. constraints.video.mandatory.minFrameRate = options.fps;
  2632. }
  2633. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2634. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2635. // this later can be a problem with some of the tests
  2636. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2637. {
  2638. // seems to be fixed now, removing this experimental fix, as having
  2639. // multiple audio tracks brake the tests
  2640. //constraints.audio = true;
  2641. constraints.fake = true;
  2642. }
  2643. return constraints;
  2644. }
  2645. function setAvailableDevices(um, available) {
  2646. if (um.indexOf("video") != -1) {
  2647. devices.video = available;
  2648. }
  2649. if (um.indexOf("audio") != -1) {
  2650. devices.audio = available;
  2651. }
  2652. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2653. }
  2654. // In case of IE we continue from 'onReady' callback
  2655. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2656. // once it is initialized.
  2657. function onReady (options, GUM) {
  2658. rtcReady = true;
  2659. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2660. screenObtainer.init(options, GUM);
  2661. }
  2662. /**
  2663. * Apply function with arguments if function exists.
  2664. * Do nothing if function not provided.
  2665. * @param {function} [fn] function to apply
  2666. * @param {Array} [args=[]] arguments for function
  2667. */
  2668. function maybeApply(fn, args) {
  2669. if (fn) {
  2670. fn.apply(null, args || []);
  2671. }
  2672. }
  2673. var getUserMediaStatus = {
  2674. initialized: false,
  2675. callbacks: []
  2676. };
  2677. /**
  2678. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2679. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2680. * @param {Function} getUserMedia native function
  2681. * @returns {Function} wrapped function
  2682. */
  2683. function wrapGetUserMedia(getUserMedia) {
  2684. return function (constraints, successCallback, errorCallback) {
  2685. getUserMedia(constraints, function (stream) {
  2686. maybeApply(successCallback, [stream]);
  2687. if (!getUserMediaStatus.initialized) {
  2688. getUserMediaStatus.initialized = true;
  2689. getUserMediaStatus.callbacks.forEach(function (callback) {
  2690. callback();
  2691. });
  2692. getUserMediaStatus.callbacks.length = 0;
  2693. }
  2694. }, function (error) {
  2695. maybeApply(errorCallback, [error]);
  2696. });
  2697. };
  2698. }
  2699. /**
  2700. * Create stub device which equals to auto selected device.
  2701. * @param {string} kind if that should be `audio` or `video` device
  2702. * @returns {Object} stub device description in `enumerateDevices` format
  2703. */
  2704. function createAutoDeviceInfo(kind) {
  2705. return {
  2706. facing: null,
  2707. label: 'Auto',
  2708. kind: kind,
  2709. deviceId: '',
  2710. groupId: null
  2711. };
  2712. }
  2713. /**
  2714. * Execute function after getUserMedia was executed at least once.
  2715. * @param {Function} callback function to execute after getUserMedia
  2716. */
  2717. function afterUserMediaInitialized(callback) {
  2718. if (getUserMediaStatus.initialized) {
  2719. callback();
  2720. } else {
  2721. getUserMediaStatus.callbacks.push(callback);
  2722. }
  2723. }
  2724. /**
  2725. * Wrapper function which makes enumerateDevices to wait
  2726. * until someone executes getUserMedia first time.
  2727. * @param {Function} enumerateDevices native function
  2728. * @returns {Funtion} wrapped function
  2729. */
  2730. function wrapEnumerateDevices(enumerateDevices) {
  2731. return function (callback) {
  2732. // enumerate devices only after initial getUserMedia
  2733. afterUserMediaInitialized(function () {
  2734. enumerateDevices().then(function (devices) {
  2735. //add auto devices
  2736. devices.unshift(
  2737. createAutoDeviceInfo('audioinput'),
  2738. createAutoDeviceInfo('videoinput')
  2739. );
  2740. callback(devices);
  2741. }, function (err) {
  2742. console.error('cannot enumerate devices: ', err);
  2743. // return only auto devices
  2744. callback([createAutoDeviceInfo('audioInput'),
  2745. createAutoDeviceInfo('videoinput')]);
  2746. });
  2747. });
  2748. };
  2749. }
  2750. /**
  2751. * Use old MediaStreamTrack to get devices list and
  2752. * convert it to enumerateDevices format.
  2753. * @param {Function} callback function to call when received devices list.
  2754. */
  2755. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2756. MediaStreamTrack.getSources(function (sources) {
  2757. var devices = sources.map(function (source) {
  2758. var kind = (source.kind || '').toLowerCase();
  2759. return {
  2760. facing: source.facing || null,
  2761. label: source.label,
  2762. kind: kind ? kind + 'input': null,
  2763. deviceId: source.id,
  2764. groupId: source.groupId || null
  2765. };
  2766. });
  2767. //add auto devices
  2768. devices.unshift(
  2769. createAutoDeviceInfo('audioinput'),
  2770. createAutoDeviceInfo('videoinput')
  2771. );
  2772. callback(devices);
  2773. });
  2774. }
  2775. function obtainDevices(options) {
  2776. if(!options.devices || options.devices.length === 0) {
  2777. return options.successCallback(options.streams || {});
  2778. }
  2779. var device = options.devices.splice(0, 1);
  2780. var devices = [];
  2781. devices.push(device);
  2782. options.deviceGUM[device](function (stream) {
  2783. options.streams = options.streams || {};
  2784. options.streams[device] = stream;
  2785. obtainDevices(options);
  2786. },
  2787. function (error) {
  2788. Object.keys(options.streams).forEach(function(device) {
  2789. RTCUtils.stopMediaStream(options.streams[device]);
  2790. });
  2791. logger.error(
  2792. "failed to obtain " + device + " stream - stop", error);
  2793. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  2794. });
  2795. }
  2796. /**
  2797. * Handles the newly created Media Streams.
  2798. * @param streams the new Media Streams
  2799. * @param resolution the resolution of the video streams
  2800. * @returns {*[]} object that describes the new streams
  2801. */
  2802. function handleLocalStream(streams, resolution) {
  2803. var audioStream, videoStream, desktopStream, res = [];
  2804. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2805. // an object with two properties: audioStream, videoStream.
  2806. if (window.webkitMediaStream) {
  2807. var audioVideo = streams.audioVideo;
  2808. if (audioVideo) {
  2809. var audioTracks = audioVideo.getAudioTracks();
  2810. if(audioTracks.length) {
  2811. audioStream = new webkitMediaStream();
  2812. for (var i = 0; i < audioTracks.length; i++) {
  2813. audioStream.addTrack(audioTracks[i]);
  2814. }
  2815. }
  2816. var videoTracks = audioVideo.getVideoTracks();
  2817. if(videoTracks.length) {
  2818. videoStream = new webkitMediaStream();
  2819. for (var j = 0; j < videoTracks.length; j++) {
  2820. videoStream.addTrack(videoTracks[j]);
  2821. }
  2822. }
  2823. }
  2824. if (streams && streams.desktopStream)
  2825. desktopStream = streams.desktopStream;
  2826. }
  2827. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2828. if (streams && streams.audio)
  2829. audioStream = streams.audio;
  2830. if (streams && streams.video)
  2831. videoStream = streams.video;
  2832. if(streams && streams.desktop)
  2833. desktopStream = streams.desktop;
  2834. }
  2835. if (desktopStream)
  2836. res.push({stream: desktopStream,
  2837. type: "video", videoType: "desktop"});
  2838. if(audioStream)
  2839. res.push({stream: audioStream, type: "audio", videoType: null});
  2840. if(videoStream)
  2841. res.push({stream: videoStream, type: "video", videoType: "camera",
  2842. resolution: resolution});
  2843. return res;
  2844. }
  2845. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2846. var RTCUtils = {
  2847. init: function (options) {
  2848. return new Promise(function(resolve, reject) {
  2849. if (RTCBrowserType.isFirefox()) {
  2850. var FFversion = RTCBrowserType.getFirefoxVersion();
  2851. if (FFversion < 40) {
  2852. logger.error(
  2853. "Firefox version too old: " + FFversion +
  2854. ". Required >= 40.");
  2855. reject(new Error("Firefox version too old: " + FFversion +
  2856. ". Required >= 40."));
  2857. return;
  2858. }
  2859. this.peerconnection = mozRTCPeerConnection;
  2860. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2861. this.enumerateDevices = wrapEnumerateDevices(
  2862. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2863. );
  2864. this.pc_constraints = {};
  2865. this.attachMediaStream = function (element, stream) {
  2866. // srcObject is being standardized and FF will eventually
  2867. // support that unprefixed. FF also supports the
  2868. // "element.src = URL.createObjectURL(...)" combo, but that
  2869. // will be deprecated in favour of srcObject.
  2870. //
  2871. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2872. // https://github.com/webrtc/samples/issues/302
  2873. if (!element[0])
  2874. return;
  2875. element[0].mozSrcObject = stream;
  2876. element[0].play();
  2877. };
  2878. this.getStreamID = function (stream) {
  2879. var id = stream.id;
  2880. if (!id) {
  2881. var tracks = stream.getVideoTracks();
  2882. if (!tracks || tracks.length === 0) {
  2883. tracks = stream.getAudioTracks();
  2884. }
  2885. id = tracks[0].id;
  2886. }
  2887. return SDPUtil.filter_special_chars(id);
  2888. };
  2889. this.getVideoSrc = function (element) {
  2890. if (!element)
  2891. return null;
  2892. return element.mozSrcObject;
  2893. };
  2894. this.setVideoSrc = function (element, src) {
  2895. if (element)
  2896. element.mozSrcObject = src;
  2897. };
  2898. RTCSessionDescription = mozRTCSessionDescription;
  2899. RTCIceCandidate = mozRTCIceCandidate;
  2900. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2901. this.peerconnection = webkitRTCPeerConnection;
  2902. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2903. if (navigator.mediaDevices) {
  2904. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2905. this.enumerateDevices = wrapEnumerateDevices(
  2906. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2907. );
  2908. } else {
  2909. this.getUserMedia = getUserMedia;
  2910. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2911. }
  2912. this.attachMediaStream = function (element, stream) {
  2913. // saves the created url for the stream, so we can reuse it
  2914. // and not keep creating urls
  2915. if (!stream.jitsiObjectURL) {
  2916. stream.jitsiObjectURL
  2917. = webkitURL.createObjectURL(stream);
  2918. }
  2919. element.attr('src', stream.jitsiObjectURL);
  2920. };
  2921. this.getStreamID = function (stream) {
  2922. // streams from FF endpoints have the characters '{' and '}'
  2923. // that make jQuery choke.
  2924. return SDPUtil.filter_special_chars(stream.id);
  2925. };
  2926. this.getVideoSrc = function (element) {
  2927. if (!element)
  2928. return null;
  2929. return element.getAttribute("src");
  2930. };
  2931. this.setVideoSrc = function (element, src) {
  2932. if (element)
  2933. element.setAttribute("src", src);
  2934. };
  2935. // DTLS should now be enabled by default but..
  2936. this.pc_constraints = {'optional': [
  2937. {'DtlsSrtpKeyAgreement': 'true'}
  2938. ]};
  2939. if (options.useIPv6) {
  2940. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2941. this.pc_constraints.optional.push({googIPv6: true});
  2942. }
  2943. if (RTCBrowserType.isAndroid()) {
  2944. this.pc_constraints = {}; // disable DTLS on Android
  2945. }
  2946. if (!webkitMediaStream.prototype.getVideoTracks) {
  2947. webkitMediaStream.prototype.getVideoTracks = function () {
  2948. return this.videoTracks;
  2949. };
  2950. }
  2951. if (!webkitMediaStream.prototype.getAudioTracks) {
  2952. webkitMediaStream.prototype.getAudioTracks = function () {
  2953. return this.audioTracks;
  2954. };
  2955. }
  2956. }
  2957. // Detect IE/Safari
  2958. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2959. //AdapterJS.WebRTCPlugin.setLogLevel(
  2960. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2961. var self = this;
  2962. AdapterJS.webRTCReady(function (isPlugin) {
  2963. self.peerconnection = RTCPeerConnection;
  2964. self.getUserMedia = window.getUserMedia;
  2965. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2966. self.attachMediaStream = function (elSel, stream) {
  2967. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2968. return;
  2969. }
  2970. attachMediaStream(elSel[0], stream);
  2971. };
  2972. self.getStreamID = function (stream) {
  2973. var id = SDPUtil.filter_special_chars(stream.label);
  2974. return id;
  2975. };
  2976. self.getVideoSrc = function (element) {
  2977. if (!element) {
  2978. logger.warn("Attempt to get video SRC of null element");
  2979. return null;
  2980. }
  2981. var children = element.children;
  2982. for (var i = 0; i !== children.length; ++i) {
  2983. if (children[i].name === 'streamId') {
  2984. return children[i].value;
  2985. }
  2986. }
  2987. //logger.info(element.id + " SRC: " + src);
  2988. return null;
  2989. };
  2990. self.setVideoSrc = function (element, src) {
  2991. //logger.info("Set video src: ", element, src);
  2992. if (!src) {
  2993. logger.warn("Not attaching video stream, 'src' is null");
  2994. return;
  2995. }
  2996. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2997. var stream = AdapterJS.WebRTCPlugin.plugin
  2998. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  2999. attachMediaStream(element, stream);
  3000. };
  3001. onReady(options, self.getUserMediaWithConstraints);
  3002. resolve();
  3003. });
  3004. } else {
  3005. try {
  3006. logger.error('Browser does not appear to be WebRTC-capable');
  3007. } catch (e) {
  3008. }
  3009. reject('Browser does not appear to be WebRTC-capable');
  3010. return;
  3011. }
  3012. // Call onReady() if Temasys plugin is not used
  3013. if (!RTCBrowserType.isTemasysPluginUsed()) {
  3014. onReady(options, this.getUserMediaWithConstraints);
  3015. resolve();
  3016. }
  3017. }.bind(this));
  3018. },
  3019. /**
  3020. * @param {string[]} um required user media types
  3021. * @param {function} success_callback
  3022. * @param {Function} failure_callback
  3023. * @param {Object} [options] optional parameters
  3024. * @param {string} options.resolution
  3025. * @param {number} options.bandwidth
  3026. * @param {number} options.fps
  3027. * @param {string} options.desktopStream
  3028. * @param {string} options.cameraDeviceId
  3029. * @param {string} options.micDeviceId
  3030. **/
  3031. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  3032. options = options || {};
  3033. var resolution = options.resolution;
  3034. var constraints = getConstraints(um, options);
  3035. logger.info("Get media constraints", constraints);
  3036. try {
  3037. this.getUserMedia(constraints,
  3038. function (stream) {
  3039. logger.log('onUserMediaSuccess');
  3040. setAvailableDevices(um, true);
  3041. success_callback(stream);
  3042. },
  3043. function (error) {
  3044. setAvailableDevices(um, false);
  3045. logger.warn('Failed to get access to local media. Error ',
  3046. error, constraints);
  3047. if (failure_callback) {
  3048. failure_callback(error, resolution);
  3049. }
  3050. });
  3051. } catch (e) {
  3052. logger.error('GUM failed: ', e);
  3053. if (failure_callback) {
  3054. failure_callback(e);
  3055. }
  3056. }
  3057. },
  3058. /**
  3059. * Creates the local MediaStreams.
  3060. * @param {Object} [options] optional parameters
  3061. * @param {Array} options.devices the devices that will be requested
  3062. * @param {string} options.resolution resolution constraints
  3063. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  3064. * type: "audio" or "video", videoType: "camera" or "desktop"}
  3065. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  3066. * @param {string} options.cameraDeviceId
  3067. * @param {string} options.micDeviceId
  3068. * @returns {*} Promise object that will receive the new JitsiTracks
  3069. */
  3070. obtainAudioAndVideoPermissions: function (options) {
  3071. var self = this;
  3072. options = options || {};
  3073. return new Promise(function (resolve, reject) {
  3074. var successCallback = function (stream) {
  3075. resolve(handleLocalStream(stream, options.resolution));
  3076. };
  3077. options.devices = options.devices || ['audio', 'video'];
  3078. if(!screenObtainer.isSupported()
  3079. && options.devices.indexOf("desktop") !== -1){
  3080. reject(new Error("Desktop sharing is not supported!"));
  3081. }
  3082. if (RTCBrowserType.isFirefox() ||
  3083. RTCBrowserType.isTemasysPluginUsed()) {
  3084. var GUM = function (device, s, e) {
  3085. this.getUserMediaWithConstraints(device, s, e, options);
  3086. };
  3087. var deviceGUM = {
  3088. "audio": GUM.bind(self, ["audio"]),
  3089. "video": GUM.bind(self, ["video"])
  3090. };
  3091. if(screenObtainer.isSupported()){
  3092. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  3093. screenObtainer);
  3094. }
  3095. // With FF/IE we can't split the stream into audio and video because FF
  3096. // doesn't support media stream constructors. So, we need to get the
  3097. // audio stream separately from the video stream using two distinct GUM
  3098. // calls. Not very user friendly :-( but we don't have many other
  3099. // options neither.
  3100. //
  3101. // Note that we pack those 2 streams in a single object and pass it to
  3102. // the successCallback method.
  3103. obtainDevices({
  3104. devices: options.devices,
  3105. streams: [],
  3106. successCallback: successCallback,
  3107. errorCallback: reject,
  3108. deviceGUM: deviceGUM
  3109. });
  3110. } else {
  3111. var hasDesktop = options.devices.indexOf('desktop') > -1;
  3112. if (hasDesktop) {
  3113. options.devices.splice(options.devices.indexOf("desktop"), 1);
  3114. }
  3115. options.resolution = options.resolution || '360';
  3116. if(options.devices.length) {
  3117. this.getUserMediaWithConstraints(
  3118. options.devices,
  3119. function (stream) {
  3120. if((options.devices.indexOf("audio") !== -1 &&
  3121. !stream.getAudioTracks().length) ||
  3122. (options.devices.indexOf("video") !== -1 &&
  3123. !stream.getVideoTracks().length))
  3124. {
  3125. self.stopMediaStream(stream);
  3126. reject(JitsiTrackErrors.parseError(
  3127. new Error("Unable to get the audio and " +
  3128. "video tracks."),
  3129. options.devices));
  3130. return;
  3131. }
  3132. if(hasDesktop) {
  3133. screenObtainer.obtainStream(
  3134. function (desktopStream) {
  3135. successCallback({audioVideo: stream,
  3136. desktopStream: desktopStream});
  3137. }, function (error) {
  3138. self.stopMediaStream(stream);
  3139. reject(
  3140. JitsiTrackErrors.parseError(error,
  3141. options.devices));
  3142. });
  3143. } else {
  3144. successCallback({audioVideo: stream});
  3145. }
  3146. },
  3147. function (error) {
  3148. reject(JitsiTrackErrors.parseError(error,
  3149. options.devices));
  3150. },
  3151. options);
  3152. } else if (hasDesktop) {
  3153. screenObtainer.obtainStream(
  3154. function (stream) {
  3155. successCallback({desktopStream: stream});
  3156. }, function (error) {
  3157. reject(
  3158. JitsiTrackErrors.parseError(error,
  3159. ["desktop"]));
  3160. });
  3161. }
  3162. }
  3163. }.bind(this));
  3164. },
  3165. addListener: function (eventType, listener) {
  3166. eventEmitter.on(eventType, listener);
  3167. },
  3168. removeListener: function (eventType, listener) {
  3169. eventEmitter.removeListener(eventType, listener);
  3170. },
  3171. getDeviceAvailability: function () {
  3172. return devices;
  3173. },
  3174. isRTCReady: function () {
  3175. return rtcReady;
  3176. },
  3177. /**
  3178. * Checks if its possible to enumerate available cameras/micropones.
  3179. * @returns {boolean} true if available, false otherwise.
  3180. */
  3181. isDeviceListAvailable: function () {
  3182. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  3183. if (isEnumerateDevicesAvailable) {
  3184. return true;
  3185. }
  3186. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  3187. },
  3188. /**
  3189. * Returns true if changing the camera / microphone device is supported and
  3190. * false if not.
  3191. */
  3192. isDeviceChangeAvailable: function () {
  3193. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  3194. RTCBrowserType.isTemasysPluginUsed())
  3195. return true;
  3196. return false;
  3197. },
  3198. /**
  3199. * A method to handle stopping of the stream.
  3200. * One point to handle the differences in various implementations.
  3201. * @param mediaStream MediaStream object to stop.
  3202. */
  3203. stopMediaStream: function (mediaStream) {
  3204. mediaStream.getTracks().forEach(function (track) {
  3205. // stop() not supported with IE
  3206. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  3207. track.stop();
  3208. }
  3209. });
  3210. // leave stop for implementation still using it
  3211. if (mediaStream.stop) {
  3212. mediaStream.stop();
  3213. }
  3214. // if we have done createObjectURL, lets clean it
  3215. if (mediaStream.jitsiObjectURL) {
  3216. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  3217. }
  3218. },
  3219. /**
  3220. * Returns whether the desktop sharing is enabled or not.
  3221. * @returns {boolean}
  3222. */
  3223. isDesktopSharingEnabled: function () {
  3224. return screenObtainer.isSupported();
  3225. }
  3226. };
  3227. module.exports = RTCUtils;
  3228. }).call(this,"/modules/RTC/RTCUtils.js")
  3229. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":132,"../../service/RTC/Resolutions":133,"../xmpp/SDPUtil":33,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":45,"jitsi-meet-logger":49}],19:[function(require,module,exports){
  3230. (function (__filename){
  3231. /* global chrome, $, alert */
  3232. /* jshint -W003 */
  3233. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3234. var RTCBrowserType = require("./RTCBrowserType");
  3235. var AdapterJS = require("./adapter.screenshare");
  3236. var DesktopSharingEventTypes
  3237. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3238. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  3239. /**
  3240. * Indicates whether the Chrome desktop sharing extension is installed.
  3241. * @type {boolean}
  3242. */
  3243. var chromeExtInstalled = false;
  3244. /**
  3245. * Indicates whether an update of the Chrome desktop sharing extension is
  3246. * required.
  3247. * @type {boolean}
  3248. */
  3249. var chromeExtUpdateRequired = false;
  3250. /**
  3251. * Whether the jidesha extension for firefox is installed for the domain on
  3252. * which we are running. Null designates an unknown value.
  3253. * @type {null}
  3254. */
  3255. var firefoxExtInstalled = null;
  3256. /**
  3257. * If set to true, detection of an installed firefox extension will be started
  3258. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3259. * user tries to enable screen sharing).
  3260. */
  3261. var reDetectFirefoxExtension = false;
  3262. var GUM = null;
  3263. /**
  3264. * Handles obtaining a stream from a screen capture on different browsers.
  3265. */
  3266. var ScreenObtainer = {
  3267. obtainStream: null,
  3268. /**
  3269. * Initializes the function used to obtain a screen capture
  3270. * (this.obtainStream).
  3271. *
  3272. * If the browser is Chrome, it uses the value of
  3273. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  3274. * decide whether to use the a Chrome extension (if the value is 'ext'),
  3275. * use the "screen" media source (if the value is 'webrtc'),
  3276. * or disable screen capture (if the value is other).
  3277. * Note that for the "screen" media source to work the
  3278. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3279. */
  3280. init: function(options, gum) {
  3281. var obtainDesktopStream = null;
  3282. this.options = options = options || {};
  3283. GUM = gum;
  3284. if (RTCBrowserType.isFirefox())
  3285. initFirefoxExtensionDetection(options);
  3286. // TODO remove this, options.desktopSharing is deprecated.
  3287. var chromeMethod =
  3288. (options.desktopSharingChromeMethod || options.desktopSharing);
  3289. if (RTCBrowserType.isTemasysPluginUsed()) {
  3290. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3291. logger.info("Screensharing not supported by this plugin " +
  3292. "version");
  3293. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3294. logger.info(
  3295. "Screensharing not available with Temasys plugin on" +
  3296. " this site");
  3297. } else {
  3298. obtainDesktopStream = obtainWebRTCScreen;
  3299. logger.info("Using Temasys plugin for desktop sharing");
  3300. }
  3301. } else if (RTCBrowserType.isChrome()) {
  3302. if (chromeMethod == "ext") {
  3303. if (RTCBrowserType.getChromeVersion() >= 34) {
  3304. obtainDesktopStream =
  3305. this.obtainScreenFromExtension;
  3306. logger.info("Using Chrome extension for desktop sharing");
  3307. initChromeExtension(options);
  3308. } else {
  3309. logger.info("Chrome extension not supported until ver 34");
  3310. }
  3311. } else if (chromeMethod == "webrtc") {
  3312. obtainDesktopStream = obtainWebRTCScreen;
  3313. logger.info("Using Chrome WebRTC for desktop sharing");
  3314. }
  3315. } else if (RTCBrowserType.isFirefox()) {
  3316. if (options.desktopSharingFirefoxDisabled) {
  3317. obtainDesktopStream = null;
  3318. } else if (window.location.protocol === "http:"){
  3319. logger.log("Screen sharing is not supported over HTTP. " +
  3320. "Use of HTTPS is required.");
  3321. obtainDesktopStream = null;
  3322. } else {
  3323. obtainDesktopStream = this.obtainScreenOnFirefox;
  3324. }
  3325. }
  3326. if (!obtainDesktopStream) {
  3327. logger.info("Desktop sharing disabled");
  3328. }
  3329. this.obtainStream = obtainDesktopStream;
  3330. },
  3331. /**
  3332. * Checks whether obtaining a screen capture is supported in the current
  3333. * environment.
  3334. * @returns {boolean}
  3335. */
  3336. isSupported: function() {
  3337. return !!this.obtainStream;
  3338. },
  3339. /**
  3340. * Obtains a screen capture stream on Firefox.
  3341. * @param callback
  3342. * @param errorCallback
  3343. */
  3344. obtainScreenOnFirefox:
  3345. function (callback, errorCallback) {
  3346. var self = this;
  3347. var extensionRequired = false;
  3348. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3349. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3350. RTCBrowserType.getFirefoxVersion() <=
  3351. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3352. extensionRequired = true;
  3353. logger.log("Jidesha extension required on firefox version " +
  3354. RTCBrowserType.getFirefoxVersion());
  3355. }
  3356. if (!extensionRequired || firefoxExtInstalled === true) {
  3357. obtainWebRTCScreen(callback, errorCallback);
  3358. return;
  3359. }
  3360. if (reDetectFirefoxExtension) {
  3361. reDetectFirefoxExtension = false;
  3362. initFirefoxExtensionDetection(this.options);
  3363. }
  3364. // Give it some (more) time to initialize, and assume lack of
  3365. // extension if it hasn't.
  3366. if (firefoxExtInstalled === null) {
  3367. window.setTimeout(
  3368. function() {
  3369. if (firefoxExtInstalled === null)
  3370. firefoxExtInstalled = false;
  3371. self.obtainScreenOnFirefox(callback, errorCallback);
  3372. },
  3373. 300
  3374. );
  3375. logger.log("Waiting for detection of jidesha on firefox to " +
  3376. "finish.");
  3377. return;
  3378. }
  3379. // We need an extension and it isn't installed.
  3380. // Make sure we check for the extension when the user clicks again.
  3381. firefoxExtInstalled = null;
  3382. reDetectFirefoxExtension = true;
  3383. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3384. // stuck in 'switching' mode.
  3385. errorCallback({
  3386. type: "jitsiError",
  3387. errorObject: JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED
  3388. });
  3389. },
  3390. /**
  3391. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3392. * 'desktop' stream for returned stream token.
  3393. */
  3394. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3395. var self = this;
  3396. if (chromeExtInstalled) {
  3397. doGetStreamFromExtension(this.options, streamCallback,
  3398. failCallback);
  3399. } else {
  3400. if (chromeExtUpdateRequired) {
  3401. alert(
  3402. 'Jitsi Desktop Streamer requires update. ' +
  3403. 'Changes will take effect after next Chrome restart.');
  3404. }
  3405. chrome.webstore.install(
  3406. getWebStoreInstallUrl(this.options),
  3407. function (arg) {
  3408. logger.log("Extension installed successfully", arg);
  3409. chromeExtInstalled = true;
  3410. // We need to give a moment for the endpoint to become
  3411. // available
  3412. window.setTimeout(function () {
  3413. doGetStreamFromExtension(self.options, streamCallback,
  3414. failCallback);
  3415. }, 500);
  3416. },
  3417. function (arg) {
  3418. logger.log("Failed to install the extension", arg);
  3419. failCallback(arg);
  3420. }
  3421. );
  3422. }
  3423. }
  3424. };
  3425. /**
  3426. * Obtains a desktop stream using getUserMedia.
  3427. * For this to work on Chrome, the
  3428. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3429. *
  3430. * On firefox, the document's domain must be white-listed in the
  3431. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3432. * 'about:config'.
  3433. */
  3434. function obtainWebRTCScreen(streamCallback, failCallback) {
  3435. GUM(
  3436. ['screen'],
  3437. streamCallback,
  3438. failCallback
  3439. );
  3440. }
  3441. /**
  3442. * Constructs inline install URL for Chrome desktop streaming extension.
  3443. * The 'chromeExtensionId' must be defined in options parameter.
  3444. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3445. * @returns {string}
  3446. */
  3447. function getWebStoreInstallUrl(options)
  3448. {
  3449. //TODO remove chromeExtensionId (deprecated)
  3450. return "https://chrome.google.com/webstore/detail/" +
  3451. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3452. }
  3453. /**
  3454. * Checks whether an update of the Chrome extension is required.
  3455. * @param minVersion minimal required version
  3456. * @param extVersion current extension version
  3457. * @returns {boolean}
  3458. */
  3459. function isUpdateRequired(minVersion, extVersion) {
  3460. try {
  3461. var s1 = minVersion.split('.');
  3462. var s2 = extVersion.split('.');
  3463. var len = Math.max(s1.length, s2.length);
  3464. for (var i = 0; i < len; i++) {
  3465. var n1 = 0,
  3466. n2 = 0;
  3467. if (i < s1.length)
  3468. n1 = parseInt(s1[i]);
  3469. if (i < s2.length)
  3470. n2 = parseInt(s2[i]);
  3471. if (isNaN(n1) || isNaN(n2)) {
  3472. return true;
  3473. } else if (n1 !== n2) {
  3474. return n1 > n2;
  3475. }
  3476. }
  3477. // will happen if both versions have identical numbers in
  3478. // their components (even if one of them is longer, has more components)
  3479. return false;
  3480. }
  3481. catch (e) {
  3482. logger.error("Failed to parse extension version", e);
  3483. return true;
  3484. }
  3485. }
  3486. function checkChromeExtInstalled(callback, options) {
  3487. if (!chrome || !chrome.runtime) {
  3488. // No API, so no extension for sure
  3489. callback(false, false);
  3490. return;
  3491. }
  3492. chrome.runtime.sendMessage(
  3493. //TODO: remove chromeExtensionId (deprecated)
  3494. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3495. { getVersion: true },
  3496. function (response) {
  3497. if (!response || !response.version) {
  3498. // Communication failure - assume that no endpoint exists
  3499. logger.warn(
  3500. "Extension not installed?: ", chrome.runtime.lastError);
  3501. callback(false, false);
  3502. return;
  3503. }
  3504. // Check installed extension version
  3505. var extVersion = response.version;
  3506. logger.log('Extension version is: ' + extVersion);
  3507. //TODO: remove minChromeExtVersion (deprecated)
  3508. var updateRequired
  3509. = isUpdateRequired(
  3510. (options.desktopSharingChromeMinExtVersion ||
  3511. options.minChromeExtVersion),
  3512. extVersion);
  3513. callback(!updateRequired, updateRequired);
  3514. }
  3515. );
  3516. }
  3517. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3518. // Sends 'getStream' msg to the extension.
  3519. // Extension id must be defined in the config.
  3520. chrome.runtime.sendMessage(
  3521. //TODO: remove chromeExtensionId (deprecated)
  3522. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3523. {
  3524. getStream: true,
  3525. //TODO: remove desktopSharingSources (deprecated).
  3526. sources: (options.desktopSharingChromeSources ||
  3527. options.desktopSharingSources)
  3528. },
  3529. function (response) {
  3530. if (!response) {
  3531. failCallback(chrome.runtime.lastError);
  3532. return;
  3533. }
  3534. logger.log("Response from extension: " + response);
  3535. if (response.streamId) {
  3536. GUM(
  3537. ['desktop'],
  3538. function (stream) {
  3539. streamCallback(stream);
  3540. },
  3541. failCallback,
  3542. {desktopStream: response.streamId});
  3543. } else {
  3544. failCallback("Extension failed to get the stream");
  3545. }
  3546. }
  3547. );
  3548. }
  3549. /**
  3550. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3551. * config.js to support inline installs. Host site must be selected as main
  3552. * website of published extension.
  3553. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3554. */
  3555. function initInlineInstalls(options)
  3556. {
  3557. $("link[rel=chrome-webstore-item]").attr("href",
  3558. getWebStoreInstallUrl(options));
  3559. }
  3560. function initChromeExtension(options) {
  3561. // Initialize Chrome extension inline installs
  3562. initInlineInstalls(options);
  3563. // Check if extension is installed
  3564. checkChromeExtInstalled(function (installed, updateRequired) {
  3565. chromeExtInstalled = installed;
  3566. chromeExtUpdateRequired = updateRequired;
  3567. logger.info(
  3568. "Chrome extension installed: " + chromeExtInstalled +
  3569. " updateRequired: " + chromeExtUpdateRequired);
  3570. }, options);
  3571. }
  3572. /**
  3573. * Starts the detection of an installed jidesha extension for firefox.
  3574. * @param options supports "desktopSharingFirefoxDisabled",
  3575. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3576. */
  3577. function initFirefoxExtensionDetection(options) {
  3578. if (options.desktopSharingFirefoxDisabled) {
  3579. return;
  3580. }
  3581. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3582. return;
  3583. if (!options.desktopSharingFirefoxExtId) {
  3584. firefoxExtInstalled = false;
  3585. return;
  3586. }
  3587. var img = document.createElement('img');
  3588. img.onload = function(){
  3589. logger.log("Detected firefox screen sharing extension.");
  3590. firefoxExtInstalled = true;
  3591. };
  3592. img.onerror = function(){
  3593. logger.log("Detected lack of firefox screen sharing extension.");
  3594. firefoxExtInstalled = false;
  3595. };
  3596. // The jidesha extension exposes an empty image file under the url:
  3597. // "chrome://EXT_ID/content/DOMAIN.png"
  3598. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3599. // DOMAIN is a domain whitelisted by the extension.
  3600. var src = "chrome://" +
  3601. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3602. "/content/" + document.location.hostname + ".png";
  3603. img.setAttribute('src', src);
  3604. }
  3605. module.exports = ScreenObtainer;
  3606. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3607. },{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":135,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":49}],20:[function(require,module,exports){
  3608. (function (__filename){
  3609. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3610. var console = require("jitsi-meet-logger").getLogger(__filename);
  3611. // Adapter's interface.
  3612. var AdapterJS = AdapterJS || {};
  3613. // Browserify compatibility
  3614. if(typeof exports !== 'undefined') {
  3615. module.exports = AdapterJS;
  3616. }
  3617. AdapterJS.options = AdapterJS.options || {};
  3618. // uncomment to get virtual webcams
  3619. // AdapterJS.options.getAllCams = true;
  3620. // uncomment to prevent the install prompt when the plugin in not yet installed
  3621. // AdapterJS.options.hidePluginInstallPrompt = true;
  3622. // AdapterJS version
  3623. AdapterJS.VERSION = '0.12.3';
  3624. // This function will be called when the WebRTC API is ready to be used
  3625. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3626. // the plugin
  3627. // You may Override this function to synchronise the start of your application
  3628. // with the WebRTC API being ready.
  3629. // If you decide not to override use this synchronisation, it may result in
  3630. // an extensive CPU usage on the plugin start (once per tab loaded)
  3631. // Params:
  3632. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3633. //
  3634. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3635. // The WebRTC API is ready.
  3636. // Override me and do whatever you want here
  3637. };
  3638. // Sets a callback function to be called when the WebRTC interface is ready.
  3639. // The first argument is the function to callback.\
  3640. // Throws an error if the first argument is not a function
  3641. AdapterJS.webRTCReady = function (callback) {
  3642. if (typeof callback !== 'function') {
  3643. throw new Error('Callback provided is not a function');
  3644. }
  3645. if (true === AdapterJS.onwebrtcreadyDone) {
  3646. // All WebRTC interfaces are ready, just call the callback
  3647. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3648. } else {
  3649. // will be triggered automatically when your browser/plugin is ready.
  3650. AdapterJS.onwebrtcready = callback;
  3651. }
  3652. };
  3653. // Plugin namespace
  3654. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3655. // The object to store plugin information
  3656. AdapterJS.WebRTCPlugin.pluginInfo = {
  3657. prefix : 'Tem',
  3658. plugName : 'TemWebRTCPlugin',
  3659. pluginId : 'plugin0',
  3660. type : 'application/x-temwebrtcplugin',
  3661. onload : '__TemWebRTCReady0',
  3662. portalLink : 'http://skylink.io/plugin/',
  3663. downloadLink : null, //set below
  3664. companyName: 'Temasys'
  3665. };
  3666. if(!!navigator.platform.match(/^Mac/i)) {
  3667. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3668. }
  3669. else if(!!navigator.platform.match(/^Win/i)) {
  3670. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3671. }
  3672. AdapterJS.WebRTCPlugin.TAGS = {
  3673. NONE : 'none',
  3674. AUDIO : 'audio',
  3675. VIDEO : 'video'
  3676. };
  3677. // Unique identifier of each opened page
  3678. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3679. // Use this whenever you want to call the plugin.
  3680. AdapterJS.WebRTCPlugin.plugin = null;
  3681. // Set log level for the plugin once it is ready.
  3682. // The different values are
  3683. // This is an asynchronous function that will run when the plugin is ready
  3684. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3685. // Defines webrtc's JS interface according to the plugin's implementation.
  3686. // Define plugin Browsers as WebRTC Interface.
  3687. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3688. // This function detects whether or not a plugin is installed.
  3689. // Checks if Not IE (firefox, for example), else if it's IE,
  3690. // we're running IE and do something. If not it is not supported.
  3691. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3692. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3693. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3694. // Inject the HTML DOM object element into the page.
  3695. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3696. // States of readiness that the plugin goes through when
  3697. // being injected and stated
  3698. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3699. NONE : 0, // no plugin use
  3700. INITIALIZING : 1, // Detected need for plugin
  3701. INJECTING : 2, // Injecting plugin
  3702. INJECTED: 3, // Plugin element injected but not usable yet
  3703. READY: 4 // Plugin ready to be used
  3704. };
  3705. // Current state of the plugin. You cannot use the plugin before this is
  3706. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3707. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3708. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3709. // Used to make sure AdapterJS.onwebrtcready is only called once
  3710. AdapterJS.onwebrtcreadyDone = false;
  3711. // Log levels for the plugin.
  3712. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3713. /*
  3714. Log outputs are prefixed in some cases.
  3715. INFO: Information reported by the plugin.
  3716. ERROR: Errors originating from within the plugin.
  3717. WEBRTC: Error originating from within the libWebRTC library
  3718. */
  3719. // From the least verbose to the most verbose
  3720. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3721. NONE : 'NONE',
  3722. ERROR : 'ERROR',
  3723. WARNING : 'WARNING',
  3724. INFO: 'INFO',
  3725. VERBOSE: 'VERBOSE',
  3726. SENSITIVE: 'SENSITIVE'
  3727. };
  3728. // Does a waiting check before proceeding to load the plugin.
  3729. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3730. // This methid will use an interval to wait for the plugin to be ready.
  3731. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3732. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3733. // This function will be called when plugin is ready. It sends necessary
  3734. // details to the plugin.
  3735. // The function will wait for the document to be ready and the set the
  3736. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3737. // indicating that it can start being requested.
  3738. // This function is not in the IE/Safari condition brackets so that
  3739. // TemPluginLoaded function might be called on Chrome/Firefox.
  3740. // This function is the only private function that is not encapsulated to
  3741. // allow the plugin method to be called.
  3742. __TemWebRTCReady0 = function () {
  3743. if (document.readyState === 'complete') {
  3744. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3745. AdapterJS.maybeThroughWebRTCReady();
  3746. } else {
  3747. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3748. if (document.readyState === 'complete') {
  3749. // TODO: update comments, we wait for the document to be ready
  3750. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3751. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3752. AdapterJS.maybeThroughWebRTCReady();
  3753. }
  3754. }, 100);
  3755. }
  3756. };
  3757. AdapterJS.maybeThroughWebRTCReady = function() {
  3758. if (!AdapterJS.onwebrtcreadyDone) {
  3759. AdapterJS.onwebrtcreadyDone = true;
  3760. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3761. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3762. }
  3763. }
  3764. };
  3765. // Text namespace
  3766. AdapterJS.TEXT = {
  3767. PLUGIN: {
  3768. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3769. 'to work on this browser.',
  3770. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3771. BUTTON: 'Install Now'
  3772. },
  3773. REFRESH: {
  3774. REQUIRE_REFRESH: 'Please refresh page',
  3775. BUTTON: 'Refresh Page'
  3776. }
  3777. };
  3778. // The result of ice connection states.
  3779. // - starting: Ice connection is starting.
  3780. // - checking: Ice connection is checking.
  3781. // - connected Ice connection is connected.
  3782. // - completed Ice connection is connected.
  3783. // - done Ice connection has been completed.
  3784. // - disconnected Ice connection has been disconnected.
  3785. // - failed Ice connection has failed.
  3786. // - closed Ice connection is closed.
  3787. AdapterJS._iceConnectionStates = {
  3788. starting : 'starting',
  3789. checking : 'checking',
  3790. connected : 'connected',
  3791. completed : 'connected',
  3792. done : 'completed',
  3793. disconnected : 'disconnected',
  3794. failed : 'failed',
  3795. closed : 'closed'
  3796. };
  3797. //The IceConnection states that has been fired for each peer.
  3798. AdapterJS._iceConnectionFiredStates = [];
  3799. // Check if WebRTC Interface is defined.
  3800. AdapterJS.isDefined = null;
  3801. // This function helps to retrieve the webrtc detected browser information.
  3802. // This sets:
  3803. // - webrtcDetectedBrowser: The browser agent name.
  3804. // - webrtcDetectedVersion: The browser version.
  3805. // - webrtcDetectedType: The types of webRTC support.
  3806. // - 'moz': Mozilla implementation of webRTC.
  3807. // - 'webkit': WebKit implementation of webRTC.
  3808. // - 'plugin': Using the plugin implementation.
  3809. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3810. var hasMatch, checkMatch = navigator.userAgent.match(
  3811. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3812. if (/trident/i.test(checkMatch[1])) {
  3813. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3814. webrtcDetectedBrowser = 'IE';
  3815. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3816. } else if (checkMatch[1] === 'Chrome') {
  3817. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3818. if (hasMatch !== null) {
  3819. webrtcDetectedBrowser = 'opera';
  3820. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3821. }
  3822. }
  3823. if (navigator.userAgent.indexOf('Safari')) {
  3824. if (typeof InstallTrigger !== 'undefined') {
  3825. webrtcDetectedBrowser = 'firefox';
  3826. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3827. webrtcDetectedBrowser = 'IE';
  3828. } else if (
  3829. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3830. webrtcDetectedBrowser = 'safari';
  3831. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3832. webrtcDetectedBrowser = 'opera';
  3833. } else if (!!window.chrome) {
  3834. webrtcDetectedBrowser = 'chrome';
  3835. }
  3836. }
  3837. if (!webrtcDetectedBrowser) {
  3838. webrtcDetectedVersion = checkMatch[1];
  3839. }
  3840. if (!webrtcDetectedVersion) {
  3841. try {
  3842. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3843. [navigator.appName, navigator.appVersion, '-?'];
  3844. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3845. checkMatch.splice(1, 1, hasMatch[1]);
  3846. }
  3847. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3848. } catch (error) { }
  3849. }
  3850. };
  3851. // To fix configuration as some browsers does not support
  3852. // the 'urls' attribute.
  3853. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3854. if (pcConfig === null) {
  3855. return;
  3856. }
  3857. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3858. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3859. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3860. delete pcConfig.iceServers[i].urls;
  3861. }
  3862. }
  3863. };
  3864. AdapterJS.addEvent = function(elem, evnt, func) {
  3865. if (elem.addEventListener) { // W3C DOM
  3866. elem.addEventListener(evnt, func, false);
  3867. } else if (elem.attachEvent) {// OLD IE DOM
  3868. elem.attachEvent('on'+evnt, func);
  3869. } else { // No much to do
  3870. elem[evnt] = func;
  3871. }
  3872. };
  3873. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3874. // only inject once the page is ready
  3875. if (document.readyState !== 'complete') {
  3876. return;
  3877. }
  3878. var w = window;
  3879. var i = document.createElement('iframe');
  3880. i.style.position = 'fixed';
  3881. i.style.top = '-41px';
  3882. i.style.left = 0;
  3883. i.style.right = 0;
  3884. i.style.width = '100%';
  3885. i.style.height = '40px';
  3886. i.style.backgroundColor = '#ffffe1';
  3887. i.style.border = 'none';
  3888. i.style.borderBottom = '1px solid #888888';
  3889. i.style.zIndex = '9999999';
  3890. if(typeof i.style.webkitTransition === 'string') {
  3891. i.style.webkitTransition = 'all .5s ease-out';
  3892. } else if(typeof i.style.transition === 'string') {
  3893. i.style.transition = 'all .5s ease-out';
  3894. }
  3895. document.body.appendChild(i);
  3896. c = (i.contentWindow) ? i.contentWindow :
  3897. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3898. c.document.open();
  3899. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3900. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3901. 'middle; cursor: default;">' + text + '</span>');
  3902. if(buttonText && buttonLink) {
  3903. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3904. c.document.close();
  3905. // On click on okay
  3906. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3907. if (!!displayRefreshBar) {
  3908. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3909. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3910. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3911. }
  3912. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3913. e.preventDefault();
  3914. try {
  3915. event.cancelBubble = true;
  3916. } catch(error) { }
  3917. var pluginInstallInterval = setInterval(function(){
  3918. if(! isIE) {
  3919. navigator.plugins.refresh(false);
  3920. }
  3921. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3922. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3923. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3924. function() { // plugin now installed
  3925. clearInterval(pluginInstallInterval);
  3926. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3927. },
  3928. function() {
  3929. // still no plugin detected, nothing to do
  3930. });
  3931. } , 500);
  3932. });
  3933. // On click on Cancel
  3934. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3935. w.document.body.removeChild(i);
  3936. });
  3937. } else {
  3938. c.document.close();
  3939. }
  3940. setTimeout(function() {
  3941. if(typeof i.style.webkitTransform === 'string') {
  3942. i.style.webkitTransform = 'translateY(40px)';
  3943. } else if(typeof i.style.transform === 'string') {
  3944. i.style.transform = 'translateY(40px)';
  3945. } else {
  3946. i.style.top = '0px';
  3947. }
  3948. }, 300);
  3949. };
  3950. // -----------------------------------------------------------
  3951. // Detected webrtc implementation. Types are:
  3952. // - 'moz': Mozilla implementation of webRTC.
  3953. // - 'webkit': WebKit implementation of webRTC.
  3954. // - 'plugin': Using the plugin implementation.
  3955. webrtcDetectedType = null;
  3956. // Detected webrtc datachannel support. Types are:
  3957. // - 'SCTP': SCTP datachannel support.
  3958. // - 'RTP': RTP datachannel support.
  3959. webrtcDetectedDCSupport = null;
  3960. // Set the settings for creating DataChannels, MediaStream for
  3961. // Cross-browser compability.
  3962. // - This is only for SCTP based support browsers.
  3963. // the 'urls' attribute.
  3964. checkMediaDataChannelSettings =
  3965. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3966. if (typeof callback !== 'function') {
  3967. return;
  3968. }
  3969. var beOfferer = true;
  3970. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  3971. // Nightly version does not require MozDontOfferDataChannel for interop
  3972. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  3973. var isPeerFirefox = peerBrowserAgent === 'firefox';
  3974. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  3975. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  3976. // Resends an updated version of constraints for MozDataChannel to work
  3977. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  3978. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  3979. try {
  3980. delete constraints.mandatory.MozDontOfferDataChannel;
  3981. } catch (error) {
  3982. console.error('Failed deleting MozDontOfferDataChannel');
  3983. console.error(error);
  3984. }
  3985. } else if ((isLocalFirefox && !isPeerFirefox)) {
  3986. constraints.mandatory.MozDontOfferDataChannel = true;
  3987. }
  3988. if (!isLocalFirefox) {
  3989. // temporary measure to remove Moz* constraints in non Firefox browsers
  3990. for (var prop in constraints.mandatory) {
  3991. if (constraints.mandatory.hasOwnProperty(prop)) {
  3992. if (prop.indexOf('Moz') !== -1) {
  3993. delete constraints.mandatory[prop];
  3994. }
  3995. }
  3996. }
  3997. }
  3998. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  3999. // interopability of the media stream
  4000. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  4001. beOfferer = false;
  4002. }
  4003. callback(beOfferer, constraints);
  4004. };
  4005. // Handles the differences for all browsers ice connection state output.
  4006. // - Tested outcomes are:
  4007. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  4008. // - Chrome (answerer) : 'checking' > 'connected'
  4009. // - Firefox (offerer) : 'checking' > 'connected'
  4010. // - Firefox (answerer): 'checking' > 'connected'
  4011. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  4012. if (typeof callback !== 'function') {
  4013. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  4014. return;
  4015. }
  4016. peerId = (peerId) ? peerId : 'peer';
  4017. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  4018. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  4019. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  4020. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  4021. AdapterJS._iceConnectionFiredStates[peerId] = [];
  4022. }
  4023. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  4024. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  4025. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  4026. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  4027. setTimeout(function () {
  4028. AdapterJS._iceConnectionFiredStates[peerId]
  4029. .push(AdapterJS._iceConnectionStates.done);
  4030. callback(AdapterJS._iceConnectionStates.done);
  4031. }, 1000);
  4032. }
  4033. callback(iceConnectionState);
  4034. }
  4035. return;
  4036. };
  4037. // Firefox:
  4038. // - Creates iceServer from the url for Firefox.
  4039. // - Create iceServer with stun url.
  4040. // - Create iceServer with turn url.
  4041. // - Ignore the transport parameter from TURN url for FF version <=27.
  4042. // - Return null for createIceServer if transport=tcp.
  4043. // - FF 27 and above supports transport parameters in TURN url,
  4044. // - So passing in the full url to create iceServer.
  4045. // Chrome:
  4046. // - Creates iceServer from the url for Chrome M33 and earlier.
  4047. // - Create iceServer with stun url.
  4048. // - Chrome M28 & above uses below TURN format.
  4049. // Plugin:
  4050. // - Creates Ice Server for Plugin Browsers
  4051. // - If Stun - Create iceServer with stun url.
  4052. // - Else - Create iceServer with turn url
  4053. // - This is a WebRTC Function
  4054. createIceServer = null;
  4055. // Firefox:
  4056. // - Creates IceServers for Firefox
  4057. // - Use .url for FireFox.
  4058. // - Multiple Urls support
  4059. // Chrome:
  4060. // - Creates iceServers from the urls for Chrome M34 and above.
  4061. // - .urls is supported since Chrome M34.
  4062. // - Multiple Urls support
  4063. // Plugin:
  4064. // - Creates Ice Servers for Plugin Browsers
  4065. // - Multiple Urls support
  4066. // - This is a WebRTC Function
  4067. createIceServers = null;
  4068. //------------------------------------------------------------
  4069. //The RTCPeerConnection object.
  4070. RTCPeerConnection = null;
  4071. // Creates RTCSessionDescription object for Plugin Browsers
  4072. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  4073. RTCSessionDescription : null;
  4074. // Creates RTCIceCandidate object for Plugin Browsers
  4075. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  4076. RTCIceCandidate : null;
  4077. // Get UserMedia (only difference is the prefix).
  4078. // Code from Adam Barth.
  4079. getUserMedia = null;
  4080. // Attach a media stream to an element.
  4081. attachMediaStream = null;
  4082. // Re-attach a media stream to an element.
  4083. reattachMediaStream = null;
  4084. // Detected browser agent name. Types are:
  4085. // - 'firefox': Firefox browser.
  4086. // - 'chrome': Chrome browser.
  4087. // - 'opera': Opera browser.
  4088. // - 'safari': Safari browser.
  4089. // - 'IE' - Internet Explorer browser.
  4090. webrtcDetectedBrowser = null;
  4091. // Detected browser version.
  4092. webrtcDetectedVersion = null;
  4093. // Check for browser types and react accordingly
  4094. if (navigator.mozGetUserMedia) {
  4095. webrtcDetectedBrowser = 'firefox';
  4096. webrtcDetectedVersion = parseInt(navigator
  4097. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  4098. webrtcDetectedType = 'moz';
  4099. webrtcDetectedDCSupport = 'SCTP';
  4100. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4101. AdapterJS.maybeFixConfiguration(pcConfig);
  4102. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  4103. };
  4104. // The RTCSessionDescription object.
  4105. RTCSessionDescription = mozRTCSessionDescription;
  4106. window.RTCSessionDescription = RTCSessionDescription;
  4107. // The RTCIceCandidate object.
  4108. RTCIceCandidate = mozRTCIceCandidate;
  4109. window.RTCIceCandidate = RTCIceCandidate;
  4110. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  4111. navigator.getUserMedia = window.getUserMedia;
  4112. // Shim for MediaStreamTrack.getSources.
  4113. MediaStreamTrack.getSources = function(successCb) {
  4114. setTimeout(function() {
  4115. var infos = [
  4116. { kind: 'audio', id: 'default', label:'', facing:'' },
  4117. { kind: 'video', id: 'default', label:'', facing:'' }
  4118. ];
  4119. successCb(infos);
  4120. }, 0);
  4121. };
  4122. createIceServer = function (url, username, password) {
  4123. var iceServer = null;
  4124. var url_parts = url.split(':');
  4125. if (url_parts[0].indexOf('stun') === 0) {
  4126. iceServer = { url : url };
  4127. } else if (url_parts[0].indexOf('turn') === 0) {
  4128. if (webrtcDetectedVersion < 27) {
  4129. var turn_url_parts = url.split('?');
  4130. if (turn_url_parts.length === 1 ||
  4131. turn_url_parts[1].indexOf('transport=udp') === 0) {
  4132. iceServer = {
  4133. url : turn_url_parts[0],
  4134. credential : password,
  4135. username : username
  4136. };
  4137. }
  4138. } else {
  4139. iceServer = {
  4140. url : url,
  4141. credential : password,
  4142. username : username
  4143. };
  4144. }
  4145. }
  4146. return iceServer;
  4147. };
  4148. createIceServers = function (urls, username, password) {
  4149. var iceServers = [];
  4150. for (var i = 0; i < urls.length; i++) {
  4151. var iceServer = createIceServer(urls[i], username, password);
  4152. if (iceServer !== null) {
  4153. iceServers.push(iceServer);
  4154. }
  4155. }
  4156. return iceServers;
  4157. };
  4158. attachMediaStream = function (element, stream) {
  4159. element.mozSrcObject = stream;
  4160. if (stream !== null)
  4161. element.play();
  4162. return element;
  4163. };
  4164. reattachMediaStream = function (to, from) {
  4165. to.mozSrcObject = from.mozSrcObject;
  4166. to.play();
  4167. return to;
  4168. };
  4169. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  4170. if (!callback) {
  4171. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  4172. ': 1 argument required, but only 0 present.');
  4173. }
  4174. return callback([]);
  4175. };
  4176. // Fake get{Video,Audio}Tracks
  4177. if (!MediaStream.prototype.getVideoTracks) {
  4178. MediaStream.prototype.getVideoTracks = function () {
  4179. return [];
  4180. };
  4181. }
  4182. if (!MediaStream.prototype.getAudioTracks) {
  4183. MediaStream.prototype.getAudioTracks = function () {
  4184. return [];
  4185. };
  4186. }
  4187. AdapterJS.maybeThroughWebRTCReady();
  4188. } else if (navigator.webkitGetUserMedia) {
  4189. webrtcDetectedBrowser = 'chrome';
  4190. webrtcDetectedType = 'webkit';
  4191. webrtcDetectedVersion = parseInt(navigator
  4192. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  4193. // check if browser is opera 20+
  4194. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  4195. if (checkIfOpera !== null) {
  4196. webrtcDetectedBrowser = 'opera';
  4197. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  4198. }
  4199. // check browser datachannel support
  4200. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  4201. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  4202. webrtcDetectedDCSupport = 'SCTP';
  4203. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  4204. webrtcDetectedVersion > 24) {
  4205. webrtcDetectedDCSupport = 'RTP';
  4206. } else {
  4207. webrtcDetectedDCSupport = '';
  4208. }
  4209. createIceServer = function (url, username, password) {
  4210. var iceServer = null;
  4211. var url_parts = url.split(':');
  4212. if (url_parts[0].indexOf('stun') === 0) {
  4213. iceServer = { 'url' : url };
  4214. } else if (url_parts[0].indexOf('turn') === 0) {
  4215. iceServer = {
  4216. 'url' : url,
  4217. 'credential' : password,
  4218. 'username' : username
  4219. };
  4220. }
  4221. return iceServer;
  4222. };
  4223. createIceServers = function (urls, username, password) {
  4224. var iceServers = [];
  4225. if (webrtcDetectedVersion >= 34) {
  4226. iceServers = {
  4227. 'urls' : urls,
  4228. 'credential' : password,
  4229. 'username' : username
  4230. };
  4231. } else {
  4232. for (var i = 0; i < urls.length; i++) {
  4233. var iceServer = createIceServer(urls[i], username, password);
  4234. if (iceServer !== null) {
  4235. iceServers.push(iceServer);
  4236. }
  4237. }
  4238. }
  4239. return iceServers;
  4240. };
  4241. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4242. if (webrtcDetectedVersion < 34) {
  4243. AdapterJS.maybeFixConfiguration(pcConfig);
  4244. }
  4245. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  4246. };
  4247. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4248. navigator.getUserMedia = window.getUserMedia;
  4249. attachMediaStream = function (element, stream) {
  4250. if (typeof element.srcObject !== 'undefined') {
  4251. element.srcObject = stream;
  4252. } else if (typeof element.mozSrcObject !== 'undefined') {
  4253. element.mozSrcObject = stream;
  4254. } else if (typeof element.src !== 'undefined') {
  4255. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  4256. } else {
  4257. console.log('Error attaching stream to element.');
  4258. }
  4259. return element;
  4260. };
  4261. reattachMediaStream = function (to, from) {
  4262. to.src = from.src;
  4263. return to;
  4264. };
  4265. AdapterJS.maybeThroughWebRTCReady();
  4266. } else if (navigator.mediaDevices && navigator.userAgent.match(
  4267. /Edge\/(\d+).(\d+)$/)) {
  4268. webrtcDetectedBrowser = 'edge';
  4269. webrtcDetectedVersion =
  4270. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  4271. // the minimum version still supported by adapter.
  4272. webrtcMinimumVersion = 12;
  4273. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  4274. attachMediaStream = function(element, stream) {
  4275. element.srcObject = stream;
  4276. return element;
  4277. };
  4278. reattachMediaStream = function(to, from) {
  4279. to.srcObject = from.srcObject;
  4280. return to;
  4281. };
  4282. AdapterJS.maybeThroughWebRTCReady();
  4283. } else { // TRY TO USE PLUGIN
  4284. // IE 9 is not offering an implementation of console.log until you open a console
  4285. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4286. /* jshint -W020 */
  4287. console = {} || console;
  4288. // Implemented based on console specs from MDN
  4289. // You may override these functions
  4290. console.log = function (arg) {};
  4291. console.info = function (arg) {};
  4292. console.error = function (arg) {};
  4293. console.dir = function (arg) {};
  4294. console.exception = function (arg) {};
  4295. console.trace = function (arg) {};
  4296. console.warn = function (arg) {};
  4297. console.count = function (arg) {};
  4298. console.debug = function (arg) {};
  4299. console.count = function (arg) {};
  4300. console.time = function (arg) {};
  4301. console.timeEnd = function (arg) {};
  4302. console.group = function (arg) {};
  4303. console.groupCollapsed = function (arg) {};
  4304. console.groupEnd = function (arg) {};
  4305. /* jshint +W020 */
  4306. }
  4307. webrtcDetectedType = 'plugin';
  4308. webrtcDetectedDCSupport = 'plugin';
  4309. AdapterJS.parseWebrtcDetectedBrowser();
  4310. isIE = webrtcDetectedBrowser === 'IE';
  4311. /* jshint -W035 */
  4312. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4313. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4314. /* empty because it needs to prevent the function from running. */
  4315. }
  4316. };
  4317. /* jshint +W035 */
  4318. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4319. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4320. // Call immediately if possible
  4321. // Once the plugin is set, the code will always take this path
  4322. callback();
  4323. } else {
  4324. // otherwise start a 100ms interval
  4325. var checkPluginReadyState = setInterval(function () {
  4326. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4327. clearInterval(checkPluginReadyState);
  4328. callback();
  4329. }
  4330. }, 100);
  4331. }
  4332. };
  4333. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4334. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4335. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4336. });
  4337. };
  4338. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4339. // only inject once the page is ready
  4340. if (document.readyState !== 'complete') {
  4341. return;
  4342. }
  4343. // Prevent multiple injections
  4344. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4345. return;
  4346. }
  4347. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4348. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4349. var frag = document.createDocumentFragment();
  4350. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4351. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4352. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4353. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4354. '<param name="pluginId" value="' +
  4355. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4356. '<param name="windowless" value="false" /> ' +
  4357. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4358. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4359. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4360. // uncomment to be able to use virtual cams
  4361. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4362. '</object>';
  4363. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4364. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4365. }
  4366. document.body.appendChild(frag);
  4367. // Need to re-fetch the plugin
  4368. AdapterJS.WebRTCPlugin.plugin =
  4369. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4370. } else {
  4371. // Load Plugin
  4372. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4373. AdapterJS.WebRTCPlugin.plugin.id =
  4374. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4375. // IE will only start the plugin if it's ACTUALLY visible
  4376. if (isIE) {
  4377. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4378. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4379. } else { // The size of the plugin on Safari should be 0x0px
  4380. // so that the autorisation prompt is at the top
  4381. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4382. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4383. }
  4384. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4385. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4386. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4387. '<param name="pluginId" value="' +
  4388. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4389. '<param name="windowless" value="false" /> ' +
  4390. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4391. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4392. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4393. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4394. }
  4395. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4396. };
  4397. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4398. function (comName, plugName, installedCb, notInstalledCb) {
  4399. if (!isIE) {
  4400. var pluginArray = navigator.plugins;
  4401. for (var i = 0; i < pluginArray.length; i++) {
  4402. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4403. installedCb();
  4404. return;
  4405. }
  4406. }
  4407. notInstalledCb();
  4408. } else {
  4409. try {
  4410. var axo = new ActiveXObject(comName + '.' + plugName);
  4411. } catch (e) {
  4412. notInstalledCb();
  4413. return;
  4414. }
  4415. installedCb();
  4416. }
  4417. };
  4418. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4419. if (AdapterJS.WebRTCPlugin.pluginState ===
  4420. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4421. console.error("AdapterJS - WebRTC interface has already been defined");
  4422. return;
  4423. }
  4424. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4425. AdapterJS.isDefined = function (variable) {
  4426. return variable !== null && variable !== undefined;
  4427. };
  4428. createIceServer = function (url, username, password) {
  4429. var iceServer = null;
  4430. var url_parts = url.split(':');
  4431. if (url_parts[0].indexOf('stun') === 0) {
  4432. iceServer = {
  4433. 'url' : url,
  4434. 'hasCredentials' : false
  4435. };
  4436. } else if (url_parts[0].indexOf('turn') === 0) {
  4437. iceServer = {
  4438. 'url' : url,
  4439. 'hasCredentials' : true,
  4440. 'credential' : password,
  4441. 'username' : username
  4442. };
  4443. }
  4444. return iceServer;
  4445. };
  4446. createIceServers = function (urls, username, password) {
  4447. var iceServers = [];
  4448. for (var i = 0; i < urls.length; ++i) {
  4449. iceServers.push(createIceServer(urls[i], username, password));
  4450. }
  4451. return iceServers;
  4452. };
  4453. RTCSessionDescription = function (info) {
  4454. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4455. return AdapterJS.WebRTCPlugin.plugin.
  4456. ConstructSessionDescription(info.type, info.sdp);
  4457. };
  4458. RTCPeerConnection = function (servers, constraints) {
  4459. var iceServers = null;
  4460. if (servers) {
  4461. iceServers = servers.iceServers;
  4462. for (var i = 0; i < iceServers.length; i++) {
  4463. if (iceServers[i].urls && !iceServers[i].url) {
  4464. iceServers[i].url = iceServers[i].urls;
  4465. }
  4466. iceServers[i].hasCredentials = AdapterJS.
  4467. isDefined(iceServers[i].username) &&
  4468. AdapterJS.isDefined(iceServers[i].credential);
  4469. }
  4470. }
  4471. var mandatory = (constraints && constraints.mandatory) ?
  4472. constraints.mandatory : null;
  4473. var optional = (constraints && constraints.optional) ?
  4474. constraints.optional : null;
  4475. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4476. return AdapterJS.WebRTCPlugin.plugin.
  4477. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4478. iceServers, mandatory, optional);
  4479. };
  4480. MediaStreamTrack = {};
  4481. MediaStreamTrack.getSources = function (callback) {
  4482. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4483. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4484. });
  4485. };
  4486. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4487. constraints.audio = constraints.audio || false;
  4488. constraints.video = constraints.video || false;
  4489. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4490. AdapterJS.WebRTCPlugin.plugin.
  4491. getUserMedia(constraints, successCallback, failureCallback);
  4492. });
  4493. };
  4494. window.navigator.getUserMedia = window.getUserMedia;
  4495. attachMediaStream = function (element, stream) {
  4496. if (!element || !element.parentNode) {
  4497. return;
  4498. }
  4499. var streamId;
  4500. if (stream === null) {
  4501. streamId = '';
  4502. } else {
  4503. if (typeof stream.enableSoundTracks !== 'undefined') {
  4504. stream.enableSoundTracks(true);
  4505. }
  4506. streamId = stream.id;
  4507. }
  4508. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4509. var nodeName = element.nodeName.toLowerCase();
  4510. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4511. var tag;
  4512. switch(nodeName) {
  4513. case 'audio':
  4514. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4515. break;
  4516. case 'video':
  4517. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4518. break;
  4519. default:
  4520. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4521. }
  4522. var frag = document.createDocumentFragment();
  4523. var temp = document.createElement('div');
  4524. var classHTML = '';
  4525. if (element.className) {
  4526. classHTML = 'class="' + element.className + '" ';
  4527. } else if (element.attributes && element.attributes['class']) {
  4528. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4529. }
  4530. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4531. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4532. '<param name="pluginId" value="' + elementId + '" /> ' +
  4533. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4534. '<param name="windowless" value="true" /> ' +
  4535. '<param name="streamId" value="' + streamId + '" /> ' +
  4536. '<param name="tag" value="' + tag + '" /> ' +
  4537. '</object>';
  4538. while (temp.firstChild) {
  4539. frag.appendChild(temp.firstChild);
  4540. }
  4541. var height = '';
  4542. var width = '';
  4543. if (element.clientWidth || element.clientHeight) {
  4544. width = element.clientWidth;
  4545. height = element.clientHeight;
  4546. }
  4547. else if (element.width || element.height) {
  4548. width = element.width;
  4549. height = element.height;
  4550. }
  4551. element.parentNode.insertBefore(frag, element);
  4552. frag = document.getElementById(elementId);
  4553. frag.width = width;
  4554. frag.height = height;
  4555. element.parentNode.removeChild(element);
  4556. } else { // already an <object> tag, just change the stream id
  4557. var children = element.children;
  4558. for (var i = 0; i !== children.length; ++i) {
  4559. if (children[i].name === 'streamId') {
  4560. children[i].value = streamId;
  4561. break;
  4562. }
  4563. }
  4564. element.setStreamId(streamId);
  4565. }
  4566. var newElement = document.getElementById(elementId);
  4567. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4568. return newElement;
  4569. };
  4570. reattachMediaStream = function (to, from) {
  4571. var stream = null;
  4572. var children = from.children;
  4573. for (var i = 0; i !== children.length; ++i) {
  4574. if (children[i].name === 'streamId') {
  4575. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4576. stream = AdapterJS.WebRTCPlugin.plugin
  4577. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4578. break;
  4579. }
  4580. }
  4581. if (stream !== null) {
  4582. return attachMediaStream(to, stream);
  4583. } else {
  4584. console.log('Could not find the stream associated with this element');
  4585. }
  4586. };
  4587. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4588. properties = Object.getOwnPropertyNames( prototype );
  4589. for(prop in properties) {
  4590. propName = properties[prop];
  4591. if (typeof(propName.slice) === 'function') {
  4592. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4593. if (isIE) {
  4594. destElem.attachEvent(propName,srcElem[propName]);
  4595. } else {
  4596. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4597. }
  4598. } else {
  4599. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4600. }
  4601. }
  4602. }
  4603. var subPrototype = Object.getPrototypeOf(prototype)
  4604. if(subPrototype != null) {
  4605. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4606. }
  4607. }
  4608. RTCIceCandidate = function (candidate) {
  4609. if (!candidate.sdpMid) {
  4610. candidate.sdpMid = '';
  4611. }
  4612. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4613. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4614. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4615. );
  4616. };
  4617. // inject plugin
  4618. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4619. AdapterJS.WebRTCPlugin.injectPlugin();
  4620. };
  4621. // This function will be called if the plugin is needed (browser different
  4622. // from Chrome or Firefox), but the plugin is not installed.
  4623. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4624. function() {
  4625. AdapterJS.addEvent(document,
  4626. 'readystatechange',
  4627. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4628. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4629. };
  4630. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4631. if (AdapterJS.options.hidePluginInstallPrompt) {
  4632. return;
  4633. }
  4634. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4635. if(downloadLink) { // if download link
  4636. var popupString;
  4637. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4638. popupString = 'This website requires you to install the ' +
  4639. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4640. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4641. ' WebRTC Plugin</a>' +
  4642. ' to work on this browser.';
  4643. } else { // no portal link, just print a generic explanation
  4644. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4645. }
  4646. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4647. } else { // no download link, just print a generic explanation
  4648. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4649. }
  4650. };
  4651. // Try to detect the plugin and act accordingly
  4652. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4653. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4654. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4655. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4656. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4657. }
  4658. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4659. },{"jitsi-meet-logger":49}],21:[function(require,module,exports){
  4660. (function (__filename){
  4661. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4662. var UsernameGenerator = require('../util/UsernameGenerator');
  4663. function supportsLocalStorage() {
  4664. try {
  4665. return 'localStorage' in window && window.localStorage !== null;
  4666. } catch (e) {
  4667. logger.log("localstorage is not supported");
  4668. return false;
  4669. }
  4670. }
  4671. function generateUniqueId() {
  4672. function _p8() {
  4673. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4674. }
  4675. return _p8() + _p8() + _p8() + _p8();
  4676. }
  4677. function Settings(conferenceID) {
  4678. this.displayName = '';
  4679. this.userId;
  4680. this.confSettings = null;
  4681. this.conferenceID = conferenceID;
  4682. this.callStatsUserName;
  4683. if (supportsLocalStorage()) {
  4684. if(!window.localStorage.getItem(conferenceID))
  4685. this.confSettings = {};
  4686. else
  4687. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4688. if(!this.confSettings.jitsiMeetId) {
  4689. this.confSettings.jitsiMeetId = generateUniqueId();
  4690. logger.log("generated id",
  4691. this.confSettings.jitsiMeetId);
  4692. this.save();
  4693. }
  4694. if (!this.confSettings.callStatsUserName) {
  4695. this.confSettings.callStatsUserName
  4696. = UsernameGenerator.generateUsername();
  4697. logger.log('generated callstats uid',
  4698. this.confSettings.callStatsUserName);
  4699. this.save();
  4700. }
  4701. this.userId = this.confSettings.jitsiMeetId || '';
  4702. this.displayName = this.confSettings.displayname || '';
  4703. this.callStatsUserName = this.confSettings.callStatsUserName || '';
  4704. } else {
  4705. logger.log("local storage is not supported");
  4706. this.userId = generateUniqueId();
  4707. this.callStatsUserName = UsernameGenerator.generateUsername();
  4708. }
  4709. }
  4710. Settings.prototype.save = function () {
  4711. if(!supportsLocalStorage())
  4712. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4713. }
  4714. Settings.prototype.setDisplayName = function (newDisplayName) {
  4715. this.displayName = newDisplayName;
  4716. if(this.confSettings != null)
  4717. this.confSettings.displayname = displayName;
  4718. this.save();
  4719. return this.displayName;
  4720. }
  4721. Settings.prototype.getSettings = function () {
  4722. return {
  4723. displayName: this.displayName,
  4724. uid: this.userId
  4725. };
  4726. }
  4727. /**
  4728. * Returns fake username for callstats
  4729. * @returns {string} fake username for callstats
  4730. */
  4731. Settings.prototype.getCallStatsUserName = function () {
  4732. return this.callStatsUserName;
  4733. }
  4734. module.exports = Settings;
  4735. }).call(this,"/modules/settings/Settings.js")
  4736. },{"../util/UsernameGenerator":27,"jitsi-meet-logger":49}],22:[function(require,module,exports){
  4737. (function (__filename){
  4738. /* global $, Strophe, callstats */
  4739. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4740. var jsSHA = require('jssha');
  4741. var io = require('socket.io-client');
  4742. /**
  4743. * @const
  4744. * @see http://www.callstats.io/api/#enumeration-of-wrtcfuncnames
  4745. */
  4746. var wrtcFuncNames = {
  4747. createOffer: "createOffer",
  4748. createAnswer: "createAnswer",
  4749. setLocalDescription: "setLocalDescription",
  4750. setRemoteDescription: "setRemoteDescription",
  4751. addIceCandidate: "addIceCandidate",
  4752. getUserMedia: "getUserMedia"
  4753. };
  4754. var callStats = null;
  4755. function initCallback (err, msg) {
  4756. logger.log("CallStats Status: err=" + err + " msg=" + msg);
  4757. }
  4758. /**
  4759. * Returns a function which invokes f in a try/catch block, logs any exception
  4760. * to the console, and then swallows it.
  4761. *
  4762. * @param f the function to invoke in a try/catch block
  4763. * @return a function which invokes f in a try/catch block, logs any exception
  4764. * to the console, and then swallows it
  4765. */
  4766. function _try_catch (f) {
  4767. return function () {
  4768. try {
  4769. f.apply(this, arguments);
  4770. } catch (e) {
  4771. logger.error(e);
  4772. }
  4773. };
  4774. }
  4775. /**
  4776. * Creates new CallStats instance that handles all callstats API calls.
  4777. * @param peerConnection {JingleSessionPC} the session object
  4778. * @param Settings {Settings} the settings instance. Declared in
  4779. * /modules/settings/Settings.js
  4780. * @param options {object} credentials for callstats.
  4781. */
  4782. var CallStats = _try_catch(function(jingleSession, Settings, options) {
  4783. try{
  4784. //check weather that should work with more than 1 peerconnection
  4785. if(!callStats) {
  4786. callStats = new callstats($, io, jsSHA);
  4787. } else {
  4788. return;
  4789. }
  4790. this.session = jingleSession;
  4791. this.peerconnection = jingleSession.peerconnection.peerconnection;
  4792. this.userID = Settings.getCallStatsUserName();
  4793. //FIXME: change it to something else (maybe roomName)
  4794. var location = window.location;
  4795. this.confID = location.hostname + location.pathname;
  4796. //userID is generated or given by the origin server
  4797. callStats.initialize(options.callStatsID,
  4798. options.callStatsSecret,
  4799. this.userID,
  4800. initCallback);
  4801. callStats.addNewFabric(this.peerconnection,
  4802. Strophe.getResourceFromJid(jingleSession.peerjid),
  4803. callStats.fabricUsage.multiplex,
  4804. this.confID,
  4805. this.pcCallback.bind(this));
  4806. } catch (e) {
  4807. // The callstats.io API failed to initialize (e.g. because its
  4808. // download failed to succeed in general or on time). Further
  4809. // attempts to utilize it cannot possibly succeed.
  4810. callStats = null;
  4811. logger.error(e);
  4812. }
  4813. // notify callstats about failures if there were any
  4814. if (CallStats.pendingErrors.length) {
  4815. CallStats.pendingErrors.forEach(function (error) {
  4816. CallStats._reportError.call(this, error.type, error.error,
  4817. error.pc);
  4818. }, this);
  4819. CallStats.pendingErrors.length = 0;
  4820. }
  4821. });
  4822. // some errors may happen before CallStats init
  4823. // in this case we accumulate them in this array
  4824. // and send them to callstats on init
  4825. CallStats.pendingErrors = [];
  4826. CallStats.prototype.pcCallback = _try_catch(function (err, msg) {
  4827. if (!callStats) {
  4828. return;
  4829. }
  4830. logger.log("Monitoring status: "+ err + " msg: " + msg);
  4831. callStats.sendFabricEvent(this.peerconnection,
  4832. callStats.fabricEvent.fabricSetup, this.confID);
  4833. });
  4834. /**
  4835. * Notifies CallStats for mute events
  4836. * @param mute {boolean} true for muted and false for not muted
  4837. * @param type {String} "audio"/"video"
  4838. */
  4839. CallStats.prototype.sendMuteEvent = _try_catch(function (mute, type) {
  4840. if (!callStats) {
  4841. return;
  4842. }
  4843. var event = null;
  4844. if (type === "video") {
  4845. event = (mute? callStats.fabricEvent.videoPause :
  4846. callStats.fabricEvent.videoResume);
  4847. }
  4848. else {
  4849. event = (mute? callStats.fabricEvent.audioMute :
  4850. callStats.fabricEvent.audioUnmute);
  4851. }
  4852. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  4853. });
  4854. /**
  4855. * Notifies CallStats for connection setup errors
  4856. */
  4857. CallStats.prototype.sendTerminateEvent = _try_catch(function () {
  4858. if(!callStats) {
  4859. return;
  4860. }
  4861. callStats.sendFabricEvent(this.peerconnection,
  4862. callStats.fabricEvent.fabricTerminated, this.confID);
  4863. });
  4864. /**
  4865. * Notifies CallStats for connection setup errors
  4866. */
  4867. CallStats.prototype.sendSetupFailedEvent = _try_catch(function () {
  4868. if(!callStats) {
  4869. return;
  4870. }
  4871. callStats.sendFabricEvent(this.peerconnection,
  4872. callStats.fabricEvent.fabricSetupFailed, this.confID);
  4873. });
  4874. /**
  4875. * Sends the given feedback through CallStats.
  4876. *
  4877. * @param overallFeedback an integer between 1 and 5 indicating the
  4878. * user feedback
  4879. * @param detailedFeedback detailed feedback from the user. Not yet used
  4880. */
  4881. CallStats.prototype.sendFeedback = _try_catch(
  4882. function(overallFeedback, detailedFeedback) {
  4883. if(!callStats) {
  4884. return;
  4885. }
  4886. var feedbackString = '{"userID":"' + this.userID + '"' +
  4887. ', "overall":' + overallFeedback +
  4888. ', "comment": "' + detailedFeedback + '"}';
  4889. var feedbackJSON = JSON.parse(feedbackString);
  4890. callStats.sendUserFeedback(this.confID, feedbackJSON);
  4891. });
  4892. /**
  4893. * Reports an error to callstats.
  4894. *
  4895. * @param type the type of the error, which will be one of the wrtcFuncNames
  4896. * @param e the error
  4897. * @param pc the peerconnection
  4898. * @private
  4899. */
  4900. CallStats._reportError = function (type, e, pc) {
  4901. if (callStats) {
  4902. callStats.reportError(pc, this.confID, type, e);
  4903. } else {
  4904. CallStats.pendingErrors.push({ type: type, error: e, pc: pc});
  4905. }
  4906. // else just ignore it
  4907. };
  4908. /**
  4909. * Notifies CallStats that getUserMedia failed.
  4910. *
  4911. * @param {Error} e error to send
  4912. * @param {CallStats} cs callstats instance related to the error (optional)
  4913. */
  4914. CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
  4915. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  4916. });
  4917. /**
  4918. * Notifies CallStats that peer connection failed to create offer.
  4919. *
  4920. * @param {Error} e error to send
  4921. * @param {RTCPeerConnection} pc connection on which failure occured.
  4922. * @param {CallStats} cs callstats instance related to the error (optional)
  4923. */
  4924. CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
  4925. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  4926. });
  4927. /**
  4928. * Notifies CallStats that peer connection failed to create answer.
  4929. *
  4930. * @param {Error} e error to send
  4931. * @param {RTCPeerConnection} pc connection on which failure occured.
  4932. * @param {CallStats} cs callstats instance related to the error (optional)
  4933. */
  4934. CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
  4935. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  4936. });
  4937. /**
  4938. * Notifies CallStats that peer connection failed to set local description.
  4939. *
  4940. * @param {Error} e error to send
  4941. * @param {RTCPeerConnection} pc connection on which failure occured.
  4942. * @param {CallStats} cs callstats instance related to the error (optional)
  4943. */
  4944. CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
  4945. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  4946. });
  4947. /**
  4948. * Notifies CallStats that peer connection failed to set remote description.
  4949. *
  4950. * @param {Error} e error to send
  4951. * @param {RTCPeerConnection} pc connection on which failure occured.
  4952. * @param {CallStats} cs callstats instance related to the error (optional)
  4953. */
  4954. CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
  4955. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  4956. });
  4957. /**
  4958. * Notifies CallStats that peer connection failed to add ICE candidate.
  4959. *
  4960. * @param {Error} e error to send
  4961. * @param {RTCPeerConnection} pc connection on which failure occured.
  4962. * @param {CallStats} cs callstats instance related to the error (optional)
  4963. */
  4964. CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
  4965. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  4966. });
  4967. module.exports = CallStats;
  4968. }).call(this,"/modules/statistics/CallStats.js")
  4969. },{"jitsi-meet-logger":49,"jssha":50,"socket.io-client":81}],23:[function(require,module,exports){
  4970. /* global config */
  4971. /**
  4972. * Provides statistics for the local stream.
  4973. */
  4974. var RTCBrowserType = require('../RTC/RTCBrowserType');
  4975. /**
  4976. * Size of the webaudio analyzer buffer.
  4977. * @type {number}
  4978. */
  4979. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  4980. /**
  4981. * Value of the webaudio analyzer smoothing time parameter.
  4982. * @type {number}
  4983. */
  4984. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  4985. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  4986. var context = null;
  4987. if(window.AudioContext) {
  4988. context = new AudioContext();
  4989. }
  4990. /**
  4991. * Converts time domain data array to audio level.
  4992. * @param samples the time domain data array.
  4993. * @returns {number} the audio level
  4994. */
  4995. function timeDomainDataToAudioLevel(samples) {
  4996. var maxVolume = 0;
  4997. var length = samples.length;
  4998. for (var i = 0; i < length; i++) {
  4999. if (maxVolume < samples[i])
  5000. maxVolume = samples[i];
  5001. }
  5002. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  5003. }
  5004. /**
  5005. * Animates audio level change
  5006. * @param newLevel the new audio level
  5007. * @param lastLevel the last audio level
  5008. * @returns {Number} the audio level to be set
  5009. */
  5010. function animateLevel(newLevel, lastLevel) {
  5011. var value = 0;
  5012. var diff = lastLevel - newLevel;
  5013. if(diff > 0.2) {
  5014. value = lastLevel - 0.2;
  5015. }
  5016. else if(diff < -0.4) {
  5017. value = lastLevel + 0.4;
  5018. }
  5019. else {
  5020. value = newLevel;
  5021. }
  5022. return parseFloat(value.toFixed(3));
  5023. }
  5024. /**
  5025. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  5026. *
  5027. * @param stream the local stream
  5028. * @param interval stats refresh interval given in ms.
  5029. * @param callback function that receives the audio levels.
  5030. * @constructor
  5031. */
  5032. function LocalStatsCollector(stream, interval, callback) {
  5033. this.stream = stream;
  5034. this.intervalId = null;
  5035. this.intervalMilis = interval;
  5036. this.audioLevel = 0;
  5037. this.callback = callback;
  5038. }
  5039. /**
  5040. * Starts the collecting the statistics.
  5041. */
  5042. LocalStatsCollector.prototype.start = function () {
  5043. if (!context ||
  5044. RTCBrowserType.isTemasysPluginUsed())
  5045. return;
  5046. var analyser = context.createAnalyser();
  5047. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  5048. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  5049. var source = context.createMediaStreamSource(this.stream);
  5050. source.connect(analyser);
  5051. var self = this;
  5052. this.intervalId = setInterval(
  5053. function () {
  5054. var array = new Uint8Array(analyser.frequencyBinCount);
  5055. analyser.getByteTimeDomainData(array);
  5056. var audioLevel = timeDomainDataToAudioLevel(array);
  5057. if (audioLevel != self.audioLevel) {
  5058. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  5059. self.callback(self.audioLevel);
  5060. }
  5061. },
  5062. this.intervalMilis
  5063. );
  5064. };
  5065. /**
  5066. * Stops collecting the statistics.
  5067. */
  5068. LocalStatsCollector.prototype.stop = function () {
  5069. if (this.intervalId) {
  5070. clearInterval(this.intervalId);
  5071. this.intervalId = null;
  5072. }
  5073. };
  5074. module.exports = LocalStatsCollector;
  5075. },{"../RTC/RTCBrowserType":17}],24:[function(require,module,exports){
  5076. (function (__filename){
  5077. /* global require, ssrc2jid */
  5078. /* jshint -W117 */
  5079. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5080. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5081. var StatisticsEvents = require("../../service/statistics/Events");
  5082. /* Whether we support the browser we are running into for logging statistics */
  5083. var browserSupported = RTCBrowserType.isChrome() ||
  5084. RTCBrowserType.isOpera();
  5085. var keyMap = {};
  5086. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  5087. "ssrc": "ssrc",
  5088. "packetsReceived": "packetsReceived",
  5089. "packetsLost": "packetsLost",
  5090. "packetsSent": "packetsSent",
  5091. "bytesReceived": "bytesReceived",
  5092. "bytesSent": "bytesSent"
  5093. };
  5094. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  5095. "receiveBandwidth": "googAvailableReceiveBandwidth",
  5096. "sendBandwidth": "googAvailableSendBandwidth",
  5097. "remoteAddress": "googRemoteAddress",
  5098. "transportType": "googTransportType",
  5099. "localAddress": "googLocalAddress",
  5100. "activeConnection": "googActiveConnection",
  5101. "ssrc": "ssrc",
  5102. "packetsReceived": "packetsReceived",
  5103. "packetsSent": "packetsSent",
  5104. "packetsLost": "packetsLost",
  5105. "bytesReceived": "bytesReceived",
  5106. "bytesSent": "bytesSent",
  5107. "googFrameHeightReceived": "googFrameHeightReceived",
  5108. "googFrameWidthReceived": "googFrameWidthReceived",
  5109. "googFrameHeightSent": "googFrameHeightSent",
  5110. "googFrameWidthSent": "googFrameWidthSent",
  5111. "audioInputLevel": "audioInputLevel",
  5112. "audioOutputLevel": "audioOutputLevel"
  5113. };
  5114. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  5115. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  5116. /**
  5117. * Calculates packet lost percent using the number of lost packets and the
  5118. * number of all packet.
  5119. * @param lostPackets the number of lost packets
  5120. * @param totalPackets the number of all packets.
  5121. * @returns {number} packet loss percent
  5122. */
  5123. function calculatePacketLoss(lostPackets, totalPackets) {
  5124. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  5125. return 0;
  5126. return Math.round((lostPackets/totalPackets)*100);
  5127. }
  5128. function getStatValue(item, name) {
  5129. var browserType = RTCBrowserType.getBrowserType();
  5130. if (!keyMap[browserType][name])
  5131. throw "The property isn't supported!";
  5132. var key = keyMap[browserType][name];
  5133. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  5134. item.stat(key) : item[key];
  5135. }
  5136. function formatAudioLevel(audioLevel) {
  5137. return Math.min(Math.max(audioLevel, 0), 1);
  5138. }
  5139. /**
  5140. * Checks whether a certain record should be included in the logged statistics.
  5141. */
  5142. function acceptStat(reportId, reportType, statName) {
  5143. if (reportType == "googCandidatePair" && statName == "googChannelId")
  5144. return false;
  5145. if (reportType == "ssrc") {
  5146. if (statName == "googTrackId" ||
  5147. statName == "transportId" ||
  5148. statName == "ssrc")
  5149. return false;
  5150. }
  5151. return true;
  5152. }
  5153. /**
  5154. * Checks whether a certain record should be included in the logged statistics.
  5155. */
  5156. function acceptReport(id, type) {
  5157. if (id.substring(0, 15) == "googCertificate" ||
  5158. id.substring(0, 9) == "googTrack" ||
  5159. id.substring(0, 20) == "googLibjingleSession")
  5160. return false;
  5161. if (type == "googComponent")
  5162. return false;
  5163. return true;
  5164. }
  5165. /**
  5166. * Peer statistics data holder.
  5167. * @constructor
  5168. */
  5169. function PeerStats()
  5170. {
  5171. this.ssrc2Loss = {};
  5172. this.ssrc2AudioLevel = {};
  5173. this.ssrc2bitrate = {};
  5174. this.ssrc2resolution = {};
  5175. }
  5176. /**
  5177. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  5178. * represented by this instance.
  5179. * @param lossRate new packet loss rate value to be set.
  5180. */
  5181. PeerStats.prototype.setSsrcLoss = function (lossRate)
  5182. {
  5183. this.ssrc2Loss = lossRate;
  5184. };
  5185. /**
  5186. * Sets resolution that belong to the ssrc
  5187. * represented by this instance.
  5188. * @param resolution new resolution value to be set.
  5189. */
  5190. PeerStats.prototype.setSsrcResolution = function (resolution)
  5191. {
  5192. if(resolution === null && this.ssrc2resolution[ssrc])
  5193. {
  5194. delete this.ssrc2resolution[ssrc];
  5195. }
  5196. else if(resolution !== null)
  5197. this.ssrc2resolution[ssrc] = resolution;
  5198. };
  5199. /**
  5200. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  5201. * represented by this instance.
  5202. * @param ssrc audio or video RTP stream SSRC.
  5203. * @param bitrate new bitrate value to be set.
  5204. */
  5205. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  5206. {
  5207. if(this.ssrc2bitrate[ssrc])
  5208. {
  5209. this.ssrc2bitrate[ssrc].download += bitrate.download;
  5210. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  5211. }
  5212. else {
  5213. this.ssrc2bitrate[ssrc] = bitrate;
  5214. }
  5215. };
  5216. /**
  5217. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  5218. * the stream which belongs to the peer represented by this instance.
  5219. * @param ssrc RTP stream SSRC for which current audio level value will be
  5220. * updated.
  5221. * @param audioLevel the new audio level value to be set. Value is truncated to
  5222. * fit the range from 0 to 1.
  5223. */
  5224. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  5225. {
  5226. // Range limit 0 - 1
  5227. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  5228. };
  5229. function ConferenceStats() {
  5230. /**
  5231. * The bandwidth
  5232. * @type {{}}
  5233. */
  5234. this.bandwidth = {};
  5235. /**
  5236. * The bit rate
  5237. * @type {{}}
  5238. */
  5239. this.bitrate = {};
  5240. /**
  5241. * The packet loss rate
  5242. * @type {{}}
  5243. */
  5244. this.packetLoss = null;
  5245. /**
  5246. * Array with the transport information.
  5247. * @type {Array}
  5248. */
  5249. this.transport = [];
  5250. }
  5251. /**
  5252. * <tt>StatsCollector</tt> registers for stats updates of given
  5253. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  5254. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  5255. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  5256. * instance as an event source.
  5257. *
  5258. * @param peerconnection webRTC peer connection object.
  5259. * @param interval stats refresh interval given in ms.
  5260. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  5261. * called on stats update.
  5262. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  5263. * @constructor
  5264. */
  5265. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  5266. {
  5267. this.peerconnection = peerconnection;
  5268. this.baselineAudioLevelsReport = null;
  5269. this.currentAudioLevelsReport = null;
  5270. this.currentStatsReport = null;
  5271. this.baselineStatsReport = null;
  5272. this.audioLevelsIntervalId = null;
  5273. this.eventEmitter = eventEmitter;
  5274. this.config = config || {};
  5275. this.conferenceStats = new ConferenceStats();
  5276. /**
  5277. * Gather PeerConnection stats once every this many milliseconds.
  5278. */
  5279. this.GATHER_INTERVAL = 15000;
  5280. /**
  5281. * Log stats via the focus once every this many milliseconds.
  5282. */
  5283. this.LOG_INTERVAL = 60000;
  5284. /**
  5285. * Gather stats and store them in this.statsToBeLogged.
  5286. */
  5287. this.gatherStatsIntervalId = null;
  5288. /**
  5289. * Send the stats already saved in this.statsToBeLogged to be logged via
  5290. * the focus.
  5291. */
  5292. this.logStatsIntervalId = null;
  5293. /**
  5294. * Stores the statistics which will be send to the focus to be logged.
  5295. */
  5296. this.statsToBeLogged =
  5297. {
  5298. timestamps: [],
  5299. stats: {}
  5300. };
  5301. // Updates stats interval
  5302. this.audioLevelsIntervalMilis = audioLevelsInterval;
  5303. this.statsIntervalId = null;
  5304. this.statsIntervalMilis = statsInterval;
  5305. // Map of ssrcs to PeerStats
  5306. this.ssrc2stats = {};
  5307. }
  5308. module.exports = StatsCollector;
  5309. /**
  5310. * Stops stats updates.
  5311. */
  5312. StatsCollector.prototype.stop = function () {
  5313. if (this.audioLevelsIntervalId) {
  5314. clearInterval(this.audioLevelsIntervalId);
  5315. this.audioLevelsIntervalId = null;
  5316. }
  5317. if (this.statsIntervalId)
  5318. {
  5319. clearInterval(this.statsIntervalId);
  5320. this.statsIntervalId = null;
  5321. }
  5322. if(this.logStatsIntervalId)
  5323. {
  5324. clearInterval(this.logStatsIntervalId);
  5325. this.logStatsIntervalId = null;
  5326. }
  5327. if(this.gatherStatsIntervalId)
  5328. {
  5329. clearInterval(this.gatherStatsIntervalId);
  5330. this.gatherStatsIntervalId = null;
  5331. }
  5332. };
  5333. /**
  5334. * Callback passed to <tt>getStats</tt> method.
  5335. * @param error an error that occurred on <tt>getStats</tt> call.
  5336. */
  5337. StatsCollector.prototype.errorCallback = function (error)
  5338. {
  5339. logger.error("Get stats error", error);
  5340. this.stop();
  5341. };
  5342. /**
  5343. * Starts stats updates.
  5344. */
  5345. StatsCollector.prototype.start = function ()
  5346. {
  5347. var self = this;
  5348. this.audioLevelsIntervalId = setInterval(
  5349. function () {
  5350. // Interval updates
  5351. self.peerconnection.getStats(
  5352. function (report) {
  5353. var results = null;
  5354. if (!report || !report.result ||
  5355. typeof report.result != 'function') {
  5356. results = report;
  5357. }
  5358. else {
  5359. results = report.result();
  5360. }
  5361. //logger.error("Got interval report", results);
  5362. self.currentAudioLevelsReport = results;
  5363. self.processAudioLevelReport();
  5364. self.baselineAudioLevelsReport =
  5365. self.currentAudioLevelsReport;
  5366. },
  5367. self.errorCallback
  5368. );
  5369. },
  5370. self.audioLevelsIntervalMilis
  5371. );
  5372. // if (!this.config.disableStats && browserSupported) {
  5373. // this.statsIntervalId = setInterval(
  5374. // function () {
  5375. // // Interval updates
  5376. // self.peerconnection.getStats(
  5377. // function (report) {
  5378. // var results = null;
  5379. // if (!report || !report.result ||
  5380. // typeof report.result != 'function') {
  5381. // //firefox
  5382. // results = report;
  5383. // }
  5384. // else {
  5385. // //chrome
  5386. // results = report.result();
  5387. // }
  5388. // //logger.error("Got interval report", results);
  5389. // self.currentStatsReport = results;
  5390. // try {
  5391. // self.processStatsReport();
  5392. // }
  5393. // catch (e) {
  5394. // logger.error("Unsupported key:" + e, e);
  5395. // }
  5396. //
  5397. // self.baselineStatsReport = self.currentStatsReport;
  5398. // },
  5399. // self.errorCallback
  5400. // );
  5401. // },
  5402. // self.statsIntervalMilis
  5403. // );
  5404. // }
  5405. //
  5406. // if (this.config.logStats && browserSupported) {
  5407. // this.gatherStatsIntervalId = setInterval(
  5408. // function () {
  5409. // self.peerconnection.getStats(
  5410. // function (report) {
  5411. // self.addStatsToBeLogged(report.result());
  5412. // },
  5413. // function () {
  5414. // }
  5415. // );
  5416. // },
  5417. // this.GATHER_INTERVAL
  5418. // );
  5419. //
  5420. // this.logStatsIntervalId = setInterval(
  5421. // function() { self.logStats(); },
  5422. // this.LOG_INTERVAL);
  5423. // }
  5424. };
  5425. /**
  5426. * Converts the stats to the format used for logging, and saves the data in
  5427. * this.statsToBeLogged.
  5428. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  5429. */
  5430. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  5431. var self = this;
  5432. var num_records = this.statsToBeLogged.timestamps.length;
  5433. this.statsToBeLogged.timestamps.push(new Date().getTime());
  5434. reports.map(function (report) {
  5435. if (!acceptReport(report.id, report.type))
  5436. return;
  5437. var stat = self.statsToBeLogged.stats[report.id];
  5438. if (!stat) {
  5439. stat = self.statsToBeLogged.stats[report.id] = {};
  5440. }
  5441. stat.type = report.type;
  5442. report.names().map(function (name) {
  5443. if (!acceptStat(report.id, report.type, name))
  5444. return;
  5445. var values = stat[name];
  5446. if (!values) {
  5447. values = stat[name] = [];
  5448. }
  5449. while (values.length < num_records) {
  5450. values.push(null);
  5451. }
  5452. values.push(report.stat(name));
  5453. });
  5454. });
  5455. };
  5456. //FIXME:
  5457. //StatsCollector.prototype.logStats = function () {
  5458. //
  5459. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  5460. // return;
  5461. // // Reset the stats
  5462. // this.statsToBeLogged.stats = {};
  5463. // this.statsToBeLogged.timestamps = [];
  5464. //};
  5465. /**
  5466. * Stats processing logic.
  5467. */
  5468. StatsCollector.prototype.processStatsReport = function () {
  5469. if (!this.baselineStatsReport) {
  5470. return;
  5471. }
  5472. for (var idx in this.currentStatsReport) {
  5473. var now = this.currentStatsReport[idx];
  5474. try {
  5475. if (getStatValue(now, 'receiveBandwidth') ||
  5476. getStatValue(now, 'sendBandwidth')) {
  5477. this.conferenceStats.bandwidth = {
  5478. "download": Math.round(
  5479. (getStatValue(now, 'receiveBandwidth')) / 1000),
  5480. "upload": Math.round(
  5481. (getStatValue(now, 'sendBandwidth')) / 1000)
  5482. };
  5483. }
  5484. }
  5485. catch(e){/*not supported*/}
  5486. if(now.type == 'googCandidatePair')
  5487. {
  5488. var ip, type, localIP, active;
  5489. try {
  5490. ip = getStatValue(now, 'remoteAddress');
  5491. type = getStatValue(now, "transportType");
  5492. localIP = getStatValue(now, "localAddress");
  5493. active = getStatValue(now, "activeConnection");
  5494. }
  5495. catch(e){/*not supported*/}
  5496. if(!ip || !type || !localIP || active != "true")
  5497. continue;
  5498. var addressSaved = false;
  5499. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  5500. {
  5501. if(this.conferenceStats.transport[i].ip == ip &&
  5502. this.conferenceStats.transport[i].type == type &&
  5503. this.conferenceStats.transport[i].localip == localIP)
  5504. {
  5505. addressSaved = true;
  5506. }
  5507. }
  5508. if(addressSaved)
  5509. continue;
  5510. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  5511. continue;
  5512. }
  5513. if(now.type == "candidatepair")
  5514. {
  5515. if(now.state == "succeeded")
  5516. continue;
  5517. var local = this.currentStatsReport[now.localCandidateId];
  5518. var remote = this.currentStatsReport[now.remoteCandidateId];
  5519. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5520. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5521. }
  5522. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5523. now.type != "inboundrtp") {
  5524. continue;
  5525. }
  5526. var before = this.baselineStatsReport[idx];
  5527. if (!before) {
  5528. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5529. continue;
  5530. }
  5531. var ssrc = getStatValue(now, 'ssrc');
  5532. if(!ssrc)
  5533. continue;
  5534. var ssrcStats = this.ssrc2stats[ssrc];
  5535. if (!ssrcStats) {
  5536. ssrcStats = new PeerStats();
  5537. this.ssrc2stats[ssrc] = ssrcStats;
  5538. }
  5539. var isDownloadStream = true;
  5540. var key = 'packetsReceived';
  5541. var packetsNow = getStatValue(now, key);
  5542. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5543. isDownloadStream = false;
  5544. key = 'packetsSent';
  5545. packetsNow = getStatValue(now, key);
  5546. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5547. console.warn("No packetsReceived nor packetsSent stat found");
  5548. continue;
  5549. }
  5550. }
  5551. if (!packetsNow || packetsNow < 0)
  5552. packetsNow = 0;
  5553. var packetsBefore = getStatValue(before, key);
  5554. if (!packetsBefore || packetsBefore < 0)
  5555. packetsBefore = 0;
  5556. var packetRate = packetsNow - packetsBefore;
  5557. if (!packetRate || packetRate < 0)
  5558. packetRate = 0;
  5559. var currentLoss = getStatValue(now, 'packetsLost');
  5560. if (!currentLoss || currentLoss < 0)
  5561. currentLoss = 0;
  5562. var previousLoss = getStatValue(before, 'packetsLost');
  5563. if (!previousLoss || previousLoss < 0)
  5564. previousLoss = 0;
  5565. var lossRate = currentLoss - previousLoss;
  5566. if (!lossRate || lossRate < 0)
  5567. lossRate = 0;
  5568. var packetsTotal = (packetRate + lossRate);
  5569. ssrcStats.setSsrcLoss(ssrc,
  5570. {"packetsTotal": packetsTotal,
  5571. "packetsLost": lossRate,
  5572. "isDownloadStream": isDownloadStream});
  5573. var bytesReceived = 0, bytesSent = 0;
  5574. if(getStatValue(now, "bytesReceived")) {
  5575. bytesReceived = getStatValue(now, "bytesReceived") -
  5576. getStatValue(before, "bytesReceived");
  5577. }
  5578. if (getStatValue(now, "bytesSent")) {
  5579. bytesSent = getStatValue(now, "bytesSent") -
  5580. getStatValue(before, "bytesSent");
  5581. }
  5582. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5583. if (bytesReceived <= 0 || time <= 0) {
  5584. bytesReceived = 0;
  5585. } else {
  5586. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5587. }
  5588. if (bytesSent <= 0 || time <= 0) {
  5589. bytesSent = 0;
  5590. } else {
  5591. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5592. }
  5593. ssrcStats.setSsrcBitrate(ssrc, {
  5594. "download": bytesReceived,
  5595. "upload": bytesSent});
  5596. var resolution = {height: null, width: null};
  5597. try {
  5598. if (getStatValue(now, "googFrameHeightReceived") &&
  5599. getStatValue(now, "googFrameWidthReceived")) {
  5600. resolution.height =
  5601. getStatValue(now, "googFrameHeightReceived");
  5602. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5603. }
  5604. else if (getStatValue(now, "googFrameHeightSent") &&
  5605. getStatValue(now, "googFrameWidthSent")) {
  5606. resolution.height = getStatValue(now, "googFrameHeightSent");
  5607. resolution.width = getStatValue(now, "googFrameWidthSent");
  5608. }
  5609. }
  5610. catch(e){/*not supported*/}
  5611. if (resolution.height && resolution.width) {
  5612. ssrcStats.setSsrcResolution(ssrc, resolution);
  5613. } else {
  5614. ssrcStats.setSsrcResolution(ssrc, null);
  5615. }
  5616. }
  5617. var self = this;
  5618. // Jid stats
  5619. var totalPackets = {download: 0, upload: 0};
  5620. var lostPackets = {download: 0, upload: 0};
  5621. var bitrateDownload = 0;
  5622. var bitrateUpload = 0;
  5623. var resolutions = {};
  5624. Object.keys(this.ssrc2stats).forEach(
  5625. function (jid) {
  5626. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5627. function (ssrc) {
  5628. var type = "upload";
  5629. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5630. type = "download";
  5631. totalPackets[type] +=
  5632. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5633. lostPackets[type] +=
  5634. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5635. }
  5636. );
  5637. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5638. function (ssrc) {
  5639. bitrateDownload +=
  5640. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5641. bitrateUpload +=
  5642. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5643. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5644. }
  5645. );
  5646. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5647. }
  5648. );
  5649. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5650. this.conferenceStats.packetLoss = {
  5651. total:
  5652. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5653. totalPackets.download + totalPackets.upload),
  5654. download:
  5655. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5656. upload:
  5657. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5658. };
  5659. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5660. {
  5661. "bitrate": this.conferenceStats.bitrate,
  5662. "packetLoss": this.conferenceStats.packetLoss,
  5663. "bandwidth": this.conferenceStats.bandwidth,
  5664. "resolution": resolutions,
  5665. "transport": this.conferenceStats.transport
  5666. });
  5667. this.conferenceStats.transport = [];
  5668. };
  5669. /**
  5670. * Stats processing logic.
  5671. */
  5672. StatsCollector.prototype.processAudioLevelReport = function () {
  5673. if (!this.baselineAudioLevelsReport) {
  5674. return;
  5675. }
  5676. for (var idx in this.currentAudioLevelsReport) {
  5677. var now = this.currentAudioLevelsReport[idx];
  5678. //if we don't have "packetsReceived" this is local stream
  5679. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5680. continue;
  5681. }
  5682. var before = this.baselineAudioLevelsReport[idx];
  5683. if (!before) {
  5684. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5685. continue;
  5686. }
  5687. var ssrc = getStatValue(now, 'ssrc');
  5688. if (!ssrc) {
  5689. if((Date.now() - now.timestamp) < 3000)
  5690. logger.warn("No ssrc: ");
  5691. continue;
  5692. }
  5693. var ssrcStats = this.ssrc2stats[ssrc];
  5694. if (!ssrcStats) {
  5695. ssrcStats = new PeerStats();
  5696. this.ssrc2stats[ssrc] = ssrcStats;
  5697. }
  5698. // Audio level
  5699. var audioLevel = null;
  5700. try {
  5701. audioLevel = getStatValue(now, 'audioInputLevel');
  5702. if (!audioLevel)
  5703. audioLevel = getStatValue(now, 'audioOutputLevel');
  5704. }
  5705. catch(e) {/*not supported*/
  5706. logger.warn("Audio Levels are not available in the statistics.");
  5707. clearInterval(this.audioLevelsIntervalId);
  5708. return;
  5709. }
  5710. if (audioLevel) {
  5711. // TODO: can't find specs about what this value really is,
  5712. // but it seems to vary between 0 and around 32k.
  5713. audioLevel = audioLevel / 32767;
  5714. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5715. this.eventEmitter.emit(
  5716. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5717. }
  5718. }
  5719. };
  5720. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5721. },{"../../service/statistics/Events":136,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":49}],25:[function(require,module,exports){
  5722. /* global require, APP */
  5723. var LocalStats = require("./LocalStatsCollector.js");
  5724. var RTPStats = require("./RTPStatsCollector.js");
  5725. var EventEmitter = require("events");
  5726. var StatisticsEvents = require("../../service/statistics/Events");
  5727. var CallStats = require("./CallStats");
  5728. // Since callstats.io is a third party, we cannot guarantee the quality of
  5729. // their service. More specifically, their server may take noticeably long
  5730. // time to respond. Consequently, it is in our best interest (in the sense
  5731. // that the intergration of callstats.io is pretty important to us but not
  5732. // enough to allow it to prevent people from joining a conference) to (1)
  5733. // start downloading their API as soon as possible and (2) do the
  5734. // downloading asynchronously.
  5735. function loadCallStatsAPI() {
  5736. (function (d, src) {
  5737. var elementName = 'script';
  5738. var newScript = d.createElement(elementName);
  5739. var referenceNode = d.getElementsByTagName(elementName)[0];
  5740. newScript.async = true;
  5741. newScript.src = src;
  5742. referenceNode.parentNode.insertBefore(newScript, referenceNode);
  5743. })(document, 'https://api.callstats.io/static/callstats.min.js');
  5744. // FIXME At the time of this writing, we hope that the callstats.io API will
  5745. // have loaded by the time we needed it (i.e. CallStats.init is invoked).
  5746. }
  5747. var eventEmitter = new EventEmitter();
  5748. function Statistics(options) {
  5749. this.rtpStats = null;
  5750. this.eventEmitter = new EventEmitter();
  5751. this.options = options || {};
  5752. this.callStatsIntegrationEnabled
  5753. = this.options.callStatsID && this.options.callStatsSecret
  5754. // Even though AppID and AppSecret may be specified, the integration of
  5755. // callstats.io may be disabled because of globally-disallowed requests
  5756. // to any third parties.
  5757. && (this.options.disableThirdPartyRequests !== true);
  5758. if(this.callStatsIntegrationEnabled)
  5759. loadCallStatsAPI();
  5760. this.audioLevelsEnabled = !this.disableAudioLevels || true;
  5761. this.callStats = null;
  5762. }
  5763. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5764. if(!this.audioLevelsEnabled)
  5765. return;
  5766. if (this.rtpStats) {
  5767. this.rtpStats.stop();
  5768. }
  5769. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5770. this.rtpStats.start();
  5771. }
  5772. Statistics.localStats = [];
  5773. Statistics.startLocalStats = function (stream, callback) {
  5774. if(!this.audioLevelsEnabled)
  5775. return;
  5776. var localStats = new LocalStats(stream, 200, callback);
  5777. this.localStats.push(localStats);
  5778. localStats.start();
  5779. }
  5780. Statistics.prototype.addAudioLevelListener = function(listener)
  5781. {
  5782. if(!this.audioLevelsEnabled)
  5783. return;
  5784. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5785. }
  5786. Statistics.prototype.removeAudioLevelListener = function(listener)
  5787. {
  5788. if(!this.audioLevelsEnabled)
  5789. return;
  5790. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5791. }
  5792. Statistics.prototype.dispose = function () {
  5793. if(this.audioLevelsEnabled) {
  5794. Statistics.stopAllLocalStats();
  5795. this.stopRemote();
  5796. if(this.eventEmitter)
  5797. this.eventEmitter.removeAllListeners();
  5798. if(eventEmitter)
  5799. eventEmitter.removeAllListeners();
  5800. }
  5801. if(this.callstats)
  5802. {
  5803. this.callstats.sendTerminateEvent();
  5804. this.callstats = null;
  5805. }
  5806. }
  5807. Statistics.stopAllLocalStats = function () {
  5808. if(!this.audioLevelsEnabled)
  5809. return;
  5810. for(var i = 0; i < this.localStats.length; i++)
  5811. this.localStats[i].stop();
  5812. this.localStats = [];
  5813. }
  5814. Statistics.stopLocalStats = function (stream) {
  5815. if(!this.audioLevelsEnabled)
  5816. return;
  5817. for(var i = 0; i < Statistics.localStats.length; i++)
  5818. if(Statistics.localStats[i].stream === stream){
  5819. var localStats = Statistics.localStats.splice(i, 1);
  5820. localStats.stop();
  5821. break;
  5822. }
  5823. }
  5824. Statistics.prototype.stopRemote = function () {
  5825. if (this.rtpStats && this.audioLevelsEnabled) {
  5826. this.rtpStats.stop();
  5827. this.eventEmitter.emit(StatisticsEvents.STOP);
  5828. this.rtpStats = null;
  5829. }
  5830. };
  5831. /**
  5832. * Obtains audio level reported in the stats for specified peer.
  5833. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5834. * audio level.
  5835. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5836. * level.
  5837. * @returns {*} a float form 0 to 1 that represents current audio level or
  5838. * <tt>null</tt> if for any reason the value is not available
  5839. * at this time.
  5840. */
  5841. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5842. if(!this.audioLevelsEnabled)
  5843. return;
  5844. var peerStats = this.rtpStats.jid2stats[peerJid];
  5845. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5846. };
  5847. //CALSTATS METHODS
  5848. /**
  5849. * Initializes the callstats.io API.
  5850. * @param peerConnection {JingleSessionPC} the session object
  5851. * @param Settings {Settings} the settings instance. Declared in
  5852. * /modules/settings/Settings.js
  5853. */
  5854. Statistics.prototype.startCallStats = function (session, settings) {
  5855. if(this.callStatsIntegrationEnabled) {
  5856. this.callstats = new CallStats(session, settings, this.options);
  5857. }
  5858. }
  5859. /**
  5860. * Returns true if the callstats integration is enabled, otherwise returns
  5861. * false.
  5862. *
  5863. * @returns true if the callstats integration is enabled, otherwise returns
  5864. * false.
  5865. */
  5866. Statistics.prototype.isCallstatsEnabled = function () {
  5867. return this.callStatsIntegrationEnabled;
  5868. }
  5869. /**
  5870. * Notifies CallStats for connection setup errors
  5871. */
  5872. Statistics.prototype.sendSetupFailedEvent = function () {
  5873. if(this.callStatsIntegrationEnabled && this.callstats)
  5874. this.callstats.sendSetupFailedEvent();
  5875. }
  5876. /**
  5877. * Notifies CallStats for mute events
  5878. * @param mute {boolean} true for muted and false for not muted
  5879. * @param type {String} "audio"/"video"
  5880. */
  5881. Statistics.prototype.sendMuteEvent = function (muted, type) {
  5882. if(this.callStatsIntegrationEnabled && this.callstats)
  5883. this.callstats.sendMuteEvent(muted, type);
  5884. }
  5885. /**
  5886. * Notifies CallStats that getUserMedia failed.
  5887. *
  5888. * @param {Error} e error to send
  5889. */
  5890. Statistics.prototype.sendGetUserMediaFailed = function (e) {
  5891. if(this.callStatsIntegrationEnabled)
  5892. CallStats.sendGetUserMediaFailed(e, this.callstats);
  5893. };
  5894. /**
  5895. * Notifies CallStats that getUserMedia failed.
  5896. *
  5897. * @param {Error} e error to send
  5898. */
  5899. Statistics.sendGetUserMediaFailed = function (e) {
  5900. CallStats.sendGetUserMediaFailed(e, null);
  5901. };
  5902. /**
  5903. * Notifies CallStats that peer connection failed to create offer.
  5904. *
  5905. * @param {Error} e error to send
  5906. * @param {RTCPeerConnection} pc connection on which failure occured.
  5907. */
  5908. Statistics.prototype.sendCreateOfferFailed = function (e, pc) {
  5909. if(this.callStatsIntegrationEnabled)
  5910. CallStats.sendCreateOfferFailed(e, pc, this.callstats);
  5911. };
  5912. /**
  5913. * Notifies CallStats that peer connection failed to create answer.
  5914. *
  5915. * @param {Error} e error to send
  5916. * @param {RTCPeerConnection} pc connection on which failure occured.
  5917. */
  5918. Statistics.prototype.sendCreateAnswerFailed = function (e, pc) {
  5919. if(this.callStatsIntegrationEnabled)
  5920. CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
  5921. };
  5922. /**
  5923. * Notifies CallStats that peer connection failed to set local description.
  5924. *
  5925. * @param {Error} e error to send
  5926. * @param {RTCPeerConnection} pc connection on which failure occured.
  5927. */
  5928. Statistics.prototype.sendSetLocalDescFailed = function (e, pc) {
  5929. if(this.callStatsIntegrationEnabled)
  5930. CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
  5931. }
  5932. /**
  5933. * Notifies CallStats that peer connection failed to set remote description.
  5934. *
  5935. * @param {Error} e error to send
  5936. * @param {RTCPeerConnection} pc connection on which failure occured.
  5937. */
  5938. Statistics.prototype.sendSetRemoteDescFailed = function (e, pc) {
  5939. if(this.callStatsIntegrationEnabled)
  5940. CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
  5941. }
  5942. /**
  5943. * Notifies CallStats that peer connection failed to add ICE candidate.
  5944. *
  5945. * @param {Error} e error to send
  5946. * @param {RTCPeerConnection} pc connection on which failure occured.
  5947. */
  5948. Statistics.prototype.sendAddIceCandidateFailed = function (e, pc) {
  5949. if(this.callStatsIntegrationEnabled)
  5950. CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
  5951. }
  5952. /**
  5953. * Sends the given feedback through CallStats.
  5954. *
  5955. * @param overallFeedback an integer between 1 and 5 indicating the
  5956. * user feedback
  5957. * @param detailedFeedback detailed feedback from the user. Not yet used
  5958. */
  5959. Statistics.prototype.sendFeedback =
  5960. function(overallFeedback, detailedFeedback){
  5961. if(this.callStatsIntegrationEnabled && this.callstats)
  5962. this.callstats.sendFeedback(overallFeedback, detailedFeedback);
  5963. }
  5964. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5965. module.exports = Statistics;
  5966. },{"../../service/statistics/Events":136,"../../service/statistics/constants":137,"./CallStats":22,"./LocalStatsCollector.js":23,"./RTPStatsCollector.js":24,"events":45}],26:[function(require,module,exports){
  5967. /**
  5968. /**
  5969. * @const
  5970. */
  5971. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5972. /**
  5973. * Hexadecimal digits.
  5974. * @const
  5975. */
  5976. var HEX_DIGITS = '0123456789abcdef';
  5977. /**
  5978. * Generates random int within the range [min, max]
  5979. * @param min the minimum value for the generated number
  5980. * @param max the maximum value for the generated number
  5981. * @returns random int number
  5982. */
  5983. function randomInt(min, max) {
  5984. return Math.floor(Math.random() * (max - min + 1)) + min;
  5985. }
  5986. /**
  5987. * Get random element from array or string.
  5988. * @param {Array|string} arr source
  5989. * @returns array element or string character
  5990. */
  5991. function randomElement(arr) {
  5992. return arr[randomInt(0, arr.length - 1)];
  5993. }
  5994. /**
  5995. * Generate random alphanumeric string.
  5996. * @param {number} length expected string length
  5997. * @returns {string} random string of specified length
  5998. */
  5999. function randomAlphanumStr(length) {
  6000. var result = '';
  6001. for (var i = 0; i < length; i += 1) {
  6002. result += randomElement(ALPHANUM);
  6003. }
  6004. return result;
  6005. }
  6006. /**
  6007. * Exported interface.
  6008. */
  6009. var RandomUtil = {
  6010. /**
  6011. * Returns a random hex digit.
  6012. * @returns {*}
  6013. */
  6014. randomHexDigit: function() {
  6015. return randomElement(HEX_DIGITS);
  6016. },
  6017. /**
  6018. * Returns a random string of hex digits with length 'len'.
  6019. * @param len the length.
  6020. */
  6021. randomHexString: function (len) {
  6022. var ret = '';
  6023. while (len--) {
  6024. ret += this.randomHexDigit();
  6025. }
  6026. return ret;
  6027. },
  6028. randomElement: randomElement,
  6029. randomAlphanumStr: randomAlphanumStr,
  6030. randomInt: randomInt
  6031. };
  6032. module.exports = RandomUtil;
  6033. },{}],27:[function(require,module,exports){
  6034. var RandomUtil = require('./RandomUtil');
  6035. /**
  6036. * from faker.js - Copyright (c) 2014-2015 Matthew Bergman & Marak Squires
  6037. * MIT License
  6038. * http://github.com/marak/faker.js/
  6039. *
  6040. * @const
  6041. */
  6042. var names = [
  6043. "Aaliyah", "Aaron", "Abagail", "Abbey", "Abbie", "Abbigail",
  6044. "Abby", "Abdiel", "Abdul", "Abdullah", "Abe", "Abel", "Abelardo", "Abigail",
  6045. "Abigale", "Abigayle", "Abner", "Abraham", "Ada", "Adah", "Adalberto",
  6046. "Adaline", "Adam", "Adan", "Addie", "Addison", "Adela", "Adelbert", "Adele",
  6047. "Adelia", "Adeline", "Adell", "Adella", "Adelle", "Aditya", "Adolf", "Adolfo",
  6048. "Adolph", "Adolphus", "Adonis", "Adrain", "Adrian", "Adriana", "Adrianna",
  6049. "Adriel", "Adrien", "Adrienne", "Afton", "Aglae", "Agnes", "Agustin",
  6050. "Agustina", "Ahmad", "Ahmed", "Aida", "Aidan", "Aiden", "Aileen", "Aimee",
  6051. "Aisha", "Aiyana", "Akeem", "Al", "Alaina", "Alan", "Alana", "Alanis",
  6052. "Alanna", "Alayna", "Alba", "Albert", "Alberta", "Albertha", "Alberto",
  6053. "Albin", "Albina", "Alda", "Alden", "Alec", "Aleen", "Alejandra",
  6054. "Alejandrin", "Alek", "Alena", "Alene", "Alessandra", "Alessandro", "Alessia",
  6055. "Aletha", "Alex", "Alexa", "Alexander", "Alexandra", "Alexandre",
  6056. "Alexandrea", "Alexandria", "Alexandrine", "Alexandro", "Alexane", "Alexanne",
  6057. "Alexie", "Alexis", "Alexys", "Alexzander", "Alf", "Alfonso", "Alfonzo",
  6058. "Alford", "Alfred", "Alfreda", "Alfredo", "Ali", "Alia", "Alice", "Alicia",
  6059. "Alisa", "Alisha", "Alison", "Alivia", "Aliya", "Aliyah", "Aliza", "Alize",
  6060. "Allan", "Allen", "Allene", "Allie", "Allison", "Ally", "Alphonso", "Alta",
  6061. "Althea", "Alva", "Alvah", "Alvena", "Alvera", "Alverta", "Alvina", "Alvis",
  6062. "Alyce", "Alycia", "Alysa", "Alysha", "Alyson", "Alysson", "Amalia", "Amanda",
  6063. "Amani", "Amara", "Amari", "Amaya", "Amber", "Ambrose", "Amelia", "Amelie",
  6064. "Amely", "America", "Americo", "Amie", "Amina", "Amir", "Amira", "Amiya",
  6065. "Amos", "Amparo", "Amy", "Amya", "Ana", "Anabel", "Anabelle", "Anahi",
  6066. "Anais", "Anastacio", "Anastasia", "Anderson", "Andre", "Andreane",
  6067. "Andreanne", "Andres", "Andrew", "Andy", "Angel", "Angela", "Angelica",
  6068. "Angelina", "Angeline", "Angelita", "Angelo", "Angie", "Angus", "Anibal",
  6069. "Anika", "Anissa", "Anita", "Aniya", "Aniyah", "Anjali", "Anna", "Annabel",
  6070. "Annabell", "Annabelle", "Annalise", "Annamae", "Annamarie", "Anne",
  6071. "Annetta", "Annette", "Annie", "Ansel", "Ansley", "Anthony", "Antoinette",
  6072. "Antone", "Antonetta", "Antonette", "Antonia", "Antonietta", "Antonina",
  6073. "Antonio", "Antwan", "Antwon", "Anya", "April", "Ara", "Araceli", "Aracely",
  6074. "Arch", "Archibald", "Ardella", "Arden", "Ardith", "Arely", "Ari", "Ariane",
  6075. "Arianna", "Aric", "Ariel", "Arielle", "Arjun", "Arlene", "Arlie", "Arlo",
  6076. "Armand", "Armando", "Armani", "Arnaldo", "Arne", "Arno", "Arnold", "Arnoldo",
  6077. "Arnulfo", "Aron", "Art", "Arthur", "Arturo", "Arvel", "Arvid", "Arvilla",
  6078. "Aryanna", "Asa", "Asha", "Ashlee", "Ashleigh", "Ashley", "Ashly", "Ashlynn",
  6079. "Ashton", "Ashtyn", "Asia", "Assunta", "Astrid", "Athena", "Aubree", "Aubrey",
  6080. "Audie", "Audra", "Audreanne", "Audrey", "August", "Augusta", "Augustine",
  6081. "Augustus", "Aurelia", "Aurelie", "Aurelio", "Aurore", "Austen", "Austin",
  6082. "Austyn", "Autumn", "Ava", "Avery", "Avis", "Axel", "Ayana", "Ayden", "Ayla",
  6083. "Aylin", "Baby", "Bailee", "Bailey", "Barbara", "Barney", "Baron", "Barrett",
  6084. "Barry", "Bart", "Bartholome", "Barton", "Baylee", "Beatrice", "Beau",
  6085. "Beaulah", "Bell", "Bella", "Belle", "Ben", "Benedict", "Benjamin", "Bennett",
  6086. "Bennie", "Benny", "Benton", "Berenice", "Bernadette", "Bernadine", "Bernard",
  6087. "Bernardo", "Berneice", "Bernhard", "Bernice", "Bernie", "Berniece",
  6088. "Bernita", "Berry", "Bert", "Berta", "Bertha", "Bertram", "Bertrand", "Beryl",
  6089. "Bessie", "Beth", "Bethany", "Bethel", "Betsy", "Bette", "Bettie", "Betty",
  6090. "Bettye", "Beulah", "Beverly", "Bianka", "Bill", "Billie", "Billy", "Birdie",
  6091. "Blair", "Blaise", "Blake", "Blanca", "Blanche", "Blaze", "Bo", "Bobbie",
  6092. "Bobby", "Bonita", "Bonnie", "Boris", "Boyd", "Brad", "Braden", "Bradford",
  6093. "Bradley", "Bradly", "Brady", "Braeden", "Brain", "Brandi", "Brando",
  6094. "Brandon", "Brandt", "Brandy", "Brandyn", "Brannon", "Branson", "Brant",
  6095. "Braulio", "Braxton", "Brayan", "Breana", "Breanna", "Breanne", "Brenda",
  6096. "Brendan", "Brenden", "Brendon", "Brenna", "Brennan", "Brennon", "Brent",
  6097. "Bret", "Brett", "Bria", "Brian", "Briana", "Brianne", "Brice", "Bridget",
  6098. "Bridgette", "Bridie", "Brielle", "Brigitte", "Brionna", "Brisa", "Britney",
  6099. "Brittany", "Brock", "Broderick", "Brody", "Brook", "Brooke", "Brooklyn",
  6100. "Brooks", "Brown", "Bruce", "Bryana", "Bryce", "Brycen", "Bryon", "Buck",
  6101. "Bud", "Buddy", "Buford", "Bulah", "Burdette", "Burley", "Burnice", "Buster",
  6102. "Cade", "Caden", "Caesar", "Caitlyn", "Cale", "Caleb", "Caleigh", "Cali",
  6103. "Calista", "Callie", "Camden", "Cameron", "Camila", "Camilla", "Camille",
  6104. "Camren", "Camron", "Camryn", "Camylle", "Candace", "Candelario", "Candice",
  6105. "Candida", "Candido", "Cara", "Carey", "Carissa", "Carlee", "Carleton",
  6106. "Carley", "Carli", "Carlie", "Carlo", "Carlos", "Carlotta", "Carmel",
  6107. "Carmela", "Carmella", "Carmelo", "Carmen", "Carmine", "Carol", "Carolanne",
  6108. "Carole", "Carolina", "Caroline", "Carolyn", "Carolyne", "Carrie", "Carroll",
  6109. "Carson", "Carter", "Cary", "Casandra", "Casey", "Casimer", "Casimir",
  6110. "Casper", "Cassandra", "Cassandre", "Cassidy", "Cassie", "Catalina",
  6111. "Caterina", "Catharine", "Catherine", "Cathrine", "Cathryn", "Cathy", "Cayla",
  6112. "Ceasar", "Cecelia", "Cecil", "Cecile", "Cecilia", "Cedrick", "Celestine",
  6113. "Celestino", "Celia", "Celine", "Cesar", "Chad", "Chadd", "Chadrick", "Chaim",
  6114. "Chance", "Chandler", "Chanel", "Chanelle", "Charity", "Charlene", "Charles",
  6115. "Charley", "Charlie", "Charlotte", "Chase", "Chasity", "Chauncey", "Chaya",
  6116. "Chaz", "Chelsea", "Chelsey", "Chelsie", "Chesley", "Chester", "Chet",
  6117. "Cheyanne", "Cheyenne", "Chloe", "Chris", "Christ", "Christa", "Christelle",
  6118. "Christian", "Christiana", "Christina", "Christine", "Christop", "Christophe",
  6119. "Christopher", "Christy", "Chyna", "Ciara", "Cicero", "Cielo", "Cierra",
  6120. "Cindy", "Citlalli", "Clair", "Claire", "Clara", "Clarabelle", "Clare",
  6121. "Clarissa", "Clark", "Claud", "Claude", "Claudia", "Claudie", "Claudine",
  6122. "Clay", "Clemens", "Clement", "Clementina", "Clementine", "Clemmie", "Cleo",
  6123. "Cleora", "Cleta", "Cletus", "Cleve", "Cleveland", "Clifford", "Clifton",
  6124. "Clint", "Clinton", "Clotilde", "Clovis", "Cloyd", "Clyde", "Coby", "Cody",
  6125. "Colby", "Cole", "Coleman", "Colin", "Colleen", "Collin", "Colt", "Colten",
  6126. "Colton", "Columbus", "Concepcion", "Conner", "Connie", "Connor", "Conor",
  6127. "Conrad", "Constance", "Constantin", "Consuelo", "Cooper", "Cora", "Coralie",
  6128. "Corbin", "Cordelia", "Cordell", "Cordia", "Cordie", "Corene", "Corine",
  6129. "Cornelius", "Cornell", "Corrine", "Cortez", "Cortney", "Cory", "Coty",
  6130. "Courtney", "Coy", "Craig", "Crawford", "Creola", "Cristal", "Cristian",
  6131. "Cristina", "Cristobal", "Cristopher", "Cruz", "Crystal", "Crystel", "Cullen",
  6132. "Curt", "Curtis", "Cydney", "Cynthia", "Cyril", "Cyrus", "Dagmar", "Dahlia",
  6133. "Daija", "Daisha", "Daisy", "Dakota", "Dale", "Dallas", "Dallin", "Dalton",
  6134. "Damaris", "Dameon", "Damian", "Damien", "Damion", "Damon", "Dan", "Dana",
  6135. "Dandre", "Dane", "D'angelo", "Dangelo", "Danial", "Daniela", "Daniella",
  6136. "Danielle", "Danika", "Dannie", "Danny", "Dante", "Danyka", "Daphne",
  6137. "Daphnee", "Daphney", "Darby", "Daren", "Darian", "Dariana", "Darien",
  6138. "Dario", "Darion", "Darius", "Darlene", "Daron", "Darrel", "Darrell",
  6139. "Darren", "Darrick", "Darrin", "Darrion", "Darron", "Darryl", "Darwin",
  6140. "Daryl", "Dashawn", "Dasia", "Dave", "David", "Davin", "Davion", "Davon",
  6141. "Davonte", "Dawn", "Dawson", "Dax", "Dayana", "Dayna", "Dayne", "Dayton",
  6142. "Dean", "Deangelo", "Deanna", "Deborah", "Declan", "Dedric", "Dedrick", "Dee",
  6143. "Deion", "Deja", "Dejah", "Dejon", "Dejuan", "Delaney", "Delbert", "Delfina",
  6144. "Delia", "Delilah", "Dell", "Della", "Delmer", "Delores", "Delpha", "Delphia",
  6145. "Delphine", "Delta", "Demarco", "Demarcus", "Demario", "Demetris",
  6146. "Demetrius", "Demond", "Dena", "Denis", "Dennis", "Deon", "Deondre",
  6147. "Deontae", "Deonte", "Dereck", "Derek", "Derick", "Deron", "Derrick",
  6148. "Deshaun", "Deshawn", "Desiree", "Desmond", "Dessie", "Destany", "Destin",
  6149. "Destinee", "Destiney", "Destini", "Destiny", "Devan", "Devante", "Deven",
  6150. "Devin", "Devon", "Devonte", "Devyn", "Dewayne", "Dewitt", "Dexter",
  6151. "Diamond", "Diana", "Dianna", "Diego", "Dillan", "Dillon", "Dimitri", "Dina",
  6152. "Dino", "Dion", "Dixie", "Dock", "Dolly", "Dolores", "Domenic", "Domenica",
  6153. "Domenick", "Domenico", "Domingo", "Dominic", "Dominique", "Don", "Donald",
  6154. "Donato", "Donavon", "Donna", "Donnell", "Donnie", "Donny", "Dora", "Dorcas",
  6155. "Dorian", "Doris", "Dorothea", "Dorothy", "Dorris", "Dortha", "Dorthy",
  6156. "Doug", "Douglas", "Dovie", "Doyle", "Drake", "Drew", "Duane", "Dudley",
  6157. "Dulce", "Duncan", "Durward", "Dustin", "Dusty", "Dwight", "Dylan", "Earl",
  6158. "Earlene", "Earline", "Earnest", "Earnestine", "Easter", "Easton", "Ebba",
  6159. "Ebony", "Ed", "Eda", "Edd", "Eddie", "Eden", "Edgar", "Edgardo", "Edison",
  6160. "Edmond", "Edmund", "Edna", "Eduardo", "Edward", "Edwardo", "Edwin", "Edwina",
  6161. "Edyth", "Edythe", "Effie", "Efrain", "Efren", "Eileen", "Einar", "Eino",
  6162. "Eladio", "Elaina", "Elbert", "Elda", "Eldon", "Eldora", "Eldred", "Eldridge",
  6163. "Eleanora", "Eleanore", "Eleazar", "Electa", "Elena", "Elenor", "Elenora",
  6164. "Eleonore", "Elfrieda", "Eli", "Elian", "Eliane", "Elias", "Eliezer",
  6165. "Elijah", "Elinor", "Elinore", "Elisa", "Elisabeth", "Elise", "Eliseo",
  6166. "Elisha", "Elissa", "Eliza", "Elizabeth", "Ella", "Ellen", "Ellie", "Elliot",
  6167. "Elliott", "Ellis", "Ellsworth", "Elmer", "Elmira", "Elmo", "Elmore", "Elna",
  6168. "Elnora", "Elody", "Eloisa", "Eloise", "Elouise", "Eloy", "Elroy", "Elsa",
  6169. "Else", "Elsie", "Elta", "Elton", "Elva", "Elvera", "Elvie", "Elvis", "Elwin",
  6170. "Elwyn", "Elyse", "Elyssa", "Elza", "Emanuel", "Emelia", "Emelie", "Emely",
  6171. "Emerald", "Emerson", "Emery", "Emie", "Emil", "Emile", "Emilia", "Emiliano",
  6172. "Emilie", "Emilio", "Emily", "Emma", "Emmalee", "Emmanuel", "Emmanuelle",
  6173. "Emmet", "Emmett", "Emmie", "Emmitt", "Emmy", "Emory", "Ena", "Enid", "Enoch",
  6174. "Enola", "Enos", "Enrico", "Enrique", "Ephraim", "Era", "Eriberto", "Eric",
  6175. "Erica", "Erich", "Erick", "Ericka", "Erik", "Erika", "Erin", "Erling",
  6176. "Erna", "Ernest", "Ernestina", "Ernestine", "Ernesto", "Ernie", "Ervin",
  6177. "Erwin", "Eryn", "Esmeralda", "Esperanza", "Esta", "Esteban", "Estefania",
  6178. "Estel", "Estell", "Estella", "Estelle", "Estevan", "Esther", "Estrella",
  6179. "Etha", "Ethan", "Ethel", "Ethelyn", "Ethyl", "Ettie", "Eudora", "Eugene",
  6180. "Eugenia", "Eula", "Eulah", "Eulalia", "Euna", "Eunice", "Eusebio", "Eva",
  6181. "Evalyn", "Evan", "Evangeline", "Evans", "Eve", "Eveline", "Evelyn",
  6182. "Everardo", "Everett", "Everette", "Evert", "Evie", "Ewald", "Ewell",
  6183. "Ezekiel", "Ezequiel", "Ezra", "Fabian", "Fabiola", "Fae", "Fannie", "Fanny",
  6184. "Fatima", "Faustino", "Fausto", "Favian", "Fay", "Faye", "Federico",
  6185. "Felicia", "Felicita", "Felicity", "Felipa", "Felipe", "Felix", "Felton",
  6186. "Fermin", "Fern", "Fernando", "Ferne", "Fidel", "Filiberto", "Filomena",
  6187. "Finn", "Fiona", "Flavie", "Flavio", "Fleta", "Fletcher", "Flo", "Florence",
  6188. "Florencio", "Florian", "Florida", "Florine", "Flossie", "Floy", "Floyd",
  6189. "Ford", "Forest", "Forrest", "Foster", "Frances", "Francesca", "Francesco",
  6190. "Francis", "Francisca", "Francisco", "Franco", "Frank", "Frankie", "Franz",
  6191. "Fred", "Freda", "Freddie", "Freddy", "Frederic", "Frederick", "Frederik",
  6192. "Frederique", "Fredrick", "Fredy", "Freeda", "Freeman", "Freida", "Frida",
  6193. "Frieda", "Friedrich", "Fritz", "Furman", "Gabe", "Gabriel", "Gabriella",
  6194. "Gabrielle", "Gaetano", "Gage", "Gail", "Gardner", "Garett", "Garfield",
  6195. "Garland", "Garnet", "Garnett", "Garret", "Garrett", "Garrick", "Garrison",
  6196. "Garry", "Garth", "Gaston", "Gavin", "Gay", "Gayle", "Gaylord", "Gene",
  6197. "General", "Genesis", "Genevieve", "Gennaro", "Genoveva", "Geo", "Geoffrey",
  6198. "George", "Georgette", "Georgiana", "Georgianna", "Geovanni", "Geovanny",
  6199. "Geovany", "Gerald", "Geraldine", "Gerard", "Gerardo", "Gerda", "Gerhard",
  6200. "Germaine", "German", "Gerry", "Gerson", "Gertrude", "Gia", "Gianni",
  6201. "Gideon", "Gilbert", "Gilberto", "Gilda", "Giles", "Gillian", "Gina", "Gino",
  6202. "Giovani", "Giovanna", "Giovanni", "Giovanny", "Gisselle", "Giuseppe",
  6203. "Gladyce", "Gladys", "Glen", "Glenda", "Glenna", "Glennie", "Gloria",
  6204. "Godfrey", "Golda", "Golden", "Gonzalo", "Gordon", "Grace", "Gracie",
  6205. "Graciela", "Grady", "Graham", "Grant", "Granville", "Grayce", "Grayson",
  6206. "Green", "Greg", "Gregg", "Gregoria", "Gregorio", "Gregory", "Greta",
  6207. "Gretchen", "Greyson", "Griffin", "Grover", "Guadalupe", "Gudrun", "Guido",
  6208. "Guillermo", "Guiseppe", "Gunnar", "Gunner", "Gus", "Gussie", "Gust",
  6209. "Gustave", "Guy", "Gwen", "Gwendolyn", "Hadley", "Hailee", "Hailey", "Hailie",
  6210. "Hal", "Haleigh", "Haley", "Halie", "Halle", "Hallie", "Hank", "Hanna",
  6211. "Hannah", "Hans", "Hardy", "Harley", "Harmon", "Harmony", "Harold",
  6212. "Harrison", "Harry", "Harvey", "Haskell", "Hassan", "Hassie", "Hattie",
  6213. "Haven", "Hayden", "Haylee", "Hayley", "Haylie", "Hazel", "Hazle", "Heath",
  6214. "Heather", "Heaven", "Heber", "Hector", "Heidi", "Helen", "Helena", "Helene",
  6215. "Helga", "Hellen", "Helmer", "Heloise", "Henderson", "Henri", "Henriette",
  6216. "Henry", "Herbert", "Herman", "Hermann", "Hermina", "Herminia", "Herminio",
  6217. "Hershel", "Herta", "Hertha", "Hester", "Hettie", "Hilario", "Hilbert",
  6218. "Hilda", "Hildegard", "Hillard", "Hillary", "Hilma", "Hilton", "Hipolito",
  6219. "Hiram", "Hobart", "Holden", "Hollie", "Hollis", "Holly", "Hope", "Horace",
  6220. "Horacio", "Hortense", "Hosea", "Houston", "Howard", "Howell", "Hoyt",
  6221. "Hubert", "Hudson", "Hugh", "Hulda", "Humberto", "Hunter", "Hyman", "Ian",
  6222. "Ibrahim", "Icie", "Ida", "Idell", "Idella", "Ignacio", "Ignatius", "Ike",
  6223. "Ila", "Ilene", "Iliana", "Ima", "Imani", "Imelda", "Immanuel", "Imogene",
  6224. "Ines", "Irma", "Irving", "Irwin", "Isaac", "Isabel", "Isabell", "Isabella",
  6225. "Isabelle", "Isac", "Isadore", "Isai", "Isaiah", "Isaias", "Isidro", "Ismael",
  6226. "Isobel", "Isom", "Israel", "Issac", "Itzel", "Iva", "Ivah", "Ivory", "Ivy",
  6227. "Izabella", "Izaiah", "Jabari", "Jace", "Jacey", "Jacinthe", "Jacinto",
  6228. "Jack", "Jackeline", "Jackie", "Jacklyn", "Jackson", "Jacky", "Jaclyn",
  6229. "Jacquelyn", "Jacques", "Jacynthe", "Jada", "Jade", "Jaden", "Jadon", "Jadyn",
  6230. "Jaeden", "Jaida", "Jaiden", "Jailyn", "Jaime", "Jairo", "Jakayla", "Jake",
  6231. "Jakob", "Jaleel", "Jalen", "Jalon", "Jalyn", "Jamaal", "Jamal", "Jamar",
  6232. "Jamarcus", "Jamel", "Jameson", "Jamey", "Jamie", "Jamil", "Jamir", "Jamison",
  6233. "Jammie", "Jan", "Jana", "Janae", "Jane", "Janelle", "Janessa", "Janet",
  6234. "Janice", "Janick", "Janie", "Janis", "Janiya", "Jannie", "Jany", "Jaquan",
  6235. "Jaquelin", "Jaqueline", "Jared", "Jaren", "Jarod", "Jaron", "Jarred",
  6236. "Jarrell", "Jarret", "Jarrett", "Jarrod", "Jarvis", "Jasen", "Jasmin",
  6237. "Jason", "Jasper", "Jaunita", "Javier", "Javon", "Javonte", "Jay", "Jayce",
  6238. "Jaycee", "Jayda", "Jayde", "Jayden", "Jaydon", "Jaylan", "Jaylen", "Jaylin",
  6239. "Jaylon", "Jayme", "Jayne", "Jayson", "Jazlyn", "Jazmin", "Jazmyn", "Jazmyne",
  6240. "Jean", "Jeanette", "Jeanie", "Jeanne", "Jed", "Jedediah", "Jedidiah", "Jeff",
  6241. "Jefferey", "Jeffery", "Jeffrey", "Jeffry", "Jena", "Jenifer", "Jennie",
  6242. "Jennifer", "Jennings", "Jennyfer", "Jensen", "Jerad", "Jerald", "Jeramie",
  6243. "Jeramy", "Jerel", "Jeremie", "Jeremy", "Jermain", "Jermaine", "Jermey",
  6244. "Jerod", "Jerome", "Jeromy", "Jerrell", "Jerrod", "Jerrold", "Jerry", "Jess",
  6245. "Jesse", "Jessica", "Jessie", "Jessika", "Jessy", "Jessyca", "Jesus", "Jett",
  6246. "Jettie", "Jevon", "Jewel", "Jewell", "Jillian", "Jimmie", "Jimmy", "Jo",
  6247. "Joan", "Joana", "Joanie", "Joanne", "Joannie", "Joanny", "Joany", "Joaquin",
  6248. "Jocelyn", "Jodie", "Jody", "Joe", "Joel", "Joelle", "Joesph", "Joey",
  6249. "Johan", "Johann", "Johanna", "Johathan", "John", "Johnathan", "Johnathon",
  6250. "Johnnie", "Johnny", "Johnpaul", "Johnson", "Jolie", "Jon", "Jonas",
  6251. "Jonatan", "Jonathan", "Jonathon", "Jordan", "Jordane", "Jordi", "Jordon",
  6252. "Jordy", "Jordyn", "Jorge", "Jose", "Josefa", "Josefina", "Joseph",
  6253. "Josephine", "Josh", "Joshua", "Joshuah", "Josiah", "Josiane", "Josianne",
  6254. "Josie", "Josue", "Jovan", "Jovani", "Jovanny", "Jovany", "Joy", "Joyce",
  6255. "Juana", "Juanita", "Judah", "Judd", "Jude", "Judge", "Judson", "Judy",
  6256. "Jules", "Julia", "Julian", "Juliana", "Julianne", "Julie", "Julien",
  6257. "Juliet", "Julio", "Julius", "June", "Junior", "Junius", "Justen", "Justice",
  6258. "Justina", "Justine", "Juston", "Justus", "Justyn", "Juvenal", "Juwan",
  6259. "Kacey", "Kaci", "Kacie", "Kade", "Kaden", "Kadin", "Kaela", "Kaelyn", "Kaia",
  6260. "Kailee", "Kailey", "Kailyn", "Kaitlin", "Kaitlyn", "Kale", "Kaleb",
  6261. "Kaleigh", "Kaley", "Kali", "Kallie", "Kameron", "Kamille", "Kamren",
  6262. "Kamron", "Kamryn", "Kane", "Kara", "Kareem", "Karelle", "Karen", "Kari",
  6263. "Kariane", "Karianne", "Karina", "Karine", "Karl", "Karlee", "Karley",
  6264. "Karli", "Karlie", "Karolann", "Karson", "Kasandra", "Kasey", "Kassandra",
  6265. "Katarina", "Katelin", "Katelyn", "Katelynn", "Katharina", "Katherine",
  6266. "Katheryn", "Kathleen", "Kathlyn", "Kathryn", "Kathryne", "Katlyn", "Katlynn",
  6267. "Katrina", "Katrine", "Kattie", "Kavon", "Kay", "Kaya", "Kaycee", "Kayden",
  6268. "Kayla", "Kaylah", "Kaylee", "Kayleigh", "Kayley", "Kayli", "Kaylie",
  6269. "Kaylin", "Keagan", "Keanu", "Keara", "Keaton", "Keegan", "Keeley", "Keely",
  6270. "Keenan", "Keira", "Keith", "Kellen", "Kelley", "Kelli", "Kellie", "Kelly",
  6271. "Kelsi", "Kelsie", "Kelton", "Kelvin", "Ken", "Kendall", "Kendra", "Kendrick",
  6272. "Kenna", "Kennedi", "Kennedy", "Kenneth", "Kennith", "Kenny", "Kenton",
  6273. "Kenya", "Kenyatta", "Kenyon", "Keon", "Keshaun", "Keshawn", "Keven", "Kevin",
  6274. "Kevon", "Keyon", "Keyshawn", "Khalid", "Khalil", "Kian", "Kiana", "Kianna",
  6275. "Kiara", "Kiarra", "Kiel", "Kiera", "Kieran", "Kiley", "Kim", "Kimberly",
  6276. "King", "Kip", "Kira", "Kirk", "Kirsten", "Kirstin", "Kitty", "Kobe", "Koby",
  6277. "Kody", "Kolby", "Kole", "Korbin", "Korey", "Kory", "Kraig", "Kris", "Krista",
  6278. "Kristian", "Kristin", "Kristina", "Kristofer", "Kristoffer", "Kristopher",
  6279. "Kristy", "Krystal", "Krystel", "Krystina", "Kurt", "Kurtis", "Kyla", "Kyle",
  6280. "Kylee", "Kyleigh", "Kyler", "Kylie", "Kyra", "Lacey", "Lacy", "Ladarius",
  6281. "Lafayette", "Laila", "Laisha", "Lamar", "Lambert", "Lamont", "Lance",
  6282. "Landen", "Lane", "Laney", "Larissa", "Laron", "Larry", "Larue", "Laura",
  6283. "Laurel", "Lauren", "Laurence", "Lauretta", "Lauriane", "Laurianne", "Laurie",
  6284. "Laurine", "Laury", "Lauryn", "Lavada", "Lavern", "Laverna", "Laverne",
  6285. "Lavina", "Lavinia", "Lavon", "Lavonne", "Lawrence", "Lawson", "Layla",
  6286. "Layne", "Lazaro", "Lea", "Leann", "Leanna", "Leanne", "Leatha", "Leda",
  6287. "Lee", "Leif", "Leila", "Leilani", "Lela", "Lelah", "Leland", "Lelia",
  6288. "Lempi", "Lemuel", "Lenna", "Lennie", "Lenny", "Lenora", "Lenore", "Leo",
  6289. "Leola", "Leon", "Leonard", "Leonardo", "Leone", "Leonel", "Leonie", "Leonor",
  6290. "Leonora", "Leopold", "Leopoldo", "Leora", "Lera", "Lesley", "Leslie",
  6291. "Lesly", "Lessie", "Lester", "Leta", "Letha", "Letitia", "Levi", "Lew",
  6292. "Lewis", "Lexi", "Lexie", "Lexus", "Lia", "Liam", "Liana", "Libbie", "Libby",
  6293. "Lila", "Lilian", "Liliana", "Liliane", "Lilla", "Lillian", "Lilliana",
  6294. "Lillie", "Lilly", "Lily", "Lilyan", "Lina", "Lincoln", "Linda", "Lindsay",
  6295. "Lindsey", "Linnea", "Linnie", "Linwood", "Lionel", "Lisa", "Lisandro",
  6296. "Lisette", "Litzy", "Liza", "Lizeth", "Lizzie", "Llewellyn", "Lloyd", "Logan",
  6297. "Lois", "Lola", "Lolita", "Loma", "Lon", "London", "Lonie", "Lonnie", "Lonny",
  6298. "Lonzo", "Lora", "Loraine", "Loren", "Lorena", "Lorenz", "Lorenza", "Lorenzo",
  6299. "Lori", "Lorine", "Lorna", "Lottie", "Lou", "Louie", "Louisa", "Lourdes",
  6300. "Louvenia", "Lowell", "Loy", "Loyal", "Loyce", "Lucas", "Luciano", "Lucie",
  6301. "Lucienne", "Lucile", "Lucinda", "Lucio", "Lucious", "Lucius", "Lucy",
  6302. "Ludie", "Ludwig", "Lue", "Luella", "Luigi", "Luis", "Luisa", "Lukas", "Lula",
  6303. "Lulu", "Luna", "Lupe", "Lura", "Lurline", "Luther", "Luz", "Lyda", "Lydia",
  6304. "Lyla", "Lynn", "Lyric", "Lysanne", "Mabel", "Mabelle", "Mable", "Mac",
  6305. "Macey", "Maci", "Macie", "Mack", "Mackenzie", "Macy", "Madaline", "Madalyn",
  6306. "Maddison", "Madeline", "Madelyn", "Madelynn", "Madge", "Madie", "Madilyn",
  6307. "Madisen", "Madison", "Madisyn", "Madonna", "Madyson", "Mae", "Maegan",
  6308. "Maeve", "Mafalda", "Magali", "Magdalen", "Magdalena", "Maggie", "Magnolia",
  6309. "Magnus", "Maia", "Maida", "Maiya", "Major", "Makayla", "Makenna", "Makenzie",
  6310. "Malachi", "Malcolm", "Malika", "Malinda", "Mallie", "Mallory", "Malvina",
  6311. "Mandy", "Manley", "Manuel", "Manuela", "Mara", "Marc", "Marcel", "Marcelina",
  6312. "Marcelino", "Marcella", "Marcelle", "Marcellus", "Marcelo", "Marcia",
  6313. "Marco", "Marcos", "Marcus", "Margaret", "Margarete", "Margarett",
  6314. "Margaretta", "Margarette", "Margarita", "Marge", "Margie", "Margot",
  6315. "Margret", "Marguerite", "Maria", "Mariah", "Mariam", "Marian", "Mariana",
  6316. "Mariane", "Marianna", "Marianne", "Mariano", "Maribel", "Marie", "Mariela",
  6317. "Marielle", "Marietta", "Marilie", "Marilou", "Marilyne", "Marina", "Mario",
  6318. "Marion", "Marisa", "Marisol", "Maritza", "Marjolaine", "Marjorie", "Marjory",
  6319. "Mark", "Markus", "Marlee", "Marlen", "Marlene", "Marley", "Marlin", "Marlon",
  6320. "Marques", "Marquis", "Marquise", "Marshall", "Marta", "Martin", "Martina",
  6321. "Martine", "Marty", "Marvin", "Mary", "Maryam", "Maryjane", "Maryse", "Mason",
  6322. "Mateo", "Mathew", "Mathias", "Mathilde", "Matilda", "Matilde", "Matt",
  6323. "Matteo", "Mattie", "Maud", "Maude", "Maudie", "Maureen", "Maurice",
  6324. "Mauricio", "Maurine", "Maverick", "Mavis", "Max", "Maxie", "Maxime",
  6325. "Maximilian", "Maximillia", "Maximillian", "Maximo", "Maximus", "Maxine",
  6326. "Maxwell", "May", "Maya", "Maybell", "Maybelle", "Maye", "Maymie", "Maynard",
  6327. "Mayra", "Mazie", "Mckayla", "Mckenna", "Mckenzie", "Meagan", "Meaghan",
  6328. "Meda", "Megane", "Meggie", "Meghan", "Mekhi", "Melany", "Melba", "Melisa",
  6329. "Melissa", "Mellie", "Melody", "Melvin", "Melvina", "Melyna", "Melyssa",
  6330. "Mercedes", "Meredith", "Merl", "Merle", "Merlin", "Merritt", "Mertie",
  6331. "Mervin", "Meta", "Mia", "Micaela", "Micah", "Michael", "Michaela", "Michale",
  6332. "Micheal", "Michel", "Michele", "Michelle", "Miguel", "Mikayla", "Mike",
  6333. "Mikel", "Milan", "Miles", "Milford", "Miller", "Millie", "Milo", "Milton",
  6334. "Mina", "Minerva", "Minnie", "Miracle", "Mireille", "Mireya", "Misael",
  6335. "Missouri", "Misty", "Mitchel", "Mitchell", "Mittie", "Modesta", "Modesto",
  6336. "Mohamed", "Mohammad", "Mohammed", "Moises", "Mollie", "Molly", "Mona",
  6337. "Monica", "Monique", "Monroe", "Monserrat", "Monserrate", "Montana", "Monte",
  6338. "Monty", "Morgan", "Moriah", "Morris", "Mortimer", "Morton", "Mose", "Moses",
  6339. "Moshe", "Mossie", "Mozell", "Mozelle", "Muhammad", "Muriel", "Murl",
  6340. "Murphy", "Murray", "Mustafa", "Mya", "Myah", "Mylene", "Myles", "Myra",
  6341. "Myriam", "Myrl", "Myrna", "Myron", "Myrtice", "Myrtie", "Myrtis", "Myrtle",
  6342. "Nadia", "Nakia", "Name", "Nannie", "Naomi", "Naomie", "Napoleon", "Narciso",
  6343. "Nash", "Nasir", "Nat", "Natalia", "Natalie", "Natasha", "Nathan",
  6344. "Nathanael", "Nathanial", "Nathaniel", "Nathen", "Nayeli", "Neal", "Ned",
  6345. "Nedra", "Neha", "Neil", "Nelda", "Nella", "Nelle", "Nellie", "Nels",
  6346. "Nelson", "Neoma", "Nestor", "Nettie", "Neva", "Newell", "Newton", "Nia",
  6347. "Nicholas", "Nicholaus", "Nichole", "Nick", "Nicklaus", "Nickolas", "Nico",
  6348. "Nicola", "Nicolas", "Nicole", "Nicolette", "Nigel", "Nikita", "Nikki",
  6349. "Nikko", "Niko", "Nikolas", "Nils", "Nina", "Noah", "Noble", "Noe", "Noel",
  6350. "Noelia", "Noemi", "Noemie", "Noemy", "Nola", "Nolan", "Nona", "Nora",
  6351. "Norbert", "Norberto", "Norene", "Norma", "Norris", "Norval", "Norwood",
  6352. "Nova", "Novella", "Nya", "Nyah", "Nyasia", "Obie", "Oceane", "Ocie",
  6353. "Octavia", "Oda", "Odell", "Odessa", "Odie", "Ofelia", "Okey", "Ola", "Olaf",
  6354. "Ole", "Olen", "Oleta", "Olga", "Olin", "Oliver", "Ollie", "Oma", "Omari",
  6355. "Omer", "Ona", "Onie", "Opal", "Ophelia", "Ora", "Oral", "Oran", "Oren",
  6356. "Orie", "Orin", "Orion", "Orland", "Orlando", "Orlo", "Orpha", "Orrin",
  6357. "Orval", "Orville", "Osbaldo", "Osborne", "Oscar", "Osvaldo", "Oswald",
  6358. "Oswaldo", "Otha", "Otho", "Otilia", "Otis", "Ottilie", "Ottis", "Otto",
  6359. "Ova", "Owen", "Ozella", "Pablo", "Paige", "Palma", "Pamela", "Pansy",
  6360. "Paolo", "Paris", "Parker", "Pascale", "Pasquale", "Pat", "Patience",
  6361. "Patricia", "Patrick", "Patsy", "Pattie", "Paul", "Paula", "Pauline",
  6362. "Paxton", "Payton", "Pearl", "Pearlie", "Pearline", "Pedro", "Peggie",
  6363. "Penelope", "Percival", "Percy", "Perry", "Pete", "Peter", "Petra", "Peyton",
  6364. "Philip", "Phoebe", "Phyllis", "Pierce", "Pierre", "Pietro", "Pink", "Pinkie",
  6365. "Piper", "Polly", "Porter", "Precious", "Presley", "Preston", "Price",
  6366. "Prince", "Princess", "Priscilla", "Providenci", "Prudence", "Queen",
  6367. "Queenie", "Quentin", "Quincy", "Quinn", "Quinten", "Quinton", "Rachael",
  6368. "Rachel", "Rachelle", "Rae", "Raegan", "Rafael", "Rafaela", "Raheem",
  6369. "Rahsaan", "Rahul", "Raina", "Raleigh", "Ralph", "Ramiro", "Ramon", "Ramona",
  6370. "Randal", "Randall", "Randi", "Randy", "Ransom", "Raoul", "Raphael",
  6371. "Raphaelle", "Raquel", "Rashad", "Rashawn", "Rasheed", "Raul", "Raven", "Ray",
  6372. "Raymond", "Raymundo", "Reagan", "Reanna", "Reba", "Rebeca", "Rebecca",
  6373. "Rebeka", "Rebekah", "Reece", "Reed", "Reese", "Regan", "Reggie", "Reginald",
  6374. "Reid", "Reilly", "Reina", "Reinhold", "Remington", "Rene", "Renee", "Ressie",
  6375. "Reta", "Retha", "Retta", "Reuben", "Reva", "Rex", "Rey", "Reyes", "Reymundo",
  6376. "Reyna", "Reynold", "Rhea", "Rhett", "Rhianna", "Rhiannon", "Rhoda",
  6377. "Ricardo", "Richard", "Richie", "Richmond", "Rick", "Rickey", "Rickie",
  6378. "Ricky", "Rico", "Rigoberto", "Riley", "Rita", "River", "Robb", "Robbie",
  6379. "Robert", "Roberta", "Roberto", "Robin", "Robyn", "Rocio", "Rocky", "Rod",
  6380. "Roderick", "Rodger", "Rodolfo", "Rodrick", "Rodrigo", "Roel", "Rogelio",
  6381. "Roger", "Rogers", "Rolando", "Rollin", "Roma", "Romaine", "Roman", "Ron",
  6382. "Ronaldo", "Ronny", "Roosevelt", "Rory", "Rosa", "Rosalee", "Rosalia",
  6383. "Rosalind", "Rosalinda", "Rosalyn", "Rosamond", "Rosanna", "Rosario",
  6384. "Roscoe", "Rose", "Rosella", "Roselyn", "Rosemarie", "Rosemary", "Rosendo",
  6385. "Rosetta", "Rosie", "Rosina", "Roslyn", "Ross", "Rossie", "Rowan", "Rowena",
  6386. "Rowland", "Roxane", "Roxanne", "Roy", "Royal", "Royce", "Rozella", "Ruben",
  6387. "Rubie", "Ruby", "Rubye", "Rudolph", "Rudy", "Rupert", "Russ", "Russel",
  6388. "Russell", "Rusty", "Ruth", "Ruthe", "Ruthie", "Ryan", "Ryann", "Ryder",
  6389. "Rylan", "Rylee", "Ryleigh", "Ryley", "Sabina", "Sabrina", "Sabryna", "Sadie",
  6390. "Sadye", "Sage", "Saige", "Sallie", "Sally", "Salma", "Salvador", "Salvatore",
  6391. "Sam", "Samanta", "Samantha", "Samara", "Samir", "Sammie", "Sammy", "Samson",
  6392. "Sandra", "Sandrine", "Sandy", "Sanford", "Santa", "Santiago", "Santina",
  6393. "Santino", "Santos", "Sarah", "Sarai", "Sarina", "Sasha", "Saul", "Savanah",
  6394. "Savanna", "Savannah", "Savion", "Scarlett", "Schuyler", "Scot", "Scottie",
  6395. "Scotty", "Seamus", "Sean", "Sebastian", "Sedrick", "Selena", "Selina",
  6396. "Selmer", "Serena", "Serenity", "Seth", "Shad", "Shaina", "Shakira", "Shana",
  6397. "Shane", "Shanel", "Shanelle", "Shania", "Shanie", "Shaniya", "Shanna",
  6398. "Shannon", "Shanny", "Shanon", "Shany", "Sharon", "Shaun", "Shawn", "Shawna",
  6399. "Shaylee", "Shayna", "Shayne", "Shea", "Sheila", "Sheldon", "Shemar",
  6400. "Sheridan", "Sherman", "Sherwood", "Shirley", "Shyann", "Shyanne", "Sibyl",
  6401. "Sid", "Sidney", "Sienna", "Sierra", "Sigmund", "Sigrid", "Sigurd", "Silas",
  6402. "Sim", "Simeon", "Simone", "Sincere", "Sister", "Skye", "Skyla", "Skylar",
  6403. "Sofia", "Soledad", "Solon", "Sonia", "Sonny", "Sonya", "Sophia", "Sophie",
  6404. "Spencer", "Stacey", "Stacy", "Stan", "Stanford", "Stanley", "Stanton",
  6405. "Stefan", "Stefanie", "Stella", "Stephan", "Stephania", "Stephanie",
  6406. "Stephany", "Stephen", "Stephon", "Sterling", "Steve", "Stevie", "Stewart",
  6407. "Stone", "Stuart", "Summer", "Sunny", "Susan", "Susana", "Susanna", "Susie",
  6408. "Suzanne", "Sven", "Syble", "Sydnee", "Sydney", "Sydni", "Sydnie", "Sylvan",
  6409. "Sylvester", "Sylvia", "Tabitha", "Tad", "Talia", "Talon", "Tamara", "Tamia",
  6410. "Tania", "Tanner", "Tanya", "Tara", "Taryn", "Tate", "Tatum", "Tatyana",
  6411. "Taurean", "Tavares", "Taya", "Taylor", "Teagan", "Ted", "Telly", "Terence",
  6412. "Teresa", "Terrance", "Terrell", "Terrence", "Terrill", "Terry", "Tess",
  6413. "Tessie", "Tevin", "Thad", "Thaddeus", "Thalia", "Thea", "Thelma", "Theo",
  6414. "Theodora", "Theodore", "Theresa", "Therese", "Theresia", "Theron", "Thomas",
  6415. "Thora", "Thurman", "Tia", "Tiana", "Tianna", "Tiara", "Tierra", "Tiffany",
  6416. "Tillman", "Timmothy", "Timmy", "Timothy", "Tina", "Tito", "Titus", "Tobin",
  6417. "Toby", "Tod", "Tom", "Tomas", "Tomasa", "Tommie", "Toney", "Toni", "Tony",
  6418. "Torey", "Torrance", "Torrey", "Toy", "Trace", "Tracey", "Tracy", "Travis",
  6419. "Travon", "Tre", "Tremaine", "Tremayne", "Trent", "Trenton", "Tressa",
  6420. "Tressie", "Treva", "Trever", "Trevion", "Trevor", "Trey", "Trinity",
  6421. "Trisha", "Tristian", "Tristin", "Triston", "Troy", "Trudie", "Trycia",
  6422. "Trystan", "Turner", "Twila", "Tyler", "Tyra", "Tyree", "Tyreek", "Tyrel",
  6423. "Tyrell", "Tyrese", "Tyrique", "Tyshawn", "Tyson", "Ubaldo", "Ulices",
  6424. "Ulises", "Una", "Unique", "Urban", "Uriah", "Uriel", "Ursula", "Vada",
  6425. "Valentin", "Valentina", "Valentine", "Valerie", "Vallie", "Van", "Vance",
  6426. "Vanessa", "Vaughn", "Veda", "Velda", "Vella", "Velma", "Velva", "Vena",
  6427. "Verda", "Verdie", "Vergie", "Verla", "Verlie", "Vern", "Verna", "Verner",
  6428. "Vernice", "Vernie", "Vernon", "Verona", "Veronica", "Vesta", "Vicenta",
  6429. "Vicente", "Vickie", "Vicky", "Victor", "Victoria", "Vida", "Vidal", "Vilma",
  6430. "Vince", "Vincent", "Vincenza", "Vincenzo", "Vinnie", "Viola", "Violet",
  6431. "Violette", "Virgie", "Virgil", "Virginia", "Virginie", "Vita", "Vito",
  6432. "Viva", "Vivian", "Viviane", "Vivianne", "Vivien", "Vivienne", "Vladimir",
  6433. "Wade", "Waino", "Waldo", "Walker", "Wallace", "Walter", "Walton", "Wanda",
  6434. "Ward", "Warren", "Watson", "Wava", "Waylon", "Wayne", "Webster", "Weldon",
  6435. "Wellington", "Wendell", "Wendy", "Werner", "Westley", "Weston", "Whitney",
  6436. "Wilber", "Wilbert", "Wilburn", "Wiley", "Wilford", "Wilfred", "Wilfredo",
  6437. "Wilfrid", "Wilhelm", "Wilhelmine", "Will", "Willa", "Willard", "William",
  6438. "Willie", "Willis", "Willow", "Willy", "Wilma", "Wilmer", "Wilson", "Wilton",
  6439. "Winfield", "Winifred", "Winnifred", "Winona", "Winston", "Woodrow", "Wyatt",
  6440. "Wyman", "Xander", "Xavier", "Xzavier", "Yadira", "Yasmeen", "Yasmin",
  6441. "Yasmine", "Yazmin", "Yesenia", "Yessenia", "Yolanda", "Yoshiko", "Yvette",
  6442. "Yvonne", "Zachariah", "Zachary", "Zachery", "Zack", "Zackary", "Zackery",
  6443. "Zakary", "Zander", "Zane", "Zaria", "Zechariah", "Zelda", "Zella", "Zelma",
  6444. "Zena", "Zetta", "Zion", "Zita", "Zoe", "Zoey", "Zoie", "Zoila", "Zola",
  6445. "Zora", "Zula"
  6446. ];
  6447. /**
  6448. * Generate random username.
  6449. * @returns {string} random username
  6450. */
  6451. function generateUsername () {
  6452. var name = RandomUtil.randomElement(names);
  6453. var suffix = RandomUtil.randomAlphanumStr(3);
  6454. return name + '-' + suffix;
  6455. }
  6456. module.exports = {
  6457. generateUsername: generateUsername
  6458. };
  6459. },{"./RandomUtil":26}],28:[function(require,module,exports){
  6460. (function (__filename){
  6461. /* global Strophe, $, $pres, $iq, $msg */
  6462. /* jshint -W101,-W069 */
  6463. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6464. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6465. var Moderator = require("./moderator");
  6466. var EventEmitter = require("events");
  6467. var Recorder = require("./recording");
  6468. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  6469. var parser = {
  6470. packet2JSON: function (packet, nodes) {
  6471. var self = this;
  6472. $(packet).children().each(function (index) {
  6473. var tagName = $(this).prop("tagName");
  6474. var node = {
  6475. tagName: tagName
  6476. };
  6477. node.attributes = {};
  6478. $($(this)[0].attributes).each(function( index, attr ) {
  6479. node.attributes[ attr.name ] = attr.value;
  6480. });
  6481. var text = Strophe.getText($(this)[0]);
  6482. if (text) {
  6483. node.value = text;
  6484. }
  6485. node.children = [];
  6486. nodes.push(node);
  6487. self.packet2JSON($(this), node.children);
  6488. });
  6489. },
  6490. JSON2packet: function (nodes, packet) {
  6491. for(var i = 0; i < nodes.length; i++) {
  6492. var node = nodes[i];
  6493. if(!node || node === null){
  6494. continue;
  6495. }
  6496. packet.c(node.tagName, node.attributes);
  6497. if(node.value)
  6498. packet.t(node.value);
  6499. if(node.children)
  6500. this.JSON2packet(node.children, packet);
  6501. packet.up();
  6502. }
  6503. // packet.up();
  6504. }
  6505. };
  6506. /**
  6507. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  6508. * @param pres the presence JSON
  6509. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  6510. */
  6511. function filterNodeFromPresenceJSON(pres, nodeName){
  6512. var res = [];
  6513. for(var i = 0; i < pres.length; i++)
  6514. if(pres[i].tagName === nodeName)
  6515. res.push(pres[i]);
  6516. return res;
  6517. }
  6518. function ChatRoom(connection, jid, password, XMPP, options, settings) {
  6519. this.eventEmitter = new EventEmitter();
  6520. this.xmpp = XMPP;
  6521. this.connection = connection;
  6522. this.roomjid = Strophe.getBareJidFromJid(jid);
  6523. this.myroomjid = jid;
  6524. this.password = password;
  6525. logger.info("Joined MUC as " + this.myroomjid);
  6526. this.members = {};
  6527. this.presMap = {};
  6528. this.presHandlers = {};
  6529. this.joined = false;
  6530. this.role = 'none';
  6531. this.focusMucJid = null;
  6532. this.bridgeIsDown = false;
  6533. this.options = options || {};
  6534. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter,
  6535. settings);
  6536. this.initPresenceMap();
  6537. this.session = null;
  6538. var self = this;
  6539. this.lastPresences = {};
  6540. this.phoneNumber = null;
  6541. this.phonePin = null;
  6542. }
  6543. ChatRoom.prototype.initPresenceMap = function () {
  6544. this.presMap['to'] = this.myroomjid;
  6545. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  6546. this.presMap["nodes"] = [];
  6547. this.presMap["nodes"].push( {
  6548. "tagName": "user-agent",
  6549. "value": navigator.userAgent,
  6550. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  6551. });
  6552. };
  6553. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  6554. this.presMap["nodes"].push( {
  6555. "tagName": "devices",
  6556. "children": [
  6557. {
  6558. "tagName": "audio",
  6559. "value": devices.audio,
  6560. },
  6561. {
  6562. "tagName": "video",
  6563. "value": devices.video,
  6564. }
  6565. ]
  6566. });
  6567. };
  6568. ChatRoom.prototype.join = function (password) {
  6569. if(password)
  6570. this.password = password;
  6571. var self = this;
  6572. this.moderator.allocateConferenceFocus(function()
  6573. {
  6574. self.sendPresence(true);
  6575. }.bind(this));
  6576. };
  6577. ChatRoom.prototype.sendPresence = function (fromJoin) {
  6578. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  6579. // Too early to send presence - not initialized
  6580. return;
  6581. }
  6582. var pres = $pres({to: this.presMap['to'] });
  6583. pres.c('x', {xmlns: this.presMap['xns']});
  6584. if (this.password) {
  6585. pres.c('password').t(this.password).up();
  6586. }
  6587. pres.up();
  6588. // Send XEP-0115 'c' stanza that contains our capabilities info
  6589. if (this.connection.caps) {
  6590. this.connection.caps.node = this.xmpp.options.clientNode;
  6591. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  6592. }
  6593. parser.JSON2packet(this.presMap.nodes, pres);
  6594. this.connection.send(pres);
  6595. };
  6596. ChatRoom.prototype.doLeave = function () {
  6597. logger.log("do leave", this.myroomjid);
  6598. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  6599. this.presMap.length = 0;
  6600. this.connection.send(pres);
  6601. };
  6602. ChatRoom.prototype.createNonAnonymousRoom = function () {
  6603. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  6604. var getForm = $iq({type: 'get', to: this.roomjid})
  6605. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  6606. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6607. var self = this;
  6608. this.connection.sendIQ(getForm, function (form) {
  6609. if (!$(form).find(
  6610. '>query>x[xmlns="jabber:x:data"]' +
  6611. '>field[var="muc#roomconfig_whois"]').length) {
  6612. logger.error('non-anonymous rooms not supported');
  6613. return;
  6614. }
  6615. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  6616. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6617. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6618. formSubmit.c('field', {'var': 'FORM_TYPE'})
  6619. .c('value')
  6620. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6621. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  6622. .c('value').t('anyone').up().up();
  6623. self.connection.sendIQ(formSubmit);
  6624. }, function (error) {
  6625. logger.error("Error getting room configuration form");
  6626. });
  6627. };
  6628. ChatRoom.prototype.onPresence = function (pres) {
  6629. var from = pres.getAttribute('from');
  6630. // Parse roles.
  6631. var member = {};
  6632. member.show = $(pres).find('>show').text();
  6633. member.status = $(pres).find('>status').text();
  6634. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  6635. member.affiliation = tmp.attr('affiliation');
  6636. member.role = tmp.attr('role');
  6637. // Focus recognition
  6638. member.jid = tmp.attr('jid');
  6639. member.isFocus = false;
  6640. if (member.jid
  6641. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  6642. member.isFocus = true;
  6643. }
  6644. $(pres).find(">x").remove();
  6645. var nodes = [];
  6646. parser.packet2JSON(pres, nodes);
  6647. this.lastPresences[from] = nodes;
  6648. var jibri = null;
  6649. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  6650. // events
  6651. for(var i = 0; i < nodes.length; i++)
  6652. {
  6653. var node = nodes[i];
  6654. switch(node.tagName)
  6655. {
  6656. case "nick":
  6657. member.nick = node.value;
  6658. break;
  6659. case "userId":
  6660. member.id = node.value;
  6661. break;
  6662. }
  6663. }
  6664. if (from == this.myroomjid) {
  6665. if (member.affiliation == 'owner'
  6666. && this.role !== member.role) {
  6667. this.role = member.role;
  6668. this.eventEmitter.emit(
  6669. XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  6670. }
  6671. if (!this.joined) {
  6672. this.joined = true;
  6673. console.log("(TIME) MUC joined:\t", window.performance.now());
  6674. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  6675. }
  6676. } else if (this.members[from] === undefined) {
  6677. // new participant
  6678. this.members[from] = member;
  6679. logger.log('entered', from, member);
  6680. if (member.isFocus) {
  6681. this.focusMucJid = from;
  6682. if(!this.recording) {
  6683. this.recording = new Recorder(this.options.recordingType,
  6684. this.eventEmitter, this.connection, this.focusMucJid,
  6685. this.options.jirecon, this.roomjid);
  6686. if(this.lastJibri)
  6687. this.recording.handleJibriPresence(this.lastJibri);
  6688. }
  6689. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  6690. }
  6691. else {
  6692. this.eventEmitter.emit(
  6693. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  6694. }
  6695. } else {
  6696. // Presence update for existing participant
  6697. // Watch role change:
  6698. if (this.members[from].role != member.role) {
  6699. this.members[from].role = member.role;
  6700. this.eventEmitter.emit(
  6701. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  6702. }
  6703. // store the new display name
  6704. if(member.displayName)
  6705. this.members[from].displayName = member.displayName;
  6706. }
  6707. // after we had fired member or room joined events, lets fire events
  6708. // for the rest info we got in presence
  6709. for(var i = 0; i < nodes.length; i++)
  6710. {
  6711. var node = nodes[i];
  6712. switch(node.tagName)
  6713. {
  6714. case "nick":
  6715. if(!member.isFocus) {
  6716. var displayName = !this.xmpp.options.displayJids
  6717. ? member.nick : Strophe.getResourceFromJid(from);
  6718. if (displayName && displayName.length > 0) {
  6719. this.eventEmitter.emit(
  6720. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  6721. }
  6722. }
  6723. break;
  6724. case "bridgeIsDown":
  6725. if(!this.bridgeIsDown) {
  6726. this.bridgeIsDown = true;
  6727. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  6728. }
  6729. break;
  6730. case "jibri-recording-status":
  6731. var jibri = node;
  6732. break;
  6733. case "call-control":
  6734. var att = node.attributes;
  6735. if(!att)
  6736. break;
  6737. this.phoneNumber = att.phone || null;
  6738. this.phonePin = att.pin || null;
  6739. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  6740. break;
  6741. default :
  6742. this.processNode(node, from);
  6743. }
  6744. }
  6745. if(!member.isFocus)
  6746. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id);
  6747. // Trigger status message update
  6748. if (member.status) {
  6749. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  6750. }
  6751. if(jibri)
  6752. {
  6753. this.lastJibri = jibri;
  6754. if(this.recording)
  6755. this.recording.handleJibriPresence(jibri);
  6756. }
  6757. };
  6758. ChatRoom.prototype.processNode = function (node, from) {
  6759. if(this.presHandlers[node.tagName])
  6760. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  6761. };
  6762. ChatRoom.prototype.sendMessage = function (body, nickname) {
  6763. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6764. msg.c('body', body).up();
  6765. if (nickname) {
  6766. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  6767. }
  6768. this.connection.send(msg);
  6769. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  6770. };
  6771. ChatRoom.prototype.setSubject = function (subject) {
  6772. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6773. msg.c('subject', subject);
  6774. this.connection.send(msg);
  6775. logger.log("topic changed to " + subject);
  6776. };
  6777. ChatRoom.prototype.onParticipantLeft = function (jid) {
  6778. delete this.lastPresences[jid];
  6779. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  6780. this.moderator.onMucMemberLeft(jid);
  6781. };
  6782. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  6783. // room destroyed ?
  6784. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6785. '>destroy').length) {
  6786. var reason;
  6787. var reasonSelect = $(pres).find(
  6788. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6789. '>destroy>reason');
  6790. if (reasonSelect.length) {
  6791. reason = reasonSelect.text();
  6792. }
  6793. this.xmpp.leaveRoom(this.roomjid);
  6794. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  6795. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  6796. return true;
  6797. }
  6798. // Status code 110 indicates that this notification is "self-presence".
  6799. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  6800. delete this.members[from];
  6801. this.onParticipantLeft(from);
  6802. }
  6803. // If the status code is 110 this means we're leaving and we would like
  6804. // to remove everyone else from our view, so we trigger the event.
  6805. else if (Object.keys(this.members).length > 1) {
  6806. for (var i in this.members) {
  6807. var member = this.members[i];
  6808. delete this.members[i];
  6809. this.onParticipantLeft(member);
  6810. }
  6811. }
  6812. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  6813. if (this.myroomjid === from) {
  6814. this.xmpp.leaveRoom(this.roomjid);
  6815. this.eventEmitter.emit(XMPPEvents.KICKED);
  6816. }
  6817. }
  6818. };
  6819. ChatRoom.prototype.onMessage = function (msg, from) {
  6820. var nick =
  6821. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  6822. .text() ||
  6823. Strophe.getResourceFromJid(from);
  6824. var txt = $(msg).find('>body').text();
  6825. var type = msg.getAttribute("type");
  6826. if (type == "error") {
  6827. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  6828. $(msg).find('>text').text(), txt);
  6829. return true;
  6830. }
  6831. var subject = $(msg).find('>subject');
  6832. if (subject.length) {
  6833. var subjectText = subject.text();
  6834. if (subjectText || subjectText === "") {
  6835. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  6836. logger.log("Subject is changed to " + subjectText);
  6837. }
  6838. }
  6839. // xep-0203 delay
  6840. var stamp = $(msg).find('>delay').attr('stamp');
  6841. if (!stamp) {
  6842. // or xep-0091 delay, UTC timestamp
  6843. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  6844. if (stamp) {
  6845. // the format is CCYYMMDDThh:mm:ss
  6846. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  6847. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  6848. }
  6849. }
  6850. if (txt) {
  6851. logger.log('chat', nick, txt);
  6852. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  6853. from, nick, txt, this.myroomjid, stamp);
  6854. }
  6855. };
  6856. ChatRoom.prototype.onPresenceError = function (pres, from) {
  6857. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  6858. logger.log('on password required', from);
  6859. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  6860. } else if ($(pres).find(
  6861. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  6862. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  6863. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  6864. // enter the room by replying with 'not-authorized'. This would
  6865. // result in reconnection from authorized domain.
  6866. // We're either missing Jicofo/Prosody config for anonymous
  6867. // domains or something is wrong.
  6868. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  6869. } else {
  6870. logger.warn('onPresError ', pres);
  6871. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6872. }
  6873. } else {
  6874. logger.warn('onPresError ', pres);
  6875. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6876. }
  6877. };
  6878. ChatRoom.prototype.kick = function (jid) {
  6879. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  6880. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  6881. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  6882. .c('reason').t('You have been kicked.').up().up().up();
  6883. this.connection.sendIQ(
  6884. kickIQ,
  6885. function (result) {
  6886. logger.log('Kick participant with jid: ', jid, result);
  6887. },
  6888. function (error) {
  6889. logger.log('Kick participant error: ', error);
  6890. });
  6891. };
  6892. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  6893. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  6894. var ob = this;
  6895. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  6896. function (res) {
  6897. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  6898. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6899. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6900. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6901. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  6902. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  6903. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  6904. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  6905. ob.connection.sendIQ(formsubmit,
  6906. onSuccess,
  6907. onError);
  6908. } else {
  6909. onNotSupported();
  6910. }
  6911. }, onError);
  6912. };
  6913. ChatRoom.prototype.addToPresence = function (key, values) {
  6914. values.tagName = key;
  6915. this.presMap["nodes"].push(values);
  6916. };
  6917. ChatRoom.prototype.removeFromPresence = function (key) {
  6918. for(var i = 0; i < this.presMap.nodes.length; i++)
  6919. {
  6920. if(key === this.presMap.nodes[i].tagName)
  6921. this.presMap.nodes.splice(i, 1);
  6922. }
  6923. };
  6924. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  6925. this.presHandlers[name] = handler;
  6926. };
  6927. ChatRoom.prototype.removePresenceListener = function (name) {
  6928. delete this.presHandlers[name];
  6929. };
  6930. ChatRoom.prototype.isModerator = function () {
  6931. return this.role === 'moderator';
  6932. };
  6933. ChatRoom.prototype.getMemberRole = function (peerJid) {
  6934. if (this.members[peerJid]) {
  6935. return this.members[peerJid].role;
  6936. }
  6937. return null;
  6938. };
  6939. ChatRoom.prototype.setJingleSession = function(session){
  6940. this.session = session;
  6941. this.session.room = this;
  6942. };
  6943. ChatRoom.prototype.removeStream = function (stream, callback) {
  6944. if(!this.session)
  6945. return;
  6946. this.session.removeStream(stream, callback);
  6947. };
  6948. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  6949. if(this.session) {
  6950. // FIXME: will block switchInProgress on true value in case of exception
  6951. this.session.switchStreams(stream, oldStream, callback, isAudio);
  6952. } else {
  6953. // We are done immediately
  6954. logger.warn("No conference handler or conference not started yet");
  6955. callback();
  6956. }
  6957. };
  6958. ChatRoom.prototype.addStream = function (stream, callback) {
  6959. if(this.session) {
  6960. // FIXME: will block switchInProgress on true value in case of exception
  6961. this.session.addStream(stream, callback);
  6962. } else {
  6963. // We are done immediately
  6964. logger.warn("No conference handler or conference not started yet");
  6965. callback();
  6966. }
  6967. };
  6968. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  6969. var self = this;
  6970. var localCallback = function (mute) {
  6971. self.sendVideoInfoPresence(mute);
  6972. if(callback)
  6973. callback(mute);
  6974. };
  6975. if(this.session)
  6976. {
  6977. this.session.setVideoMute(
  6978. mute, localCallback, options);
  6979. }
  6980. else {
  6981. localCallback(mute);
  6982. }
  6983. };
  6984. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  6985. //This will be for remote streams only
  6986. // if (this.forceMuted && !mute) {
  6987. // logger.info("Asking focus for unmute");
  6988. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  6989. // // FIXME: wait for result before resetting muted status
  6990. // this.forceMuted = false;
  6991. // }
  6992. return this.sendAudioInfoPresence(mute, callback);
  6993. };
  6994. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  6995. this.removeFromPresence("audiomuted");
  6996. this.addToPresence("audiomuted",
  6997. {attributes:
  6998. {"audions": "http://jitsi.org/jitmeet/audio"},
  6999. value: mute.toString()});
  7000. };
  7001. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  7002. this.addAudioInfoToPresence(mute);
  7003. if(this.connection) {
  7004. this.sendPresence();
  7005. }
  7006. if(callback)
  7007. callback();
  7008. };
  7009. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  7010. this.removeFromPresence("videomuted");
  7011. this.addToPresence("videomuted",
  7012. {attributes:
  7013. {"videons": "http://jitsi.org/jitmeet/video"},
  7014. value: mute.toString()});
  7015. };
  7016. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  7017. this.addVideoInfoToPresence(mute);
  7018. if(!this.connection)
  7019. return;
  7020. this.sendPresence();
  7021. };
  7022. ChatRoom.prototype.addListener = function(type, listener) {
  7023. this.eventEmitter.on(type, listener);
  7024. };
  7025. ChatRoom.prototype.removeListener = function (type, listener) {
  7026. this.eventEmitter.removeListener(type, listener);
  7027. };
  7028. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  7029. if(this.lastPresences[data.peerjid])
  7030. {
  7031. var pres = this.lastPresences[data.peerjid];
  7032. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  7033. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  7034. data.videomuted = ((videomuted.length > 0
  7035. && videomuted[0]
  7036. && videomuted[0]["value"] === "true")? true : false);
  7037. data.audiomuted = ((audiomuted.length > 0
  7038. && audiomuted[0]
  7039. && audiomuted[0]["value"] === "true")? true : false);
  7040. }
  7041. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  7042. };
  7043. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  7044. if (!this.session)
  7045. return null;
  7046. return this.session.getSsrcOwner(ssrc);
  7047. };
  7048. /**
  7049. * Returns true if the recording is supproted and false if not.
  7050. */
  7051. ChatRoom.prototype.isRecordingSupported = function () {
  7052. if(this.recording)
  7053. return this.recording.isSupported();
  7054. return false;
  7055. };
  7056. /**
  7057. * Returns null if the recording is not supported, "on" if the recording started
  7058. * and "off" if the recording is not started.
  7059. */
  7060. ChatRoom.prototype.getRecordingState = function () {
  7061. if(this.recording)
  7062. return this.recording.getState();
  7063. return "off";
  7064. }
  7065. /**
  7066. * Returns the url of the recorded video.
  7067. */
  7068. ChatRoom.prototype.getRecordingURL = function () {
  7069. if(this.recording)
  7070. return this.recording.getURL();
  7071. return null;
  7072. }
  7073. /**
  7074. * Starts/stops the recording
  7075. * @param token token for authentication
  7076. * @param statusChangeHandler {function} receives the new status as argument.
  7077. */
  7078. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  7079. if(this.recording)
  7080. return this.recording.toggleRecording(options, statusChangeHandler);
  7081. return statusChangeHandler("error",
  7082. new Error("The conference is not created yet!"));
  7083. }
  7084. /**
  7085. * Returns true if the SIP calls are supported and false otherwise
  7086. */
  7087. ChatRoom.prototype.isSIPCallingSupported = function () {
  7088. if(this.moderator)
  7089. return this.moderator.isSipGatewayEnabled();
  7090. return false;
  7091. }
  7092. /**
  7093. * Dials a number.
  7094. * @param number the number
  7095. */
  7096. ChatRoom.prototype.dial = function (number) {
  7097. return this.connection.rayo.dial(number, "fromnumber",
  7098. Strophe.getNodeFromJid(this.myroomjid), this.password,
  7099. this.focusMucJid);
  7100. }
  7101. /**
  7102. * Hangup an existing call
  7103. */
  7104. ChatRoom.prototype.hangup = function () {
  7105. return this.connection.rayo.hangup();
  7106. }
  7107. /**
  7108. * Returns the phone number for joining the conference.
  7109. */
  7110. ChatRoom.prototype.getPhoneNumber = function () {
  7111. return this.phoneNumber;
  7112. }
  7113. /**
  7114. * Returns the pin for joining the conference with phone.
  7115. */
  7116. ChatRoom.prototype.getPhonePin = function () {
  7117. return this.phonePin;
  7118. }
  7119. /**
  7120. * Returns the connection state for the current session.
  7121. */
  7122. ChatRoom.prototype.getConnectionState = function () {
  7123. if(!this.session)
  7124. return null;
  7125. return this.session.getIceConnectionState();
  7126. }
  7127. /**
  7128. * Mutes remote participant.
  7129. * @param jid of the participant
  7130. * @param mute
  7131. */
  7132. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  7133. logger.info("set mute", mute);
  7134. var iqToFocus = $iq(
  7135. {to: this.focusMucJid, type: 'set'})
  7136. .c('mute', {
  7137. xmlns: 'http://jitsi.org/jitmeet/audio',
  7138. jid: jid
  7139. })
  7140. .t(mute.toString())
  7141. .up();
  7142. this.connection.sendIQ(
  7143. iqToFocus,
  7144. function (result) {
  7145. logger.log('set mute', result);
  7146. },
  7147. function (error) {
  7148. logger.log('set mute error', error);
  7149. });
  7150. }
  7151. ChatRoom.prototype.onMute = function (iq) {
  7152. var from = iq.getAttribute('from');
  7153. if (from !== this.focusMucJid) {
  7154. logger.warn("Ignored mute from non focus peer");
  7155. return false;
  7156. }
  7157. var mute = $(iq).find('mute');
  7158. if (mute.length) {
  7159. var doMuteAudio = mute.text() === "true";
  7160. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  7161. }
  7162. return true;
  7163. }
  7164. module.exports = ChatRoom;
  7165. }).call(this,"/modules/xmpp/ChatRoom.js")
  7166. },{"../../service/xmpp/XMPPEvents":138,"./moderator":35,"./recording":36,"events":45,"jitsi-meet-logger":49}],29:[function(require,module,exports){
  7167. (function (__filename){
  7168. /*
  7169. * JingleSession provides an API to manage a single Jingle session. We will
  7170. * have different implementations depending on the underlying interface used
  7171. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  7172. */
  7173. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7174. function JingleSession(me, sid, connection, service, eventEmitter) {
  7175. /**
  7176. * Our JID.
  7177. */
  7178. this.me = me;
  7179. /**
  7180. * The Jingle session identifier.
  7181. */
  7182. this.sid = sid;
  7183. /**
  7184. * The XMPP connection.
  7185. */
  7186. this.connection = connection;
  7187. /**
  7188. * The XMPP service.
  7189. */
  7190. this.service = service;
  7191. /**
  7192. * The event emitter.
  7193. */
  7194. this.eventEmitter = eventEmitter;
  7195. /**
  7196. * Whether to use dripping or not. Dripping is sending trickle candidates
  7197. * not one-by-one.
  7198. * Note: currently we do not support 'false'.
  7199. */
  7200. this.usedrip = true;
  7201. /**
  7202. * When dripping is used, stores ICE candidates which are to be sent.
  7203. */
  7204. this.drip_container = [];
  7205. // Media constraints. Is this WebRTC only?
  7206. this.media_constraints = null;
  7207. // ICE servers config (RTCConfiguration?).
  7208. this.ice_config = {};
  7209. // The chat room instance associated with the session.
  7210. this.room = null;
  7211. }
  7212. /**
  7213. * Prepares this object to initiate a session.
  7214. * @param peerjid the JID of the remote peer.
  7215. * @param isInitiator whether we will be the Jingle initiator.
  7216. * @param media_constraints
  7217. * @param ice_config
  7218. */
  7219. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  7220. media_constraints, ice_config) {
  7221. this.media_constraints = media_constraints;
  7222. this.ice_config = ice_config;
  7223. if (this.state !== null) {
  7224. logger.error('attempt to initiate on session ' + this.sid +
  7225. 'in state ' + this.state);
  7226. return;
  7227. }
  7228. this.state = 'pending';
  7229. this.initiator = isInitiator ? this.me : peerjid;
  7230. this.responder = !isInitiator ? this.me : peerjid;
  7231. this.peerjid = peerjid;
  7232. this.doInitialize();
  7233. };
  7234. /**
  7235. * Finishes initialization.
  7236. */
  7237. JingleSession.prototype.doInitialize = function() {};
  7238. /**
  7239. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  7240. * Note: currently only used on transport-info
  7241. */
  7242. JingleSession.prototype.addIceCandidates = function(contents) {};
  7243. /**
  7244. * Handles an 'add-source' event.
  7245. *
  7246. * @param contents an array of Jingle 'content' elements.
  7247. */
  7248. JingleSession.prototype.addSources = function(contents) {};
  7249. /**
  7250. * Handles a 'remove-source' event.
  7251. *
  7252. * @param contents an array of Jingle 'content' elements.
  7253. */
  7254. JingleSession.prototype.removeSources = function(contents) {};
  7255. /**
  7256. * Terminates this Jingle session (stops sending media and closes the streams?)
  7257. */
  7258. JingleSession.prototype.terminate = function() {};
  7259. /**
  7260. * Sends a Jingle session-terminate message to the peer and terminates the
  7261. * session.
  7262. * @param reason
  7263. * @param text
  7264. */
  7265. JingleSession.prototype.sendTerminate = function(reason, text) {};
  7266. /**
  7267. * Handles an offer from the remote peer (prepares to accept a session).
  7268. * @param jingle the 'jingle' XML element.
  7269. */
  7270. JingleSession.prototype.setOffer = function(jingle) {};
  7271. /**
  7272. * Handles an answer from the remote peer (prepares to accept a session).
  7273. * @param jingle the 'jingle' XML element.
  7274. */
  7275. JingleSession.prototype.setAnswer = function(jingle) {};
  7276. module.exports = JingleSession;
  7277. }).call(this,"/modules/xmpp/JingleSession.js")
  7278. },{"jitsi-meet-logger":49}],30:[function(require,module,exports){
  7279. (function (__filename){
  7280. /* jshint -W117 */
  7281. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7282. var JingleSession = require("./JingleSession");
  7283. var TraceablePeerConnection = require("./TraceablePeerConnection");
  7284. var SDPDiffer = require("./SDPDiffer");
  7285. var SDPUtil = require("./SDPUtil");
  7286. var SDP = require("./SDP");
  7287. var async = require("async");
  7288. var transform = require("sdp-transform");
  7289. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7290. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7291. var RTC = require("../RTC/RTC");
  7292. // Jingle stuff
  7293. function JingleSessionPC(me, sid, connection, service) {
  7294. JingleSession.call(this, me, sid, connection, service);
  7295. this.initiator = null;
  7296. this.responder = null;
  7297. this.peerjid = null;
  7298. this.state = null;
  7299. this.localSDP = null;
  7300. this.remoteSDP = null;
  7301. this.relayedStreams = [];
  7302. this.usetrickle = true;
  7303. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  7304. this.hadstuncandidate = false;
  7305. this.hadturncandidate = false;
  7306. this.lasticecandidate = false;
  7307. this.statsinterval = null;
  7308. this.reason = null;
  7309. this.addssrc = [];
  7310. this.removessrc = [];
  7311. this.pendingop = null;
  7312. this.switchstreams = false;
  7313. this.addingStreams = false;
  7314. this.wait = true;
  7315. /**
  7316. * A map that stores SSRCs of local streams
  7317. * @type {{}} maps media type('audio' or 'video') to SSRC number
  7318. */
  7319. this.localStreamsSSRC = {};
  7320. this.ssrcOwners = {};
  7321. this.ssrcVideoTypes = {};
  7322. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  7323. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  7324. /**
  7325. * The indicator which determines whether the (local) video has been muted
  7326. * in response to a user command in contrast to an automatic decision made
  7327. * by the application logic.
  7328. */
  7329. this.videoMuteByUser = false;
  7330. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  7331. // We start with the queue paused. We resume it when the signaling state is
  7332. // stable and the ice connection state is connected.
  7333. this.modifySourcesQueue.pause();
  7334. }
  7335. //XXX this is badly broken...
  7336. JingleSessionPC.prototype = JingleSession.prototype;
  7337. JingleSessionPC.prototype.constructor = JingleSessionPC;
  7338. JingleSessionPC.prototype.setOffer = function(offer) {
  7339. this.setRemoteDescription(offer, 'offer');
  7340. };
  7341. JingleSessionPC.prototype.setAnswer = function(answer) {
  7342. this.setRemoteDescription(answer, 'answer');
  7343. };
  7344. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  7345. var signalingState = this.peerconnection.signalingState;
  7346. var iceConnectionState = this.peerconnection.iceConnectionState;
  7347. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  7348. this.modifySourcesQueue.resume();
  7349. } else {
  7350. this.modifySourcesQueue.pause();
  7351. }
  7352. };
  7353. JingleSessionPC.prototype.doInitialize = function () {
  7354. var self = this;
  7355. this.hadstuncandidate = false;
  7356. this.hadturncandidate = false;
  7357. this.lasticecandidate = false;
  7358. // True if reconnect is in progress
  7359. this.isreconnect = false;
  7360. // Set to true if the connection was ever stable
  7361. this.wasstable = false;
  7362. this.peerconnection = new TraceablePeerConnection(
  7363. this.connection.jingle.ice_config,
  7364. RTC.getPCConstraints(),
  7365. this);
  7366. this.peerconnection.onicecandidate = function (event) {
  7367. var protocol;
  7368. if (event && event.candidate) {
  7369. protocol = (typeof event.candidate.protocol === 'string')
  7370. ? event.candidate.protocol.toLowerCase() : '';
  7371. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7372. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7373. return;
  7374. }
  7375. }
  7376. self.sendIceCandidate(event.candidate);
  7377. };
  7378. this.peerconnection.onaddstream = function (event) {
  7379. if (event.stream.id !== 'default') {
  7380. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  7381. self.remoteStreamAdded(event);
  7382. } else {
  7383. // This is a recvonly stream. Clients that implement Unified Plan,
  7384. // such as Firefox use recvonly "streams/channels/tracks" for
  7385. // receiving remote stream/tracks, as opposed to Plan B where there
  7386. // are only 3 channels: audio, video and data.
  7387. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  7388. }
  7389. };
  7390. this.peerconnection.onremovestream = function (event) {
  7391. // Remove the stream from remoteStreams
  7392. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  7393. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  7394. };
  7395. this.peerconnection.onsignalingstatechange = function (event) {
  7396. if (!(self && self.peerconnection)) return;
  7397. if (self.peerconnection.signalingState === 'stable') {
  7398. self.wasstable = true;
  7399. }
  7400. self.updateModifySourcesQueue();
  7401. };
  7402. /**
  7403. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  7404. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  7405. * RTCPeerConnection.iceConnectionState changes.
  7406. *
  7407. * @param event the event containing information about the change
  7408. */
  7409. this.peerconnection.oniceconnectionstatechange = function (event) {
  7410. if (!(self && self.peerconnection)) return;
  7411. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  7412. ":\t", window.performance.now());
  7413. self.updateModifySourcesQueue();
  7414. switch (self.peerconnection.iceConnectionState) {
  7415. case 'connected':
  7416. // Informs interested parties that the connection has been restored.
  7417. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  7418. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  7419. self.isreconnect = false;
  7420. break;
  7421. case 'disconnected':
  7422. self.isreconnect = true;
  7423. // Informs interested parties that the connection has been interrupted.
  7424. if (self.wasstable)
  7425. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  7426. break;
  7427. case 'failed':
  7428. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7429. break;
  7430. }
  7431. onIceConnectionStateChange(self.sid, self);
  7432. };
  7433. this.peerconnection.onnegotiationneeded = function (event) {
  7434. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  7435. };
  7436. this.relayedStreams.forEach(function(stream) {
  7437. self.peerconnection.addStream(stream);
  7438. });
  7439. };
  7440. function onIceConnectionStateChange(sid, session) {
  7441. switch (session.peerconnection.iceConnectionState) {
  7442. case 'checking':
  7443. session.timeChecking = (new Date()).getTime();
  7444. session.firstconnect = true;
  7445. break;
  7446. case 'completed': // on caller side
  7447. case 'connected':
  7448. if (session.firstconnect) {
  7449. session.firstconnect = false;
  7450. var metadata = {};
  7451. metadata.setupTime
  7452. = (new Date()).getTime() - session.timeChecking;
  7453. session.peerconnection.getStats(function (res) {
  7454. if(res && res.result) {
  7455. res.result().forEach(function (report) {
  7456. if (report.type == 'googCandidatePair' &&
  7457. report.stat('googActiveConnection') == 'true') {
  7458. metadata.localCandidateType
  7459. = report.stat('googLocalCandidateType');
  7460. metadata.remoteCandidateType
  7461. = report.stat('googRemoteCandidateType');
  7462. // log pair as well so we can get nice pie
  7463. // charts
  7464. metadata.candidatePair
  7465. = report.stat('googLocalCandidateType') +
  7466. ';' +
  7467. report.stat('googRemoteCandidateType');
  7468. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  7469. {
  7470. metadata.ipv6 = true;
  7471. }
  7472. }
  7473. });
  7474. }
  7475. });
  7476. }
  7477. break;
  7478. }
  7479. }
  7480. JingleSessionPC.prototype.accept = function () {
  7481. this.state = 'active';
  7482. var pranswer = this.peerconnection.localDescription;
  7483. if (!pranswer || pranswer.type != 'pranswer') {
  7484. return;
  7485. }
  7486. logger.log('going from pranswer to answer');
  7487. if (this.usetrickle) {
  7488. // remove candidates already sent from session-accept
  7489. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  7490. for (var i = 0; i < lines.length; i++) {
  7491. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  7492. }
  7493. }
  7494. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  7495. // FIXME: change any inactive to sendrecv or whatever they were originally
  7496. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  7497. }
  7498. var prsdp = new SDP(pranswer.sdp);
  7499. if (this.webrtcIceTcpDisable) {
  7500. prsdp.removeTcpCandidates = true;
  7501. }
  7502. if (this.webrtcIceUdpDisable) {
  7503. prsdp.removeUdpCandidates = true;
  7504. }
  7505. var accept = $iq({to: this.peerjid,
  7506. type: 'set'})
  7507. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7508. action: 'session-accept',
  7509. initiator: this.initiator,
  7510. responder: this.responder,
  7511. sid: this.sid });
  7512. // FIXME why do we generate session-accept in 3 different places ?
  7513. prsdp.toJingle(
  7514. accept,
  7515. this.initiator == this.me ? 'initiator' : 'responder');
  7516. var sdp = this.peerconnection.localDescription.sdp;
  7517. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  7518. // FIXME: change any inactive to sendrecv or whatever they were originally
  7519. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  7520. }
  7521. var self = this;
  7522. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  7523. function () {
  7524. //logger.log('setLocalDescription success');
  7525. self.setLocalDescription();
  7526. self.connection.sendIQ(accept,
  7527. function () {
  7528. var ack = {};
  7529. ack.source = 'answer';
  7530. $(document).trigger('ack.jingle', [self.sid, ack]);
  7531. },
  7532. function (stanza) {
  7533. var error = ($(stanza).find('error').length) ? {
  7534. code: $(stanza).find('error').attr('code'),
  7535. reason: $(stanza).find('error :first')[0].tagName
  7536. }:{};
  7537. error.source = 'answer';
  7538. JingleSessionPC.onJingleError(self.sid, error);
  7539. },
  7540. 10000);
  7541. },
  7542. function (e) {
  7543. logger.error('setLocalDescription failed', e);
  7544. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7545. }
  7546. );
  7547. };
  7548. JingleSessionPC.prototype.terminate = function (reason) {
  7549. this.state = 'ended';
  7550. this.reason = reason;
  7551. this.peerconnection.close();
  7552. if (this.statsinterval !== null) {
  7553. window.clearInterval(this.statsinterval);
  7554. this.statsinterval = null;
  7555. }
  7556. };
  7557. JingleSessionPC.prototype.active = function () {
  7558. return this.state == 'active';
  7559. };
  7560. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  7561. var self = this;
  7562. if (candidate && !this.lasticecandidate) {
  7563. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  7564. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  7565. if (!(ice && jcand)) {
  7566. logger.error('failed to get ice && jcand');
  7567. return;
  7568. }
  7569. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7570. if (jcand.type === 'srflx') {
  7571. this.hadstuncandidate = true;
  7572. } else if (jcand.type === 'relay') {
  7573. this.hadturncandidate = true;
  7574. }
  7575. if (this.usetrickle) {
  7576. if (this.usedrip) {
  7577. if (this.drip_container.length === 0) {
  7578. // start 20ms callout
  7579. window.setTimeout(function () {
  7580. if (self.drip_container.length === 0) return;
  7581. self.sendIceCandidates(self.drip_container);
  7582. self.drip_container = [];
  7583. }, 20);
  7584. }
  7585. this.drip_container.push(candidate);
  7586. return;
  7587. } else {
  7588. self.sendIceCandidate([candidate]);
  7589. }
  7590. }
  7591. } else {
  7592. //logger.log('sendIceCandidate: last candidate.');
  7593. if (!this.usetrickle) {
  7594. //logger.log('should send full offer now...');
  7595. //FIXME why do we generate session-accept in 3 different places ?
  7596. var init = $iq({to: this.peerjid,
  7597. type: 'set'})
  7598. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7599. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  7600. initiator: this.initiator,
  7601. sid: this.sid});
  7602. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  7603. if (self.webrtcIceTcpDisable) {
  7604. this.localSDP.removeTcpCandidates = true;
  7605. }
  7606. if (self.webrtcIceUdpDisable) {
  7607. this.localSDP.removeUdpCandidates = true;
  7608. }
  7609. var sendJingle = function (ssrc) {
  7610. if(!ssrc)
  7611. ssrc = {};
  7612. self.localSDP.toJingle(
  7613. init,
  7614. self.initiator == self.me ? 'initiator' : 'responder',
  7615. ssrc);
  7616. self.connection.sendIQ(init,
  7617. function () {
  7618. //logger.log('session initiate ack');
  7619. var ack = {};
  7620. ack.source = 'offer';
  7621. $(document).trigger('ack.jingle', [self.sid, ack]);
  7622. },
  7623. function (stanza) {
  7624. self.state = 'error';
  7625. self.peerconnection.close();
  7626. var error = ($(stanza).find('error').length) ? {
  7627. code: $(stanza).find('error').attr('code'),
  7628. reason: $(stanza).find('error :first')[0].tagName,
  7629. }:{};
  7630. error.source = 'offer';
  7631. JingleSessionPC.onJingleError(self.sid, error);
  7632. },
  7633. 10000);
  7634. };
  7635. sendJingle();
  7636. }
  7637. this.lasticecandidate = true;
  7638. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  7639. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  7640. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  7641. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  7642. }
  7643. }
  7644. };
  7645. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  7646. logger.log('sendIceCandidates', candidates);
  7647. var cand = $iq({to: this.peerjid, type: 'set'})
  7648. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7649. action: 'transport-info',
  7650. initiator: this.initiator,
  7651. sid: this.sid});
  7652. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  7653. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  7654. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  7655. if (cands.length > 0) {
  7656. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  7657. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7658. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  7659. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  7660. }).c('transport', ice);
  7661. for (var i = 0; i < cands.length; i++) {
  7662. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  7663. }
  7664. // add fingerprint
  7665. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  7666. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  7667. tmp.required = true;
  7668. cand.c(
  7669. 'fingerprint',
  7670. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  7671. .t(tmp.fingerprint);
  7672. delete tmp.fingerprint;
  7673. cand.attrs(tmp);
  7674. cand.up();
  7675. }
  7676. cand.up(); // transport
  7677. cand.up(); // content
  7678. }
  7679. }
  7680. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  7681. //logger.log('was this the last candidate', this.lasticecandidate);
  7682. this.connection.sendIQ(cand,
  7683. function () {
  7684. var ack = {};
  7685. ack.source = 'transportinfo';
  7686. $(document).trigger('ack.jingle', [this.sid, ack]);
  7687. },
  7688. function (stanza) {
  7689. var error = ($(stanza).find('error').length) ? {
  7690. code: $(stanza).find('error').attr('code'),
  7691. reason: $(stanza).find('error :first')[0].tagName,
  7692. }:{};
  7693. error.source = 'transportinfo';
  7694. JingleSessionPC.onJingleError(this.sid, error);
  7695. },
  7696. 10000);
  7697. };
  7698. JingleSessionPC.prototype.sendOffer = function () {
  7699. //logger.log('sendOffer...');
  7700. var self = this;
  7701. this.peerconnection.createOffer(function (sdp) {
  7702. self.createdOffer(sdp);
  7703. },
  7704. function (e) {
  7705. logger.error('createOffer failed', e);
  7706. },
  7707. this.media_constraints
  7708. );
  7709. };
  7710. // FIXME createdOffer is never used in jitsi-meet
  7711. JingleSessionPC.prototype.createdOffer = function (sdp) {
  7712. //logger.log('createdOffer', sdp);
  7713. var self = this;
  7714. this.localSDP = new SDP(sdp.sdp);
  7715. //this.localSDP.mangle();
  7716. var sendJingle = function () {
  7717. var init = $iq({to: this.peerjid,
  7718. type: 'set'})
  7719. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7720. action: 'session-initiate',
  7721. initiator: this.initiator,
  7722. sid: this.sid});
  7723. self.localSDP.toJingle(
  7724. init,
  7725. this.initiator == this.me ? 'initiator' : 'responder');
  7726. self.connection.sendIQ(init,
  7727. function () {
  7728. var ack = {};
  7729. ack.source = 'offer';
  7730. $(document).trigger('ack.jingle', [self.sid, ack]);
  7731. },
  7732. function (stanza) {
  7733. self.state = 'error';
  7734. self.peerconnection.close();
  7735. var error = ($(stanza).find('error').length) ? {
  7736. code: $(stanza).find('error').attr('code'),
  7737. reason: $(stanza).find('error :first')[0].tagName,
  7738. }:{};
  7739. error.source = 'offer';
  7740. JingleSessionPC.onJingleError(self.sid, error);
  7741. },
  7742. 10000);
  7743. }
  7744. sdp.sdp = this.localSDP.raw;
  7745. this.peerconnection.setLocalDescription(sdp,
  7746. function () {
  7747. if(self.usetrickle)
  7748. {
  7749. sendJingle();
  7750. }
  7751. self.setLocalDescription();
  7752. //logger.log('setLocalDescription success');
  7753. },
  7754. function (e) {
  7755. logger.error('setLocalDescription failed', e);
  7756. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7757. }
  7758. );
  7759. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  7760. for (var i = 0; i < cands.length; i++) {
  7761. var cand = SDPUtil.parse_icecandidate(cands[i]);
  7762. if (cand.type == 'srflx') {
  7763. this.hadstuncandidate = true;
  7764. } else if (cand.type == 'relay') {
  7765. this.hadturncandidate = true;
  7766. }
  7767. }
  7768. };
  7769. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  7770. var self = this;
  7771. $(contents).each(function (idx, content) {
  7772. var name = $(content).attr('name');
  7773. var mediaType = this.getAttribute('name');
  7774. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7775. ssrcs.each(function () {
  7776. var ssrc = this.getAttribute('ssrc');
  7777. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  7778. function () {
  7779. var owner = this.getAttribute('owner');
  7780. self.ssrcOwners[ssrc] = owner;
  7781. }
  7782. );
  7783. });
  7784. });
  7785. };
  7786. /**
  7787. * Returns the SSRC of local audio stream.
  7788. * @param mediaType 'audio' or 'video' media type
  7789. * @returns {*} the SSRC number of local audio or video stream.
  7790. */
  7791. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  7792. return this.localStreamsSSRC[mediaType];
  7793. };
  7794. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  7795. return this.ssrcOwners[ssrc];
  7796. };
  7797. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  7798. //logger.log('setting remote description... ', desctype);
  7799. this.remoteSDP = new SDP('');
  7800. if (this.webrtcIceTcpDisable) {
  7801. this.remoteSDP.removeTcpCandidates = true;
  7802. }
  7803. if (this.webrtcIceUdpDisable) {
  7804. this.remoteSDP.removeUdpCandidates = true;
  7805. }
  7806. this.remoteSDP.fromJingle(elem);
  7807. this.readSsrcInfo($(elem).find(">content"));
  7808. if (this.peerconnection.remoteDescription) {
  7809. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  7810. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  7811. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  7812. for (var i = 0; i < pranswer.media.length; i++) {
  7813. // make sure we have ice ufrag and pwd
  7814. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  7815. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  7816. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  7817. } else {
  7818. logger.warn('no ice ufrag?');
  7819. }
  7820. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  7821. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  7822. } else {
  7823. logger.warn('no ice pwd?');
  7824. }
  7825. }
  7826. // copy over candidates
  7827. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  7828. for (var j = 0; j < lines.length; j++) {
  7829. this.remoteSDP.media[i] += lines[j] + '\r\n';
  7830. }
  7831. }
  7832. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  7833. }
  7834. }
  7835. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  7836. this.peerconnection.setRemoteDescription(remotedesc,
  7837. function () {
  7838. //logger.log('setRemoteDescription success');
  7839. },
  7840. function (e) {
  7841. logger.error('setRemoteDescription error', e);
  7842. JingleSessionPC.onJingleFatalError(self, e);
  7843. }
  7844. );
  7845. };
  7846. /**
  7847. * Adds remote ICE candidates to this Jingle session.
  7848. * @param elem An array of Jingle "content" elements?
  7849. */
  7850. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  7851. var self = this;
  7852. if (this.peerconnection.signalingState == 'closed') {
  7853. return;
  7854. }
  7855. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  7856. logger.log('trickle ice candidate arriving before session accept...');
  7857. // create a PRANSWER for setRemoteDescription
  7858. if (!this.remoteSDP) {
  7859. var cobbled = 'v=0\r\n' +
  7860. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  7861. 's=-\r\n' +
  7862. 't=0 0\r\n';
  7863. // first, take some things from the local description
  7864. for (var i = 0; i < this.localSDP.media.length; i++) {
  7865. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  7866. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  7867. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  7868. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  7869. }
  7870. cobbled += 'a=inactive\r\n';
  7871. }
  7872. this.remoteSDP = new SDP(cobbled);
  7873. }
  7874. // then add things like ice and dtls from remote candidate
  7875. elem.each(function () {
  7876. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  7877. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7878. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7879. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  7880. var tmp = $(this).find('transport');
  7881. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  7882. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  7883. tmp = $(this).find('transport>fingerprint');
  7884. if (tmp.length) {
  7885. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  7886. } else {
  7887. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  7888. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  7889. }
  7890. break;
  7891. }
  7892. }
  7893. }
  7894. });
  7895. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  7896. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  7897. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  7898. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  7899. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  7900. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  7901. }).length == this.remoteSDP.media.length;
  7902. if (iscomplete) {
  7903. logger.log('setting pranswer');
  7904. try {
  7905. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  7906. function() {
  7907. },
  7908. function(e) {
  7909. logger.log('setRemoteDescription pranswer failed', e.toString());
  7910. });
  7911. } catch (e) {
  7912. logger.error('setting pranswer failed', e);
  7913. }
  7914. } else {
  7915. //logger.log('not yet setting pranswer');
  7916. }
  7917. }
  7918. // operate on each content element
  7919. elem.each(function () {
  7920. // would love to deactivate this, but firefox still requires it
  7921. var idx = -1;
  7922. var i;
  7923. for (i = 0; i < self.remoteSDP.media.length; i++) {
  7924. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7925. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7926. idx = i;
  7927. break;
  7928. }
  7929. }
  7930. if (idx == -1) { // fall back to localdescription
  7931. for (i = 0; i < self.localSDP.media.length; i++) {
  7932. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7933. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7934. idx = i;
  7935. break;
  7936. }
  7937. }
  7938. }
  7939. var name = $(this).attr('name');
  7940. // TODO: check ice-pwd and ice-ufrag?
  7941. $(this).find('transport>candidate').each(function () {
  7942. var line, candidate;
  7943. var protocol = this.getAttribute('protocol');
  7944. protocol =
  7945. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  7946. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7947. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7948. return;
  7949. }
  7950. line = SDPUtil.candidateFromJingle(this);
  7951. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  7952. sdpMid: name,
  7953. candidate: line});
  7954. try {
  7955. self.peerconnection.addIceCandidate(candidate);
  7956. } catch (e) {
  7957. logger.error('addIceCandidate failed', e.toString(), line);
  7958. self.room.eventEmitter.emit(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  7959. err, self.peerconnection);
  7960. }
  7961. });
  7962. });
  7963. };
  7964. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  7965. //logger.log('createAnswer', provisional);
  7966. var self = this;
  7967. this.peerconnection.createAnswer(
  7968. function (sdp) {
  7969. self.createdAnswer(sdp, provisional);
  7970. },
  7971. function (e) {
  7972. logger.error('createAnswer failed', e);
  7973. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7974. },
  7975. this.media_constraints
  7976. );
  7977. };
  7978. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  7979. //logger.log('createAnswer callback');
  7980. var self = this;
  7981. this.localSDP = new SDP(sdp.sdp);
  7982. //this.localSDP.mangle();
  7983. this.usepranswer = provisional === true;
  7984. if (this.usetrickle) {
  7985. if (this.usepranswer) {
  7986. sdp.type = 'pranswer';
  7987. for (var i = 0; i < this.localSDP.media.length; i++) {
  7988. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  7989. }
  7990. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  7991. }
  7992. }
  7993. var self = this;
  7994. var sendJingle = function (ssrcs) {
  7995. // FIXME why do we generate session-accept in 3 different places ?
  7996. var accept = $iq({to: self.peerjid,
  7997. type: 'set'})
  7998. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7999. action: 'session-accept',
  8000. initiator: self.initiator,
  8001. responder: self.responder,
  8002. sid: self.sid });
  8003. if (self.webrtcIceTcpDisable) {
  8004. self.localSDP.removeTcpCandidates = true;
  8005. }
  8006. if (self.webrtcIceUdpDisable) {
  8007. self.localSDP.removeUdpCandidates = true;
  8008. }
  8009. self.localSDP.toJingle(
  8010. accept,
  8011. self.initiator == self.me ? 'initiator' : 'responder',
  8012. ssrcs);
  8013. self.connection.sendIQ(accept,
  8014. function () {
  8015. var ack = {};
  8016. ack.source = 'answer';
  8017. $(document).trigger('ack.jingle', [self.sid, ack]);
  8018. },
  8019. function (stanza) {
  8020. var error = ($(stanza).find('error').length) ? {
  8021. code: $(stanza).find('error').attr('code'),
  8022. reason: $(stanza).find('error :first')[0].tagName,
  8023. }:{};
  8024. error.source = 'answer';
  8025. JingleSessionPC.onJingleError(self.sid, error);
  8026. },
  8027. 10000);
  8028. }
  8029. sdp.sdp = this.localSDP.raw;
  8030. this.peerconnection.setLocalDescription(sdp,
  8031. function () {
  8032. //logger.log('setLocalDescription success');
  8033. if (self.usetrickle && !self.usepranswer) {
  8034. sendJingle();
  8035. }
  8036. self.setLocalDescription();
  8037. },
  8038. function (e) {
  8039. logger.error('setLocalDescription failed', e);
  8040. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8041. }
  8042. );
  8043. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  8044. for (var j = 0; j < cands.length; j++) {
  8045. var cand = SDPUtil.parse_icecandidate(cands[j]);
  8046. if (cand.type == 'srflx') {
  8047. this.hadstuncandidate = true;
  8048. } else if (cand.type == 'relay') {
  8049. this.hadturncandidate = true;
  8050. }
  8051. }
  8052. };
  8053. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  8054. var self = this,
  8055. term = $iq({to: this.peerjid,
  8056. type: 'set'})
  8057. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8058. action: 'session-terminate',
  8059. initiator: this.initiator,
  8060. sid: this.sid})
  8061. .c('reason')
  8062. .c(reason || 'success');
  8063. if (text) {
  8064. term.up().c('text').t(text);
  8065. }
  8066. this.connection.sendIQ(term,
  8067. function () {
  8068. self.peerconnection.close();
  8069. self.peerconnection = null;
  8070. self.terminate();
  8071. var ack = {};
  8072. ack.source = 'terminate';
  8073. $(document).trigger('ack.jingle', [self.sid, ack]);
  8074. },
  8075. function (stanza) {
  8076. var error = ($(stanza).find('error').length) ? {
  8077. code: $(stanza).find('error').attr('code'),
  8078. reason: $(stanza).find('error :first')[0].tagName,
  8079. }:{};
  8080. $(document).trigger('ack.jingle', [self.sid, error]);
  8081. },
  8082. 10000);
  8083. if (this.statsinterval !== null) {
  8084. window.clearInterval(this.statsinterval);
  8085. this.statsinterval = null;
  8086. }
  8087. };
  8088. /**
  8089. * Handles a Jingle source-add message for this Jingle session.
  8090. * @param elem An array of Jingle "content" elements.
  8091. */
  8092. JingleSessionPC.prototype.addSource = function (elem) {
  8093. var self = this;
  8094. // FIXME: dirty waiting
  8095. if (!this.peerconnection.localDescription)
  8096. {
  8097. logger.warn("addSource - localDescription not ready yet")
  8098. setTimeout(function()
  8099. {
  8100. self.addSource(elem);
  8101. },
  8102. 200
  8103. );
  8104. return;
  8105. }
  8106. logger.log('addssrc', new Date().getTime());
  8107. logger.log('ice', this.peerconnection.iceConnectionState);
  8108. this.readSsrcInfo(elem);
  8109. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8110. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8111. $(elem).each(function (idx, content) {
  8112. var name = $(content).attr('name');
  8113. var lines = '';
  8114. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8115. var semantics = this.getAttribute('semantics');
  8116. var ssrcs = $(this).find('>source').map(function () {
  8117. return this.getAttribute('ssrc');
  8118. }).get();
  8119. if (ssrcs.length) {
  8120. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8121. }
  8122. });
  8123. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8124. tmp.each(function () {
  8125. var ssrc = $(this).attr('ssrc');
  8126. if(mySdp.containsSSRC(ssrc)){
  8127. /**
  8128. * This happens when multiple participants change their streams at the same time and
  8129. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  8130. * addssrc are scheduled for update IQ. See
  8131. */
  8132. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  8133. return;
  8134. }
  8135. if (sdp.containsSSRC(ssrc)) {
  8136. logger.warn("Source-add request for existing SSRC: " + ssrc);
  8137. return;
  8138. }
  8139. $(this).find('>parameter').each(function () {
  8140. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8141. if ($(this).attr('value') && $(this).attr('value').length)
  8142. lines += ':' + $(this).attr('value');
  8143. lines += '\r\n';
  8144. });
  8145. });
  8146. sdp.media.forEach(function(media, idx) {
  8147. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8148. return;
  8149. sdp.media[idx] += lines;
  8150. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  8151. self.addssrc[idx] += lines;
  8152. });
  8153. sdp.raw = sdp.session + sdp.media.join('');
  8154. });
  8155. this.modifySourcesQueue.push(function() {
  8156. // When a source is added and if this is FF, a new channel is allocated
  8157. // for receiving the added source. We need to diffuse the SSRC of this
  8158. // new recvonly channel to the rest of the peers.
  8159. logger.log('modify sources done');
  8160. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8161. logger.log("SDPs", mySdp, newSdp);
  8162. self.notifyMySSRCUpdate(mySdp, newSdp);
  8163. });
  8164. };
  8165. /**
  8166. * Handles a Jingle source-remove message for this Jingle session.
  8167. * @param elem An array of Jingle "content" elements.
  8168. */
  8169. JingleSessionPC.prototype.removeSource = function (elem) {
  8170. var self = this;
  8171. // FIXME: dirty waiting
  8172. if (!this.peerconnection.localDescription) {
  8173. logger.warn("removeSource - localDescription not ready yet");
  8174. setTimeout(function() {
  8175. self.removeSource(elem);
  8176. },
  8177. 200
  8178. );
  8179. return;
  8180. }
  8181. logger.log('removessrc', new Date().getTime());
  8182. logger.log('ice', this.peerconnection.iceConnectionState);
  8183. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8184. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8185. $(elem).each(function (idx, content) {
  8186. var name = $(content).attr('name');
  8187. var lines = '';
  8188. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8189. var semantics = this.getAttribute('semantics');
  8190. var ssrcs = $(this).find('>source').map(function () {
  8191. return this.getAttribute('ssrc');
  8192. }).get();
  8193. if (ssrcs.length) {
  8194. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8195. }
  8196. });
  8197. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8198. tmp.each(function () {
  8199. var ssrc = $(this).attr('ssrc');
  8200. // This should never happen, but can be useful for bug detection
  8201. if(mySdp.containsSSRC(ssrc)){
  8202. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  8203. return;
  8204. }
  8205. $(this).find('>parameter').each(function () {
  8206. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8207. if ($(this).attr('value') && $(this).attr('value').length)
  8208. lines += ':' + $(this).attr('value');
  8209. lines += '\r\n';
  8210. });
  8211. });
  8212. sdp.media.forEach(function(media, idx) {
  8213. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8214. return;
  8215. sdp.media[idx] += lines;
  8216. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  8217. self.removessrc[idx] += lines;
  8218. });
  8219. sdp.raw = sdp.session + sdp.media.join('');
  8220. });
  8221. this.modifySourcesQueue.push(function() {
  8222. // When a source is removed and if this is FF, the recvonly channel that
  8223. // receives the remote stream is deactivated . We need to diffuse the
  8224. // recvonly SSRC removal to the rest of the peers.
  8225. logger.log('modify sources done');
  8226. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8227. logger.log("SDPs", mySdp, newSdp);
  8228. self.notifyMySSRCUpdate(mySdp, newSdp);
  8229. });
  8230. };
  8231. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  8232. var self = this;
  8233. if (this.peerconnection.signalingState == 'closed') return;
  8234. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  8235. || this.switchstreams || this.addingStreams)){
  8236. // There is nothing to do since scheduled job might have been executed by another succeeding call
  8237. this.setLocalDescription();
  8238. if(successCallback){
  8239. successCallback();
  8240. }
  8241. queueCallback();
  8242. return;
  8243. }
  8244. // Reset switch streams flags
  8245. this.switchstreams = false;
  8246. this.addingStreams = false;
  8247. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8248. // add sources
  8249. this.addssrc.forEach(function(lines, idx) {
  8250. sdp.media[idx] += lines;
  8251. });
  8252. this.addssrc = [];
  8253. // remove sources
  8254. this.removessrc.forEach(function(lines, idx) {
  8255. lines = lines.split('\r\n');
  8256. lines.pop(); // remove empty last element;
  8257. lines.forEach(function(line) {
  8258. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  8259. });
  8260. });
  8261. this.removessrc = [];
  8262. sdp.raw = sdp.session + sdp.media.join('');
  8263. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  8264. function() {
  8265. if(self.signalingState == 'closed') {
  8266. logger.error("createAnswer attempt on closed state");
  8267. queueCallback("createAnswer attempt on closed state");
  8268. return;
  8269. }
  8270. self.peerconnection.createAnswer(
  8271. function(modifiedAnswer) {
  8272. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  8273. if (self.pendingop !== null) {
  8274. var sdp = new SDP(modifiedAnswer.sdp);
  8275. if (sdp.media.length > 1) {
  8276. switch(self.pendingop) {
  8277. case 'mute':
  8278. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  8279. break;
  8280. case 'unmute':
  8281. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  8282. break;
  8283. }
  8284. sdp.raw = sdp.session + sdp.media.join('');
  8285. modifiedAnswer.sdp = sdp.raw;
  8286. }
  8287. self.pendingop = null;
  8288. }
  8289. // FIXME: pushing down an answer while ice connection state
  8290. // is still checking is bad...
  8291. //logger.log(self.peerconnection.iceConnectionState);
  8292. // trying to work around another chrome bug
  8293. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  8294. self.peerconnection.setLocalDescription(modifiedAnswer,
  8295. function() {
  8296. //logger.log('modified setLocalDescription ok');
  8297. self.setLocalDescription();
  8298. if(successCallback){
  8299. successCallback();
  8300. }
  8301. queueCallback();
  8302. },
  8303. function(error) {
  8304. logger.error('modified setLocalDescription failed', error);
  8305. queueCallback(error);
  8306. }
  8307. );
  8308. },
  8309. function(error) {
  8310. logger.error('modified answer failed', error);
  8311. queueCallback(error);
  8312. }
  8313. );
  8314. },
  8315. function(error) {
  8316. logger.error('modify failed', error);
  8317. queueCallback(error);
  8318. }
  8319. );
  8320. };
  8321. /**
  8322. * Switches video streams.
  8323. * @param newStream new stream that will be used as video of this session.
  8324. * @param oldStream old video stream of this session.
  8325. * @param successCallback callback executed after successful stream switch.
  8326. * @param isAudio whether the streams are audio (if true) or video (if false).
  8327. */
  8328. JingleSessionPC.prototype.switchStreams =
  8329. function (newStream, oldStream, successCallback, isAudio) {
  8330. var self = this;
  8331. var sender, newTrack;
  8332. var senderKind = isAudio ? 'audio' : 'video';
  8333. // Remember SDP to figure out added/removed SSRCs
  8334. var oldSdp = null;
  8335. if (self.peerconnection) {
  8336. if (self.peerconnection.localDescription) {
  8337. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8338. }
  8339. if (RTCBrowserType.getBrowserType() ===
  8340. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8341. // On Firefox we don't replace MediaStreams as this messes up the
  8342. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8343. // of complications. Instead, we use the RTPSender and replace just
  8344. // the track.
  8345. // Find the right sender (for audio or video)
  8346. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8347. if (s.track && s.track.kind === senderKind) {
  8348. sender = s;
  8349. return true;
  8350. }
  8351. });
  8352. if (sender) {
  8353. // We assume that our streams have a single track, either audio
  8354. // or video.
  8355. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  8356. newStream.getVideoTracks()[0];
  8357. sender.replaceTrack(newTrack)
  8358. .then(function() {
  8359. console.log("Replaced a track, isAudio=" + isAudio);
  8360. })
  8361. .catch(function(err) {
  8362. console.log("Failed to replace a track: " + err);
  8363. });
  8364. } else {
  8365. console.log("Cannot switch tracks: no RTPSender.");
  8366. }
  8367. } else {
  8368. self.peerconnection.removeStream(oldStream, true);
  8369. if (newStream) {
  8370. self.peerconnection.addStream(newStream);
  8371. }
  8372. }
  8373. }
  8374. // Conference is not active
  8375. if (!oldSdp) {
  8376. successCallback();
  8377. return;
  8378. }
  8379. self.switchstreams = true;
  8380. self.modifySourcesQueue.push(function() {
  8381. logger.log('modify sources done');
  8382. successCallback();
  8383. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8384. logger.log("SDPs", oldSdp, newSdp);
  8385. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8386. });
  8387. };
  8388. /**
  8389. * Adds streams.
  8390. * @param stream new stream that will be added.
  8391. * @param success_callback callback executed after successful stream addition.
  8392. */
  8393. JingleSessionPC.prototype.addStream = function (stream, callback) {
  8394. var self = this;
  8395. // Remember SDP to figure out added/removed SSRCs
  8396. var oldSdp = null;
  8397. if(this.peerconnection) {
  8398. if(this.peerconnection.localDescription) {
  8399. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8400. }
  8401. if(stream)
  8402. this.peerconnection.addStream(stream);
  8403. }
  8404. // Conference is not active
  8405. if(!oldSdp || !this.peerconnection) {
  8406. callback();
  8407. return;
  8408. }
  8409. this.addingStreams = true;
  8410. this.modifySourcesQueue.push(function() {
  8411. logger.log('modify sources done');
  8412. callback();
  8413. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8414. logger.log("SDPs", oldSdp, newSdp);
  8415. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8416. });
  8417. }
  8418. /**
  8419. * Remove streams.
  8420. * @param stream stream that will be removed.
  8421. * @param success_callback callback executed after successful stream addition.
  8422. */
  8423. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  8424. var self = this;
  8425. // Remember SDP to figure out added/removed SSRCs
  8426. var oldSdp = null;
  8427. if(this.peerconnection) {
  8428. if(this.peerconnection.localDescription) {
  8429. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8430. }
  8431. if (RTCBrowserType.getBrowserType() ===
  8432. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8433. var sender = null;
  8434. // On Firefox we don't replace MediaStreams as this messes up the
  8435. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8436. // of complications. Instead, we use the RTPSender and replace just
  8437. // the track.
  8438. var track = null;
  8439. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  8440. track = stream.getAudioTracks()[0];
  8441. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  8442. {
  8443. track = stream.getVideoTracks()[0];
  8444. }
  8445. if(!track) {
  8446. console.log("Cannot switch tracks: no tracks.");
  8447. return;
  8448. }
  8449. // Find the right sender (for audio or video)
  8450. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8451. if (s.track === track) {
  8452. sender = s;
  8453. return true;
  8454. }
  8455. });
  8456. if (sender) {
  8457. self.peerconnection.peerconnection.removeTrack(sender);
  8458. // .then(function() {
  8459. // console.log("Replaced a track, isAudio=" + isAudio);
  8460. // })
  8461. // .catch(function(err) {
  8462. // console.log("Failed to replace a track: " + err);
  8463. // });
  8464. } else {
  8465. console.log("Cannot switch tracks: no RTPSender.");
  8466. }
  8467. } else if(stream)
  8468. this.peerconnection.removeStream(stream);
  8469. }
  8470. // Conference is not active
  8471. if(!oldSdp || !this.peerconnection) {
  8472. callback();
  8473. return;
  8474. }
  8475. this.addingStreams = true;
  8476. this.modifySourcesQueue.push(function() {
  8477. logger.log('modify sources done');
  8478. callback();
  8479. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8480. logger.log("SDPs", oldSdp, newSdp);
  8481. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8482. });
  8483. }
  8484. /**
  8485. * Figures out added/removed ssrcs and send update IQs.
  8486. * @param old_sdp SDP object for old description.
  8487. * @param new_sdp SDP object for new description.
  8488. */
  8489. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  8490. if (!(this.peerconnection.signalingState == 'stable' &&
  8491. this.peerconnection.iceConnectionState == 'connected')){
  8492. logger.log("Too early to send updates");
  8493. return;
  8494. }
  8495. // send source-remove IQ.
  8496. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  8497. var remove = $iq({to: this.peerjid, type: 'set'})
  8498. .c('jingle', {
  8499. xmlns: 'urn:xmpp:jingle:1',
  8500. action: 'source-remove',
  8501. initiator: this.initiator,
  8502. sid: this.sid
  8503. }
  8504. );
  8505. var removed = sdpDiffer.toJingle(remove);
  8506. if (removed && remove) {
  8507. logger.info("Sending source-remove", remove);
  8508. this.connection.sendIQ(remove,
  8509. function (res) {
  8510. logger.info('got remove result', res);
  8511. },
  8512. function (err) {
  8513. logger.error('got remove error', err);
  8514. }
  8515. );
  8516. } else {
  8517. logger.log('removal not necessary');
  8518. }
  8519. // send source-add IQ.
  8520. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  8521. var add = $iq({to: this.peerjid, type: 'set'})
  8522. .c('jingle', {
  8523. xmlns: 'urn:xmpp:jingle:1',
  8524. action: 'source-add',
  8525. initiator: this.initiator,
  8526. sid: this.sid
  8527. }
  8528. );
  8529. var added = sdpDiffer.toJingle(add);
  8530. if (added && add) {
  8531. logger.info("Sending source-add", add);
  8532. this.connection.sendIQ(add,
  8533. function (res) {
  8534. logger.info('got add result', res);
  8535. },
  8536. function (err) {
  8537. logger.error('got add error', err);
  8538. }
  8539. );
  8540. } else {
  8541. logger.log('addition not necessary');
  8542. }
  8543. };
  8544. /**
  8545. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  8546. *
  8547. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  8548. * tracks; otherwise, <tt>false</tt>
  8549. * @param callback a function to be invoked with <tt>mute</tt> after all video
  8550. * tracks have been enabled/disabled. The function may, optionally, return
  8551. * another function which is to be invoked after the whole mute/unmute operation
  8552. * has completed successfully.
  8553. * @param options an object which specifies optional arguments such as the
  8554. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  8555. * specifies whether the method was initiated in response to a user command (in
  8556. * contrast to an automatic decision made by the application logic)
  8557. */
  8558. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  8559. var byUser;
  8560. if (options) {
  8561. byUser = options.byUser;
  8562. if (typeof byUser === 'undefined') {
  8563. byUser = true;
  8564. }
  8565. } else {
  8566. byUser = true;
  8567. }
  8568. // The user's command to mute the (local) video takes precedence over any
  8569. // automatic decision made by the application logic.
  8570. if (byUser) {
  8571. this.videoMuteByUser = mute;
  8572. } else if (this.videoMuteByUser) {
  8573. return;
  8574. }
  8575. this.hardMuteVideo(mute);
  8576. var self = this;
  8577. var oldSdp = null;
  8578. if(self.peerconnection) {
  8579. if(self.peerconnection.localDescription) {
  8580. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8581. }
  8582. }
  8583. this.modifySourcesQueue.push(function() {
  8584. logger.log('modify sources done');
  8585. callback(mute);
  8586. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8587. logger.log("SDPs", oldSdp, newSdp);
  8588. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8589. });
  8590. };
  8591. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  8592. this.pendingop = muted ? 'mute' : 'unmute';
  8593. };
  8594. JingleSessionPC.prototype.sendMute = function (muted, content) {
  8595. var info = $iq({to: this.peerjid,
  8596. type: 'set'})
  8597. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8598. action: 'session-info',
  8599. initiator: this.initiator,
  8600. sid: this.sid });
  8601. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8602. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  8603. if (content) {
  8604. info.attrs({'name': content});
  8605. }
  8606. this.connection.send(info);
  8607. };
  8608. JingleSessionPC.prototype.sendRinging = function () {
  8609. var info = $iq({to: this.peerjid,
  8610. type: 'set'})
  8611. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8612. action: 'session-info',
  8613. initiator: this.initiator,
  8614. sid: this.sid });
  8615. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8616. this.connection.send(info);
  8617. };
  8618. JingleSessionPC.prototype.getStats = function (interval) {
  8619. var self = this;
  8620. var recv = {audio: 0, video: 0};
  8621. var lost = {audio: 0, video: 0};
  8622. var lastrecv = {audio: 0, video: 0};
  8623. var lastlost = {audio: 0, video: 0};
  8624. var loss = {audio: 0, video: 0};
  8625. var delta = {audio: 0, video: 0};
  8626. this.statsinterval = window.setInterval(function () {
  8627. if (self && self.peerconnection && self.peerconnection.getStats) {
  8628. self.peerconnection.getStats(function (stats) {
  8629. var results = stats.result();
  8630. // TODO: there are so much statistics you can get from this..
  8631. for (var i = 0; i < results.length; ++i) {
  8632. if (results[i].type == 'ssrc') {
  8633. var packetsrecv = results[i].stat('packetsReceived');
  8634. var packetslost = results[i].stat('packetsLost');
  8635. if (packetsrecv && packetslost) {
  8636. packetsrecv = parseInt(packetsrecv, 10);
  8637. packetslost = parseInt(packetslost, 10);
  8638. if (results[i].stat('googFrameRateReceived')) {
  8639. lastlost.video = lost.video;
  8640. lastrecv.video = recv.video;
  8641. recv.video = packetsrecv;
  8642. lost.video = packetslost;
  8643. } else {
  8644. lastlost.audio = lost.audio;
  8645. lastrecv.audio = recv.audio;
  8646. recv.audio = packetsrecv;
  8647. lost.audio = packetslost;
  8648. }
  8649. }
  8650. }
  8651. }
  8652. delta.audio = recv.audio - lastrecv.audio;
  8653. delta.video = recv.video - lastrecv.video;
  8654. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  8655. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  8656. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  8657. });
  8658. }
  8659. }, interval || 3000);
  8660. return this.statsinterval;
  8661. };
  8662. JingleSessionPC.onJingleError = function (session, error)
  8663. {
  8664. logger.error("Jingle error", error);
  8665. }
  8666. JingleSessionPC.onJingleFatalError = function (session, error)
  8667. {
  8668. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8669. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  8670. }
  8671. JingleSessionPC.prototype.setLocalDescription = function () {
  8672. var self = this;
  8673. var newssrcs = [];
  8674. if(!this.peerconnection.localDescription)
  8675. return;
  8676. var session = transform.parse(this.peerconnection.localDescription.sdp);
  8677. var i;
  8678. session.media.forEach(function (media) {
  8679. if (media.ssrcs && media.ssrcs.length > 0) {
  8680. // TODO(gp) maybe exclude FID streams?
  8681. media.ssrcs.forEach(function (ssrc) {
  8682. if (ssrc.attribute !== 'cname') {
  8683. return;
  8684. }
  8685. newssrcs.push({
  8686. 'ssrc': ssrc.id,
  8687. 'type': media.type
  8688. });
  8689. // FIXME allows for only one SSRC per media type
  8690. self.localStreamsSSRC[media.type] = ssrc.id;
  8691. });
  8692. }
  8693. });
  8694. logger.log('new ssrcs', newssrcs);
  8695. // Bind us as local SSRCs owner
  8696. if (newssrcs.length > 0) {
  8697. for (i = 0; i < newssrcs.length; i++) {
  8698. var ssrc = newssrcs[i].ssrc;
  8699. var myJid = self.me;
  8700. self.ssrcOwners[ssrc] = myJid;
  8701. }
  8702. }
  8703. }
  8704. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8705. JingleSessionPC.prototype.sendKeyframe = function () {
  8706. var pc = this.peerconnection;
  8707. logger.log('sendkeyframe', pc.iceConnectionState);
  8708. if (pc.iceConnectionState !== 'connected') return; // safe...
  8709. var self = this;
  8710. pc.setRemoteDescription(
  8711. pc.remoteDescription,
  8712. function () {
  8713. pc.createAnswer(
  8714. function (modifiedAnswer) {
  8715. pc.setLocalDescription(
  8716. modifiedAnswer,
  8717. function () {
  8718. // noop
  8719. },
  8720. function (error) {
  8721. logger.log('triggerKeyframe setLocalDescription failed', error);
  8722. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  8723. }
  8724. );
  8725. },
  8726. function (error) {
  8727. logger.log('triggerKeyframe createAnswer failed', error);
  8728. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  8729. }
  8730. );
  8731. },
  8732. function (error) {
  8733. logger.log('triggerKeyframe setRemoteDescription failed', error);
  8734. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  8735. }
  8736. );
  8737. }
  8738. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  8739. var self = this;
  8740. var thessrc;
  8741. var streamId = RTC.getStreamID(data.stream);
  8742. // look up an associated JID for a stream id
  8743. if (!streamId) {
  8744. logger.error("No stream ID for", data.stream);
  8745. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  8746. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  8747. var ssrclines = this.peerconnection.remoteDescription?
  8748. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  8749. ssrclines = ssrclines.filter(function (line) {
  8750. // NOTE(gp) previously we filtered on the mslabel, but that property
  8751. // is not always present.
  8752. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  8753. if (RTCBrowserType.isTemasysPluginUsed()) {
  8754. return ((line.indexOf('mslabel:' + streamId) !== -1));
  8755. } else {
  8756. return ((line.indexOf('msid:' + streamId) !== -1));
  8757. }
  8758. });
  8759. if (ssrclines.length) {
  8760. thessrc = ssrclines[0].substring(7).split(' ')[0];
  8761. if (!self.ssrcOwners[thessrc]) {
  8762. logger.error("No SSRC owner known for: " + thessrc);
  8763. return;
  8764. }
  8765. data.peerjid = self.ssrcOwners[thessrc];
  8766. logger.log('associated jid', self.ssrcOwners[thessrc]);
  8767. } else {
  8768. logger.error("No SSRC lines for ", streamId);
  8769. }
  8770. }
  8771. this.room.remoteStreamAdded(data, this.sid, thessrc);
  8772. var isVideo = data.stream.getVideoTracks().length > 0;
  8773. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8774. if (isVideo &&
  8775. data.peerjid && this.peerjid === data.peerjid &&
  8776. data.stream.getVideoTracks().length === 0 &&
  8777. RTC.localVideo.getTracks().length > 0) {
  8778. window.setTimeout(function () {
  8779. self.sendKeyframe();
  8780. }, 3000);
  8781. }
  8782. }
  8783. /**
  8784. * Returns the ice connection state for the peer connection.
  8785. * @returns the ice connection state for the peer connection.
  8786. */
  8787. JingleSessionPC.prototype.getIceConnectionState = function () {
  8788. return this.peerconnection.iceConnectionState;
  8789. }
  8790. module.exports = JingleSessionPC;
  8791. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  8792. },{"../../service/xmpp/XMPPEvents":138,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":29,"./SDP":31,"./SDPDiffer":32,"./SDPUtil":33,"./TraceablePeerConnection":34,"async":44,"jitsi-meet-logger":49,"sdp-transform":78}],31:[function(require,module,exports){
  8793. (function (__filename){
  8794. /* jshint -W117 */
  8795. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8796. var SDPUtil = require("./SDPUtil");
  8797. // SDP STUFF
  8798. function SDP(sdp) {
  8799. /**
  8800. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  8801. * @type {boolean}
  8802. */
  8803. this.removeTcpCandidates = false;
  8804. /**
  8805. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  8806. * @type {boolean}
  8807. */
  8808. this.removeUdpCandidates = false;
  8809. this.media = sdp.split('\r\nm=');
  8810. for (var i = 1; i < this.media.length; i++) {
  8811. this.media[i] = 'm=' + this.media[i];
  8812. if (i != this.media.length - 1) {
  8813. this.media[i] += '\r\n';
  8814. }
  8815. }
  8816. this.session = this.media.shift() + '\r\n';
  8817. this.raw = this.session + this.media.join('');
  8818. }
  8819. /**
  8820. * Returns map of MediaChannel mapped per channel idx.
  8821. */
  8822. SDP.prototype.getMediaSsrcMap = function() {
  8823. var self = this;
  8824. var media_ssrcs = {};
  8825. var tmp;
  8826. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  8827. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  8828. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  8829. var media = {
  8830. mediaindex: mediaindex,
  8831. mid: mid,
  8832. ssrcs: {},
  8833. ssrcGroups: []
  8834. };
  8835. media_ssrcs[mediaindex] = media;
  8836. tmp.forEach(function (line) {
  8837. var linessrc = line.substring(7).split(' ')[0];
  8838. // allocate new ChannelSsrc
  8839. if(!media.ssrcs[linessrc]) {
  8840. media.ssrcs[linessrc] = {
  8841. ssrc: linessrc,
  8842. lines: []
  8843. };
  8844. }
  8845. media.ssrcs[linessrc].lines.push(line);
  8846. });
  8847. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  8848. tmp.forEach(function(line){
  8849. var idx = line.indexOf(' ');
  8850. var semantics = line.substr(0, idx).substr(13);
  8851. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8852. if (ssrcs.length) {
  8853. media.ssrcGroups.push({
  8854. semantics: semantics,
  8855. ssrcs: ssrcs
  8856. });
  8857. }
  8858. });
  8859. }
  8860. return media_ssrcs;
  8861. };
  8862. /**
  8863. * Returns <tt>true</tt> if this SDP contains given SSRC.
  8864. * @param ssrc the ssrc to check.
  8865. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  8866. */
  8867. SDP.prototype.containsSSRC = function (ssrc) {
  8868. // FIXME this code is really strange - improve it if you can
  8869. var medias = this.getMediaSsrcMap();
  8870. var result = false;
  8871. Object.keys(medias).forEach(function (mediaindex) {
  8872. if (result)
  8873. return;
  8874. if (medias[mediaindex].ssrcs[ssrc]) {
  8875. result = true;
  8876. }
  8877. });
  8878. return result;
  8879. };
  8880. // remove iSAC and CN from SDP
  8881. SDP.prototype.mangle = function () {
  8882. var i, j, mline, lines, rtpmap, newdesc;
  8883. for (i = 0; i < this.media.length; i++) {
  8884. lines = this.media[i].split('\r\n');
  8885. lines.pop(); // remove empty last element
  8886. mline = SDPUtil.parse_mline(lines.shift());
  8887. if (mline.media != 'audio')
  8888. continue;
  8889. newdesc = '';
  8890. mline.fmt.length = 0;
  8891. for (j = 0; j < lines.length; j++) {
  8892. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  8893. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  8894. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  8895. continue;
  8896. mline.fmt.push(rtpmap.id);
  8897. newdesc += lines[j] + '\r\n';
  8898. } else {
  8899. newdesc += lines[j] + '\r\n';
  8900. }
  8901. }
  8902. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  8903. this.media[i] += newdesc;
  8904. }
  8905. this.raw = this.session + this.media.join('');
  8906. };
  8907. // remove lines matching prefix from session section
  8908. SDP.prototype.removeSessionLines = function(prefix) {
  8909. var self = this;
  8910. var lines = SDPUtil.find_lines(this.session, prefix);
  8911. lines.forEach(function(line) {
  8912. self.session = self.session.replace(line + '\r\n', '');
  8913. });
  8914. this.raw = this.session + this.media.join('');
  8915. return lines;
  8916. }
  8917. // remove lines matching prefix from a media section specified by mediaindex
  8918. // TODO: non-numeric mediaindex could match mid
  8919. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  8920. var self = this;
  8921. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  8922. lines.forEach(function(line) {
  8923. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  8924. });
  8925. this.raw = this.session + this.media.join('');
  8926. return lines;
  8927. }
  8928. // add content's to a jingle element
  8929. SDP.prototype.toJingle = function (elem, thecreator) {
  8930. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  8931. var self = this;
  8932. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  8933. // new bundle plan
  8934. if (SDPUtil.find_line(this.session, 'a=group:')) {
  8935. lines = SDPUtil.find_lines(this.session, 'a=group:');
  8936. for (i = 0; i < lines.length; i++) {
  8937. tmp = lines[i].split(' ');
  8938. var semantics = tmp.shift().substr(8);
  8939. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  8940. for (j = 0; j < tmp.length; j++) {
  8941. elem.c('content', {name: tmp[j]}).up();
  8942. }
  8943. elem.up();
  8944. }
  8945. }
  8946. for (i = 0; i < this.media.length; i++) {
  8947. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  8948. if (!(mline.media === 'audio' ||
  8949. mline.media === 'video' ||
  8950. mline.media === 'application'))
  8951. {
  8952. continue;
  8953. }
  8954. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  8955. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  8956. } else {
  8957. ssrc = false;
  8958. }
  8959. elem.c('content', {creator: thecreator, name: mline.media});
  8960. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  8961. // prefer identifier from a=mid if present
  8962. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  8963. elem.attrs({ name: mid });
  8964. }
  8965. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  8966. elem.c('description',
  8967. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  8968. media: mline.media });
  8969. if (ssrc) {
  8970. elem.attrs({ssrc: ssrc});
  8971. }
  8972. for (j = 0; j < mline.fmt.length; j++) {
  8973. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  8974. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  8975. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  8976. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  8977. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  8978. for (k = 0; k < tmp.length; k++) {
  8979. elem.c('parameter', tmp[k]).up();
  8980. }
  8981. }
  8982. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  8983. elem.up();
  8984. }
  8985. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  8986. elem.c('encryption', {required: 1});
  8987. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  8988. crypto.forEach(function(line) {
  8989. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  8990. });
  8991. elem.up(); // end of encryption
  8992. }
  8993. if (ssrc) {
  8994. // new style mapping
  8995. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  8996. // FIXME: group by ssrc and support multiple different ssrcs
  8997. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  8998. if(ssrclines.length > 0) {
  8999. ssrclines.forEach(function (line) {
  9000. var idx = line.indexOf(' ');
  9001. var linessrc = line.substr(0, idx).substr(7);
  9002. if (linessrc != ssrc) {
  9003. elem.up();
  9004. ssrc = linessrc;
  9005. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9006. }
  9007. var kv = line.substr(idx + 1);
  9008. elem.c('parameter');
  9009. if (kv.indexOf(':') == -1) {
  9010. elem.attrs({ name: kv });
  9011. } else {
  9012. var k = kv.split(':', 2)[0];
  9013. elem.attrs({ name: k });
  9014. var v = kv.split(':', 2)[1];
  9015. v = SDPUtil.filter_special_chars(v);
  9016. elem.attrs({ value: v });
  9017. }
  9018. elem.up();
  9019. });
  9020. } else {
  9021. elem.up();
  9022. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9023. elem.c('parameter');
  9024. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  9025. elem.up();
  9026. var msid = null;
  9027. if(mline.media == "audio")
  9028. {
  9029. msid = APP.RTC.localAudio._getId();
  9030. }
  9031. else
  9032. {
  9033. msid = APP.RTC.localVideo._getId();
  9034. }
  9035. if(msid != null)
  9036. {
  9037. msid = SDPUtil.filter_special_chars(msid);
  9038. elem.c('parameter');
  9039. elem.attrs({name: "msid", value:msid});
  9040. elem.up();
  9041. elem.c('parameter');
  9042. elem.attrs({name: "mslabel", value:msid});
  9043. elem.up();
  9044. elem.c('parameter');
  9045. elem.attrs({name: "label", value:msid});
  9046. elem.up();
  9047. }
  9048. }
  9049. elem.up();
  9050. // XEP-0339 handle ssrc-group attributes
  9051. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  9052. ssrc_group_lines.forEach(function(line) {
  9053. var idx = line.indexOf(' ');
  9054. var semantics = line.substr(0, idx).substr(13);
  9055. var ssrcs = line.substr(14 + semantics.length).split(' ');
  9056. if (ssrcs.length) {
  9057. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9058. ssrcs.forEach(function(ssrc) {
  9059. elem.c('source', { ssrc: ssrc })
  9060. .up();
  9061. });
  9062. elem.up();
  9063. }
  9064. });
  9065. }
  9066. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  9067. elem.c('rtcp-mux').up();
  9068. }
  9069. // XEP-0293 -- map a=rtcp-fb:*
  9070. this.rtcpFbToJingle(i, elem, '*');
  9071. // XEP-0294
  9072. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  9073. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  9074. for (j = 0; j < lines.length; j++) {
  9075. tmp = SDPUtil.parse_extmap(lines[j]);
  9076. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  9077. uri: tmp.uri,
  9078. id: tmp.value });
  9079. if (tmp.hasOwnProperty('direction')) {
  9080. switch (tmp.direction) {
  9081. case 'sendonly':
  9082. elem.attrs({senders: 'responder'});
  9083. break;
  9084. case 'recvonly':
  9085. elem.attrs({senders: 'initiator'});
  9086. break;
  9087. case 'sendrecv':
  9088. elem.attrs({senders: 'both'});
  9089. break;
  9090. case 'inactive':
  9091. elem.attrs({senders: 'none'});
  9092. break;
  9093. }
  9094. }
  9095. // TODO: handle params
  9096. elem.up();
  9097. }
  9098. }
  9099. elem.up(); // end of description
  9100. }
  9101. // map ice-ufrag/pwd, dtls fingerprint, candidates
  9102. this.transportToJingle(i, elem);
  9103. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  9104. elem.attrs({senders: 'both'});
  9105. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  9106. elem.attrs({senders: 'initiator'});
  9107. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  9108. elem.attrs({senders: 'responder'});
  9109. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  9110. elem.attrs({senders: 'none'});
  9111. }
  9112. if (mline.port == '0') {
  9113. // estos hack to reject an m-line
  9114. elem.attrs({senders: 'rejected'});
  9115. }
  9116. elem.up(); // end of content
  9117. }
  9118. elem.up();
  9119. return elem;
  9120. };
  9121. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  9122. var tmp, sctpmap, sctpAttrs, fingerprints;
  9123. var self = this;
  9124. elem.c('transport');
  9125. // XEP-0343 DTLS/SCTP
  9126. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  9127. {
  9128. sctpmap = SDPUtil.find_line(
  9129. this.media[mediaindex], 'a=sctpmap:', self.session);
  9130. if (sctpmap)
  9131. {
  9132. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  9133. elem.c('sctpmap',
  9134. {
  9135. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  9136. number: sctpAttrs[0], /* SCTP port */
  9137. protocol: sctpAttrs[1] /* protocol */
  9138. });
  9139. // Optional stream count attribute
  9140. if (sctpAttrs.length > 2)
  9141. elem.attrs({ streams: sctpAttrs[2]});
  9142. elem.up();
  9143. }
  9144. }
  9145. // XEP-0320
  9146. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  9147. fingerprints.forEach(function(line) {
  9148. tmp = SDPUtil.parse_fingerprint(line);
  9149. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  9150. elem.c('fingerprint').t(tmp.fingerprint);
  9151. delete tmp.fingerprint;
  9152. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  9153. if (line) {
  9154. tmp.setup = line.substr(8);
  9155. }
  9156. elem.attrs(tmp);
  9157. elem.up(); // end of fingerprint
  9158. });
  9159. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  9160. if (tmp) {
  9161. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  9162. elem.attrs(tmp);
  9163. // XEP-0176
  9164. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  9165. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  9166. lines.forEach(function (line) {
  9167. var candidate = SDPUtil.candidateToJingle(line);
  9168. var protocol = (candidate &&
  9169. typeof candidate.protocol === 'string')
  9170. ? candidate.protocol.toLowerCase() : '';
  9171. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9172. (self.removeUdpCandidates && protocol === 'udp')) {
  9173. return;
  9174. }
  9175. elem.c('candidate', candidate).up();
  9176. });
  9177. }
  9178. }
  9179. elem.up(); // end of transport
  9180. }
  9181. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  9182. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  9183. lines.forEach(function (line) {
  9184. var tmp = SDPUtil.parse_rtcpfb(line);
  9185. if (tmp.type == 'trr-int') {
  9186. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  9187. elem.up();
  9188. } else {
  9189. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  9190. if (tmp.params.length > 0) {
  9191. elem.attrs({'subtype': tmp.params[0]});
  9192. }
  9193. elem.up();
  9194. }
  9195. });
  9196. };
  9197. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  9198. var media = '';
  9199. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9200. if (tmp.length) {
  9201. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  9202. if (tmp.attr('value')) {
  9203. media += tmp.attr('value');
  9204. } else {
  9205. media += '0';
  9206. }
  9207. media += '\r\n';
  9208. }
  9209. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9210. tmp.each(function () {
  9211. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  9212. if ($(this).attr('subtype')) {
  9213. media += ' ' + $(this).attr('subtype');
  9214. }
  9215. media += '\r\n';
  9216. });
  9217. return media;
  9218. };
  9219. // construct an SDP from a jingle stanza
  9220. SDP.prototype.fromJingle = function (jingle) {
  9221. var self = this;
  9222. this.raw = 'v=0\r\n' +
  9223. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  9224. 's=-\r\n' +
  9225. 't=0 0\r\n';
  9226. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  9227. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  9228. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  9229. var contents = $(group).find('>content').map(function (idx, content) {
  9230. return content.getAttribute('name');
  9231. }).get();
  9232. if (contents.length > 0) {
  9233. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  9234. }
  9235. });
  9236. }
  9237. this.session = this.raw;
  9238. jingle.find('>content').each(function () {
  9239. var m = self.jingle2media($(this));
  9240. self.media.push(m);
  9241. });
  9242. // reconstruct msid-semantic -- apparently not necessary
  9243. /*
  9244. var msid = SDPUtil.parse_ssrc(this.raw);
  9245. if (msid.hasOwnProperty('mslabel')) {
  9246. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  9247. }
  9248. */
  9249. this.raw = this.session + this.media.join('');
  9250. };
  9251. // translate a jingle content element into an an SDP media part
  9252. SDP.prototype.jingle2media = function (content) {
  9253. var media = '',
  9254. desc = content.find('description'),
  9255. ssrc = desc.attr('ssrc'),
  9256. self = this,
  9257. tmp;
  9258. var sctp = content.find(
  9259. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  9260. tmp = { media: desc.attr('media') };
  9261. tmp.port = '1';
  9262. if (content.attr('senders') == 'rejected') {
  9263. // estos hack to reject an m-line.
  9264. tmp.port = '0';
  9265. }
  9266. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  9267. if (sctp.length)
  9268. tmp.proto = 'DTLS/SCTP';
  9269. else
  9270. tmp.proto = 'RTP/SAVPF';
  9271. } else {
  9272. tmp.proto = 'RTP/AVPF';
  9273. }
  9274. if (!sctp.length) {
  9275. tmp.fmt = desc.find('payload-type').map(
  9276. function () { return this.getAttribute('id'); }).get();
  9277. media += SDPUtil.build_mline(tmp) + '\r\n';
  9278. } else {
  9279. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  9280. media += 'a=sctpmap:' + sctp.attr('number') +
  9281. ' ' + sctp.attr('protocol');
  9282. var streamCount = sctp.attr('streams');
  9283. if (streamCount)
  9284. media += ' ' + streamCount + '\r\n';
  9285. else
  9286. media += '\r\n';
  9287. }
  9288. media += 'c=IN IP4 0.0.0.0\r\n';
  9289. if (!sctp.length)
  9290. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  9291. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  9292. if (tmp.length) {
  9293. if (tmp.attr('ufrag')) {
  9294. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  9295. }
  9296. if (tmp.attr('pwd')) {
  9297. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  9298. }
  9299. tmp.find('>fingerprint').each(function () {
  9300. // FIXME: check namespace at some point
  9301. media += 'a=fingerprint:' + this.getAttribute('hash');
  9302. media += ' ' + $(this).text();
  9303. media += '\r\n';
  9304. if (this.getAttribute('setup')) {
  9305. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  9306. }
  9307. });
  9308. }
  9309. switch (content.attr('senders')) {
  9310. case 'initiator':
  9311. media += 'a=sendonly\r\n';
  9312. break;
  9313. case 'responder':
  9314. media += 'a=recvonly\r\n';
  9315. break;
  9316. case 'none':
  9317. media += 'a=inactive\r\n';
  9318. break;
  9319. case 'both':
  9320. media += 'a=sendrecv\r\n';
  9321. break;
  9322. }
  9323. media += 'a=mid:' + content.attr('name') + '\r\n';
  9324. // <description><rtcp-mux/></description>
  9325. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  9326. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  9327. if (desc.find('rtcp-mux').length) {
  9328. media += 'a=rtcp-mux\r\n';
  9329. }
  9330. if (desc.find('encryption').length) {
  9331. desc.find('encryption>crypto').each(function () {
  9332. media += 'a=crypto:' + this.getAttribute('tag');
  9333. media += ' ' + this.getAttribute('crypto-suite');
  9334. media += ' ' + this.getAttribute('key-params');
  9335. if (this.getAttribute('session-params')) {
  9336. media += ' ' + this.getAttribute('session-params');
  9337. }
  9338. media += '\r\n';
  9339. });
  9340. }
  9341. desc.find('payload-type').each(function () {
  9342. media += SDPUtil.build_rtpmap(this) + '\r\n';
  9343. if ($(this).find('>parameter').length) {
  9344. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  9345. media += $(this).find('parameter').map(function () {
  9346. return (this.getAttribute('name')
  9347. ? (this.getAttribute('name') + '=') : '') +
  9348. this.getAttribute('value');
  9349. }).get().join('; ');
  9350. media += '\r\n';
  9351. }
  9352. // xep-0293
  9353. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  9354. });
  9355. // xep-0293
  9356. media += self.rtcpFbFromJingle(desc, '*');
  9357. // xep-0294
  9358. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  9359. tmp.each(function () {
  9360. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  9361. });
  9362. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  9363. var protocol = this.getAttribute('protocol');
  9364. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  9365. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9366. (self.removeUdpCandidates && protocol === 'udp')) {
  9367. return;
  9368. }
  9369. media += SDPUtil.candidateFromJingle(this);
  9370. });
  9371. // XEP-0339 handle ssrc-group attributes
  9372. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  9373. var semantics = this.getAttribute('semantics');
  9374. var ssrcs = $(this).find('>source').map(function() {
  9375. return this.getAttribute('ssrc');
  9376. }).get();
  9377. if (ssrcs.length) {
  9378. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  9379. }
  9380. });
  9381. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  9382. tmp.each(function () {
  9383. var ssrc = this.getAttribute('ssrc');
  9384. $(this).find('>parameter').each(function () {
  9385. var name = this.getAttribute('name');
  9386. var value = this.getAttribute('value');
  9387. value = SDPUtil.filter_special_chars(value);
  9388. media += 'a=ssrc:' + ssrc + ' ' + name;
  9389. if (value && value.length)
  9390. media += ':' + value;
  9391. media += '\r\n';
  9392. });
  9393. });
  9394. return media;
  9395. };
  9396. module.exports = SDP;
  9397. }).call(this,"/modules/xmpp/SDP.js")
  9398. },{"./SDPUtil":33,"jitsi-meet-logger":49}],32:[function(require,module,exports){
  9399. var SDPUtil = require("./SDPUtil");
  9400. function SDPDiffer(mySDP, otherSDP)
  9401. {
  9402. this.mySDP = mySDP;
  9403. this.otherSDP = otherSDP;
  9404. }
  9405. /**
  9406. * Returns map of MediaChannel that contains media contained in
  9407. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  9408. */
  9409. SDPDiffer.prototype.getNewMedia = function() {
  9410. // this could be useful in Array.prototype.
  9411. function arrayEquals(array) {
  9412. // if the other array is a falsy value, return
  9413. if (!array)
  9414. return false;
  9415. // compare lengths - can save a lot of time
  9416. if (this.length != array.length)
  9417. return false;
  9418. for (var i = 0, l=this.length; i < l; i++) {
  9419. // Check if we have nested arrays
  9420. if (this[i] instanceof Array && array[i] instanceof Array) {
  9421. // recurse into the nested arrays
  9422. if (!this[i].equals(array[i]))
  9423. return false;
  9424. }
  9425. else if (this[i] != array[i]) {
  9426. // Warning - two different object instances will never be
  9427. // equal: {x:20} != {x:20}
  9428. return false;
  9429. }
  9430. }
  9431. return true;
  9432. }
  9433. var myMedias = this.mySDP.getMediaSsrcMap();
  9434. var othersMedias = this.otherSDP.getMediaSsrcMap();
  9435. var newMedia = {};
  9436. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  9437. var myMedia = myMedias[othersMediaIdx];
  9438. var othersMedia = othersMedias[othersMediaIdx];
  9439. if(!myMedia && othersMedia) {
  9440. // Add whole channel
  9441. newMedia[othersMediaIdx] = othersMedia;
  9442. return;
  9443. }
  9444. // Look for new ssrcs across the channel
  9445. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  9446. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  9447. // Allocate channel if we've found ssrc that doesn't exist in
  9448. // our channel
  9449. if(!newMedia[othersMediaIdx]){
  9450. newMedia[othersMediaIdx] = {
  9451. mediaindex: othersMedia.mediaindex,
  9452. mid: othersMedia.mid,
  9453. ssrcs: {},
  9454. ssrcGroups: []
  9455. };
  9456. }
  9457. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  9458. }
  9459. });
  9460. // Look for new ssrc groups across the channels
  9461. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  9462. // try to match the other ssrc-group with an ssrc-group of ours
  9463. var matched = false;
  9464. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  9465. var mySsrcGroup = myMedia.ssrcGroups[i];
  9466. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  9467. arrayEquals.apply(otherSsrcGroup.ssrcs,
  9468. [mySsrcGroup.ssrcs])) {
  9469. matched = true;
  9470. break;
  9471. }
  9472. }
  9473. if (!matched) {
  9474. // Allocate channel if we've found an ssrc-group that doesn't
  9475. // exist in our channel
  9476. if(!newMedia[othersMediaIdx]){
  9477. newMedia[othersMediaIdx] = {
  9478. mediaindex: othersMedia.mediaindex,
  9479. mid: othersMedia.mid,
  9480. ssrcs: {},
  9481. ssrcGroups: []
  9482. };
  9483. }
  9484. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  9485. }
  9486. });
  9487. });
  9488. return newMedia;
  9489. };
  9490. /**
  9491. * TODO: document!
  9492. */
  9493. SDPDiffer.prototype.toJingle = function(modify) {
  9494. var sdpMediaSsrcs = this.getNewMedia();
  9495. var modified = false;
  9496. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  9497. modified = true;
  9498. var media = sdpMediaSsrcs[mediaindex];
  9499. modify.c('content', {name: media.mid});
  9500. modify.c('description',
  9501. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  9502. // FIXME: not completely sure this operates on blocks and / or handles
  9503. // different ssrcs correctly
  9504. // generate sources from lines
  9505. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  9506. var mediaSsrc = media.ssrcs[ssrcNum];
  9507. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9508. modify.attrs({ssrc: mediaSsrc.ssrc});
  9509. // iterate over ssrc lines
  9510. mediaSsrc.lines.forEach(function (line) {
  9511. var idx = line.indexOf(' ');
  9512. var kv = line.substr(idx + 1);
  9513. modify.c('parameter');
  9514. if (kv.indexOf(':') == -1) {
  9515. modify.attrs({ name: kv });
  9516. } else {
  9517. var nv = kv.split(':', 2);
  9518. var name = nv[0];
  9519. var value = SDPUtil.filter_special_chars(nv[1]);
  9520. modify.attrs({ name: name });
  9521. modify.attrs({ value: value });
  9522. }
  9523. modify.up(); // end of parameter
  9524. });
  9525. modify.up(); // end of source
  9526. });
  9527. // generate source groups from lines
  9528. media.ssrcGroups.forEach(function(ssrcGroup) {
  9529. if (ssrcGroup.ssrcs.length) {
  9530. modify.c('ssrc-group', {
  9531. semantics: ssrcGroup.semantics,
  9532. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  9533. });
  9534. ssrcGroup.ssrcs.forEach(function (ssrc) {
  9535. modify.c('source', { ssrc: ssrc })
  9536. .up(); // end of source
  9537. });
  9538. modify.up(); // end of ssrc-group
  9539. }
  9540. });
  9541. modify.up(); // end of description
  9542. modify.up(); // end of content
  9543. });
  9544. return modified;
  9545. };
  9546. module.exports = SDPDiffer;
  9547. },{"./SDPUtil":33}],33:[function(require,module,exports){
  9548. (function (__filename){
  9549. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9550. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9551. SDPUtil = {
  9552. filter_special_chars: function (text) {
  9553. return text.replace(/[\\\/\{,\}\+]/g, "");
  9554. },
  9555. iceparams: function (mediadesc, sessiondesc) {
  9556. var data = null;
  9557. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  9558. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  9559. data = {
  9560. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  9561. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  9562. };
  9563. }
  9564. return data;
  9565. },
  9566. parse_iceufrag: function (line) {
  9567. return line.substring(12);
  9568. },
  9569. build_iceufrag: function (frag) {
  9570. return 'a=ice-ufrag:' + frag;
  9571. },
  9572. parse_icepwd: function (line) {
  9573. return line.substring(10);
  9574. },
  9575. build_icepwd: function (pwd) {
  9576. return 'a=ice-pwd:' + pwd;
  9577. },
  9578. parse_mid: function (line) {
  9579. return line.substring(6);
  9580. },
  9581. parse_mline: function (line) {
  9582. var parts = line.substring(2).split(' '),
  9583. data = {};
  9584. data.media = parts.shift();
  9585. data.port = parts.shift();
  9586. data.proto = parts.shift();
  9587. if (parts[parts.length - 1] === '') { // trailing whitespace
  9588. parts.pop();
  9589. }
  9590. data.fmt = parts;
  9591. return data;
  9592. },
  9593. build_mline: function (mline) {
  9594. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  9595. },
  9596. parse_rtpmap: function (line) {
  9597. var parts = line.substring(9).split(' '),
  9598. data = {};
  9599. data.id = parts.shift();
  9600. parts = parts[0].split('/');
  9601. data.name = parts.shift();
  9602. data.clockrate = parts.shift();
  9603. data.channels = parts.length ? parts.shift() : '1';
  9604. return data;
  9605. },
  9606. /**
  9607. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  9608. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  9609. * @returns [SCTP port number, protocol, streams]
  9610. */
  9611. parse_sctpmap: function (line)
  9612. {
  9613. var parts = line.substring(10).split(' ');
  9614. var sctpPort = parts[0];
  9615. var protocol = parts[1];
  9616. // Stream count is optional
  9617. var streamCount = parts.length > 2 ? parts[2] : null;
  9618. return [sctpPort, protocol, streamCount];// SCTP port
  9619. },
  9620. build_rtpmap: function (el) {
  9621. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  9622. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  9623. line += '/' + el.getAttribute('channels');
  9624. }
  9625. return line;
  9626. },
  9627. parse_crypto: function (line) {
  9628. var parts = line.substring(9).split(' '),
  9629. data = {};
  9630. data.tag = parts.shift();
  9631. data['crypto-suite'] = parts.shift();
  9632. data['key-params'] = parts.shift();
  9633. if (parts.length) {
  9634. data['session-params'] = parts.join(' ');
  9635. }
  9636. return data;
  9637. },
  9638. parse_fingerprint: function (line) { // RFC 4572
  9639. var parts = line.substring(14).split(' '),
  9640. data = {};
  9641. data.hash = parts.shift();
  9642. data.fingerprint = parts.shift();
  9643. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  9644. return data;
  9645. },
  9646. parse_fmtp: function (line) {
  9647. var parts = line.split(' '),
  9648. i, key, value,
  9649. data = [];
  9650. parts.shift();
  9651. parts = parts.join(' ').split(';');
  9652. for (i = 0; i < parts.length; i++) {
  9653. key = parts[i].split('=')[0];
  9654. while (key.length && key[0] == ' ') {
  9655. key = key.substring(1);
  9656. }
  9657. value = parts[i].split('=')[1];
  9658. if (key && value) {
  9659. data.push({name: key, value: value});
  9660. } else if (key) {
  9661. // rfc 4733 (DTMF) style stuff
  9662. data.push({name: '', value: key});
  9663. }
  9664. }
  9665. return data;
  9666. },
  9667. parse_icecandidate: function (line) {
  9668. var candidate = {},
  9669. elems = line.split(' ');
  9670. candidate.foundation = elems[0].substring(12);
  9671. candidate.component = elems[1];
  9672. candidate.protocol = elems[2].toLowerCase();
  9673. candidate.priority = elems[3];
  9674. candidate.ip = elems[4];
  9675. candidate.port = elems[5];
  9676. // elems[6] => "typ"
  9677. candidate.type = elems[7];
  9678. candidate.generation = 0; // default value, may be overwritten below
  9679. for (var i = 8; i < elems.length; i += 2) {
  9680. switch (elems[i]) {
  9681. case 'raddr':
  9682. candidate['rel-addr'] = elems[i + 1];
  9683. break;
  9684. case 'rport':
  9685. candidate['rel-port'] = elems[i + 1];
  9686. break;
  9687. case 'generation':
  9688. candidate.generation = elems[i + 1];
  9689. break;
  9690. case 'tcptype':
  9691. candidate.tcptype = elems[i + 1];
  9692. break;
  9693. default: // TODO
  9694. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9695. }
  9696. }
  9697. candidate.network = '1';
  9698. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9699. return candidate;
  9700. },
  9701. build_icecandidate: function (cand) {
  9702. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  9703. line += ' ';
  9704. switch (cand.type) {
  9705. case 'srflx':
  9706. case 'prflx':
  9707. case 'relay':
  9708. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  9709. line += 'raddr';
  9710. line += ' ';
  9711. line += cand['rel-addr'];
  9712. line += ' ';
  9713. line += 'rport';
  9714. line += ' ';
  9715. line += cand['rel-port'];
  9716. line += ' ';
  9717. }
  9718. break;
  9719. }
  9720. if (cand.hasOwnAttribute('tcptype')) {
  9721. line += 'tcptype';
  9722. line += ' ';
  9723. line += cand.tcptype;
  9724. line += ' ';
  9725. }
  9726. line += 'generation';
  9727. line += ' ';
  9728. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  9729. return line;
  9730. },
  9731. parse_ssrc: function (desc) {
  9732. // proprietary mapping of a=ssrc lines
  9733. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  9734. // and parse according to that
  9735. var lines = desc.split('\r\n'),
  9736. data = {};
  9737. for (var i = 0; i < lines.length; i++) {
  9738. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  9739. var idx = lines[i].indexOf(' ');
  9740. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  9741. }
  9742. }
  9743. return data;
  9744. },
  9745. parse_rtcpfb: function (line) {
  9746. var parts = line.substr(10).split(' ');
  9747. var data = {};
  9748. data.pt = parts.shift();
  9749. data.type = parts.shift();
  9750. data.params = parts;
  9751. return data;
  9752. },
  9753. parse_extmap: function (line) {
  9754. var parts = line.substr(9).split(' ');
  9755. var data = {};
  9756. data.value = parts.shift();
  9757. if (data.value.indexOf('/') != -1) {
  9758. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  9759. data.value = data.value.substr(0, data.value.indexOf('/'));
  9760. } else {
  9761. data.direction = 'both';
  9762. }
  9763. data.uri = parts.shift();
  9764. data.params = parts;
  9765. return data;
  9766. },
  9767. find_line: function (haystack, needle, sessionpart) {
  9768. var lines = haystack.split('\r\n');
  9769. for (var i = 0; i < lines.length; i++) {
  9770. if (lines[i].substring(0, needle.length) == needle) {
  9771. return lines[i];
  9772. }
  9773. }
  9774. if (!sessionpart) {
  9775. return false;
  9776. }
  9777. // search session part
  9778. lines = sessionpart.split('\r\n');
  9779. for (var j = 0; j < lines.length; j++) {
  9780. if (lines[j].substring(0, needle.length) == needle) {
  9781. return lines[j];
  9782. }
  9783. }
  9784. return false;
  9785. },
  9786. find_lines: function (haystack, needle, sessionpart) {
  9787. var lines = haystack.split('\r\n'),
  9788. needles = [];
  9789. for (var i = 0; i < lines.length; i++) {
  9790. if (lines[i].substring(0, needle.length) == needle)
  9791. needles.push(lines[i]);
  9792. }
  9793. if (needles.length || !sessionpart) {
  9794. return needles;
  9795. }
  9796. // search session part
  9797. lines = sessionpart.split('\r\n');
  9798. for (var j = 0; j < lines.length; j++) {
  9799. if (lines[j].substring(0, needle.length) == needle) {
  9800. needles.push(lines[j]);
  9801. }
  9802. }
  9803. return needles;
  9804. },
  9805. candidateToJingle: function (line) {
  9806. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  9807. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  9808. if (line.indexOf('candidate:') === 0) {
  9809. line = 'a=' + line;
  9810. } else if (line.substring(0, 12) != 'a=candidate:') {
  9811. logger.log('parseCandidate called with a line that is not a candidate line');
  9812. logger.log(line);
  9813. return null;
  9814. }
  9815. if (line.substring(line.length - 2) == '\r\n') // chomp it
  9816. line = line.substring(0, line.length - 2);
  9817. var candidate = {},
  9818. elems = line.split(' '),
  9819. i;
  9820. if (elems[6] != 'typ') {
  9821. logger.log('did not find typ in the right place');
  9822. logger.log(line);
  9823. return null;
  9824. }
  9825. candidate.foundation = elems[0].substring(12);
  9826. candidate.component = elems[1];
  9827. candidate.protocol = elems[2].toLowerCase();
  9828. candidate.priority = elems[3];
  9829. candidate.ip = elems[4];
  9830. candidate.port = elems[5];
  9831. // elems[6] => "typ"
  9832. candidate.type = elems[7];
  9833. candidate.generation = '0'; // default, may be overwritten below
  9834. for (i = 8; i < elems.length; i += 2) {
  9835. switch (elems[i]) {
  9836. case 'raddr':
  9837. candidate['rel-addr'] = elems[i + 1];
  9838. break;
  9839. case 'rport':
  9840. candidate['rel-port'] = elems[i + 1];
  9841. break;
  9842. case 'generation':
  9843. candidate.generation = elems[i + 1];
  9844. break;
  9845. case 'tcptype':
  9846. candidate.tcptype = elems[i + 1];
  9847. break;
  9848. default: // TODO
  9849. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9850. }
  9851. }
  9852. candidate.network = '1';
  9853. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9854. return candidate;
  9855. },
  9856. candidateFromJingle: function (cand) {
  9857. var line = 'a=candidate:';
  9858. line += cand.getAttribute('foundation');
  9859. line += ' ';
  9860. line += cand.getAttribute('component');
  9861. line += ' ';
  9862. var protocol = cand.getAttribute('protocol');
  9863. // use tcp candidates for FF
  9864. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  9865. protocol = 'tcp';
  9866. }
  9867. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  9868. line += ' ';
  9869. line += cand.getAttribute('priority');
  9870. line += ' ';
  9871. line += cand.getAttribute('ip');
  9872. line += ' ';
  9873. line += cand.getAttribute('port');
  9874. line += ' ';
  9875. line += 'typ';
  9876. line += ' ' + cand.getAttribute('type');
  9877. line += ' ';
  9878. switch (cand.getAttribute('type')) {
  9879. case 'srflx':
  9880. case 'prflx':
  9881. case 'relay':
  9882. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  9883. line += 'raddr';
  9884. line += ' ';
  9885. line += cand.getAttribute('rel-addr');
  9886. line += ' ';
  9887. line += 'rport';
  9888. line += ' ';
  9889. line += cand.getAttribute('rel-port');
  9890. line += ' ';
  9891. }
  9892. break;
  9893. }
  9894. if (protocol.toLowerCase() == 'tcp') {
  9895. line += 'tcptype';
  9896. line += ' ';
  9897. line += cand.getAttribute('tcptype');
  9898. line += ' ';
  9899. }
  9900. line += 'generation';
  9901. line += ' ';
  9902. line += cand.getAttribute('generation') || '0';
  9903. return line + '\r\n';
  9904. }
  9905. };
  9906. module.exports = SDPUtil;
  9907. }).call(this,"/modules/xmpp/SDPUtil.js")
  9908. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":49}],34:[function(require,module,exports){
  9909. (function (__filename){
  9910. /* global $ */
  9911. var RTC = require('../RTC/RTC');
  9912. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9913. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  9914. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9915. function TraceablePeerConnection(ice_config, constraints, session) {
  9916. var self = this;
  9917. this.session = session;
  9918. var RTCPeerConnectionType = null;
  9919. if (RTCBrowserType.isFirefox()) {
  9920. RTCPeerConnectionType = mozRTCPeerConnection;
  9921. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  9922. RTCPeerConnectionType = RTCPeerConnection;
  9923. } else {
  9924. RTCPeerConnectionType = webkitRTCPeerConnection;
  9925. }
  9926. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  9927. this.updateLog = [];
  9928. this.stats = {};
  9929. this.statsinterval = null;
  9930. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  9931. var Interop = require('sdp-interop').Interop;
  9932. this.interop = new Interop();
  9933. var Simulcast = require('sdp-simulcast');
  9934. this.simulcast = new Simulcast({numOfLayers: 3,
  9935. explodeRemoteSimulcast: false});
  9936. this.eventEmitter = this.session.room.eventEmitter;
  9937. // override as desired
  9938. this.trace = function (what, info) {
  9939. /*logger.warn('WTRACE', what, info);
  9940. if (info && RTCBrowserType.isIExplorer()) {
  9941. if (info.length > 1024) {
  9942. logger.warn('WTRACE', what, info.substr(1024));
  9943. }
  9944. if (info.length > 2048) {
  9945. logger.warn('WTRACE', what, info.substr(2048));
  9946. }
  9947. }*/
  9948. self.updateLog.push({
  9949. time: new Date(),
  9950. type: what,
  9951. value: info || ""
  9952. });
  9953. };
  9954. this.onicecandidate = null;
  9955. this.peerconnection.onicecandidate = function (event) {
  9956. // FIXME: this causes stack overflow with Temasys Plugin
  9957. if (!RTCBrowserType.isTemasysPluginUsed())
  9958. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  9959. if (self.onicecandidate !== null) {
  9960. self.onicecandidate(event);
  9961. }
  9962. };
  9963. this.onaddstream = null;
  9964. this.peerconnection.onaddstream = function (event) {
  9965. self.trace('onaddstream', event.stream.id);
  9966. if (self.onaddstream !== null) {
  9967. self.onaddstream(event);
  9968. }
  9969. };
  9970. this.onremovestream = null;
  9971. this.peerconnection.onremovestream = function (event) {
  9972. self.trace('onremovestream', event.stream.id);
  9973. if (self.onremovestream !== null) {
  9974. self.onremovestream(event);
  9975. }
  9976. };
  9977. this.onsignalingstatechange = null;
  9978. this.peerconnection.onsignalingstatechange = function (event) {
  9979. self.trace('onsignalingstatechange', self.signalingState);
  9980. if (self.onsignalingstatechange !== null) {
  9981. self.onsignalingstatechange(event);
  9982. }
  9983. };
  9984. this.oniceconnectionstatechange = null;
  9985. this.peerconnection.oniceconnectionstatechange = function (event) {
  9986. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  9987. if (self.oniceconnectionstatechange !== null) {
  9988. self.oniceconnectionstatechange(event);
  9989. }
  9990. };
  9991. this.onnegotiationneeded = null;
  9992. this.peerconnection.onnegotiationneeded = function (event) {
  9993. self.trace('onnegotiationneeded');
  9994. if (self.onnegotiationneeded !== null) {
  9995. self.onnegotiationneeded(event);
  9996. }
  9997. };
  9998. self.ondatachannel = null;
  9999. this.peerconnection.ondatachannel = function (event) {
  10000. self.trace('ondatachannel', event);
  10001. if (self.ondatachannel !== null) {
  10002. self.ondatachannel(event);
  10003. }
  10004. };
  10005. // XXX: do all non-firefox browsers which we support also support this?
  10006. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  10007. this.statsinterval = window.setInterval(function() {
  10008. self.peerconnection.getStats(function(stats) {
  10009. var results = stats.result();
  10010. var now = new Date();
  10011. for (var i = 0; i < results.length; ++i) {
  10012. results[i].names().forEach(function (name) {
  10013. var id = results[i].id + '-' + name;
  10014. if (!self.stats[id]) {
  10015. self.stats[id] = {
  10016. startTime: now,
  10017. endTime: now,
  10018. values: [],
  10019. times: []
  10020. };
  10021. }
  10022. self.stats[id].values.push(results[i].stat(name));
  10023. self.stats[id].times.push(now.getTime());
  10024. if (self.stats[id].values.length > self.maxstats) {
  10025. self.stats[id].values.shift();
  10026. self.stats[id].times.shift();
  10027. }
  10028. self.stats[id].endTime = now;
  10029. });
  10030. }
  10031. });
  10032. }, 1000);
  10033. }
  10034. }
  10035. /**
  10036. * Returns a string representation of a SessionDescription object.
  10037. */
  10038. var dumpSDP = function(description) {
  10039. if (typeof description === 'undefined' || description == null) {
  10040. return '';
  10041. }
  10042. return 'type: ' + description.type + '\r\n' + description.sdp;
  10043. };
  10044. var insertRecvOnlySSRC = function (desc) {
  10045. if (typeof desc !== 'object' || desc === null ||
  10046. typeof desc.sdp !== 'string') {
  10047. console.warn('An empty description was passed as an argument.');
  10048. return desc;
  10049. }
  10050. var transform = require('sdp-transform');
  10051. var RandomUtil = require('../util/RandomUtil');
  10052. var session = transform.parse(desc.sdp);
  10053. if (!Array.isArray(session.media))
  10054. {
  10055. return;
  10056. }
  10057. var modded = false;
  10058. session.media.forEach(function (bLine) {
  10059. if (bLine.direction != 'recvonly')
  10060. {
  10061. return;
  10062. }
  10063. modded = true;
  10064. if (!Array.isArray(bLine.ssrcs) || bLine.ssrcs.length === 0)
  10065. {
  10066. var ssrc = RandomUtil.randomInt(1, 0xffffffff);
  10067. bLine.ssrcs = [{
  10068. id: ssrc,
  10069. attribute: 'cname',
  10070. value: ['recvonly-', ssrc].join('')
  10071. }];
  10072. }
  10073. });
  10074. return (!modded) ? desc : new RTCSessionDescription({
  10075. type: desc.type,
  10076. sdp: transform.write(session),
  10077. });
  10078. };
  10079. /**
  10080. * Takes a SessionDescription object and returns a "normalized" version.
  10081. * Currently it only takes care of ordering the a=ssrc lines.
  10082. */
  10083. var normalizePlanB = function(desc) {
  10084. if (typeof desc !== 'object' || desc === null ||
  10085. typeof desc.sdp !== 'string') {
  10086. logger.warn('An empty description was passed as an argument.');
  10087. return desc;
  10088. }
  10089. var transform = require('sdp-transform');
  10090. var session = transform.parse(desc.sdp);
  10091. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  10092. Array.isArray(session.media)) {
  10093. session.media.forEach(function (mLine) {
  10094. // Chrome appears to be picky about the order in which a=ssrc lines
  10095. // are listed in an m-line when rtx is enabled (and thus there are
  10096. // a=ssrc-group lines with FID semantics). Specifically if we have
  10097. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  10098. // the "a=ssrc:S1" lines, SRD fails.
  10099. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  10100. // first.
  10101. var firstSsrcs = [];
  10102. var newSsrcLines = [];
  10103. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  10104. mLine.ssrcGroups.forEach(function (group) {
  10105. if (typeof group.semantics !== 'undefined' &&
  10106. group.semantics === 'FID') {
  10107. if (typeof group.ssrcs !== 'undefined') {
  10108. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  10109. }
  10110. }
  10111. });
  10112. }
  10113. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  10114. var i;
  10115. for (i = 0; i<mLine.ssrcs.length; i++){
  10116. if (typeof mLine.ssrcs[i] === 'object'
  10117. && typeof mLine.ssrcs[i].id !== 'undefined'
  10118. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  10119. newSsrcLines.push(mLine.ssrcs[i]);
  10120. delete mLine.ssrcs[i];
  10121. }
  10122. }
  10123. for (i = 0; i<mLine.ssrcs.length; i++){
  10124. if (typeof mLine.ssrcs[i] !== 'undefined') {
  10125. newSsrcLines.push(mLine.ssrcs[i]);
  10126. }
  10127. }
  10128. mLine.ssrcs = newSsrcLines;
  10129. }
  10130. });
  10131. }
  10132. var resStr = transform.write(session);
  10133. return new RTCSessionDescription({
  10134. type: desc.type,
  10135. sdp: resStr
  10136. });
  10137. };
  10138. var getters = {
  10139. signalingState: function () {
  10140. return this.peerconnection.signalingState;
  10141. },
  10142. iceConnectionState: function () {
  10143. return this.peerconnection.iceConnectionState;
  10144. },
  10145. localDescription: function() {
  10146. var desc = this.peerconnection.localDescription;
  10147. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  10148. // if we're running on FF, transform to Plan B first.
  10149. if (RTCBrowserType.usesUnifiedPlan()) {
  10150. desc = this.interop.toPlanB(desc);
  10151. this.trace('getLocalDescription::postTransform (Plan B)',
  10152. dumpSDP(desc));
  10153. }
  10154. return desc;
  10155. },
  10156. remoteDescription: function() {
  10157. var desc = this.peerconnection.remoteDescription;
  10158. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  10159. // if we're running on FF, transform to Plan B first.
  10160. if (RTCBrowserType.usesUnifiedPlan()) {
  10161. desc = this.interop.toPlanB(desc);
  10162. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  10163. }
  10164. return desc;
  10165. }
  10166. };
  10167. Object.keys(getters).forEach(function (prop) {
  10168. Object.defineProperty(
  10169. TraceablePeerConnection.prototype,
  10170. prop, {
  10171. get: getters[prop]
  10172. }
  10173. );
  10174. });
  10175. TraceablePeerConnection.prototype.addStream = function (stream) {
  10176. this.trace('addStream', stream.id);
  10177. try
  10178. {
  10179. this.peerconnection.addStream(stream);
  10180. }
  10181. catch (e)
  10182. {
  10183. logger.error(e);
  10184. }
  10185. };
  10186. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  10187. this.trace('removeStream', stream.id);
  10188. if(stopStreams) {
  10189. RTC.stopMediaStream(stream);
  10190. }
  10191. try {
  10192. // FF doesn't support this yet.
  10193. if (this.peerconnection.removeStream)
  10194. this.peerconnection.removeStream(stream);
  10195. } catch (e) {
  10196. logger.error(e);
  10197. }
  10198. };
  10199. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  10200. this.trace('createDataChannel', label, opts);
  10201. return this.peerconnection.createDataChannel(label, opts);
  10202. };
  10203. TraceablePeerConnection.prototype.setLocalDescription
  10204. = function (description, successCallback, failureCallback) {
  10205. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  10206. // if we're running on FF, transform to Plan A first.
  10207. if (RTCBrowserType.usesUnifiedPlan()) {
  10208. description = this.interop.toUnifiedPlan(description);
  10209. this.trace('setLocalDescription::postTransform (Plan A)',
  10210. dumpSDP(description));
  10211. }
  10212. var self = this;
  10213. this.peerconnection.setLocalDescription(description,
  10214. function () {
  10215. self.trace('setLocalDescriptionOnSuccess');
  10216. successCallback();
  10217. },
  10218. function (err) {
  10219. self.trace('setLocalDescriptionOnFailure', err);
  10220. self.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  10221. err, self.peerconnection);
  10222. failureCallback(err);
  10223. }
  10224. );
  10225. };
  10226. TraceablePeerConnection.prototype.setRemoteDescription
  10227. = function (description, successCallback, failureCallback) {
  10228. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  10229. // TODO the focus should squeze or explode the remote simulcast
  10230. description = this.simulcast.mungeRemoteDescription(description);
  10231. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  10232. // if we're running on FF, transform to Plan A first.
  10233. if (RTCBrowserType.usesUnifiedPlan()) {
  10234. description = this.interop.toUnifiedPlan(description);
  10235. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  10236. }
  10237. if (RTCBrowserType.usesPlanB()) {
  10238. description = normalizePlanB(description);
  10239. }
  10240. var self = this;
  10241. this.peerconnection.setRemoteDescription(description,
  10242. function () {
  10243. self.trace('setRemoteDescriptionOnSuccess');
  10244. successCallback();
  10245. },
  10246. function (err) {
  10247. self.trace('setRemoteDescriptionOnFailure', err);
  10248. self.eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  10249. err, self.peerconnection);
  10250. failureCallback(err);
  10251. }
  10252. );
  10253. /*
  10254. if (this.statsinterval === null && this.maxstats > 0) {
  10255. // start gathering stats
  10256. }
  10257. */
  10258. };
  10259. TraceablePeerConnection.prototype.close = function () {
  10260. this.trace('stop');
  10261. if (this.statsinterval !== null) {
  10262. window.clearInterval(this.statsinterval);
  10263. this.statsinterval = null;
  10264. }
  10265. this.peerconnection.close();
  10266. };
  10267. TraceablePeerConnection.prototype.createOffer
  10268. = function (successCallback, failureCallback, constraints) {
  10269. var self = this;
  10270. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  10271. this.peerconnection.createOffer(
  10272. function (offer) {
  10273. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  10274. // NOTE this is not tested because in meet the focus generates the
  10275. // offer.
  10276. // if we're running on FF, transform to Plan B first.
  10277. if (RTCBrowserType.usesUnifiedPlan()) {
  10278. offer = self.interop.toPlanB(offer);
  10279. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  10280. }
  10281. if (RTCBrowserType.isChrome())
  10282. {
  10283. offer = insertRecvOnlySSRC(offer);
  10284. self.trace('createOfferOnSuccess::mungeLocalVideoSSRC', dumpSDP(offer));
  10285. }
  10286. if (!self.session.room.options.disableSimulcast
  10287. && self.simulcast.isSupported()) {
  10288. offer = self.simulcast.mungeLocalDescription(offer);
  10289. self.trace('createOfferOnSuccess::postTransform (simulcast)',
  10290. dumpSDP(offer));
  10291. }
  10292. successCallback(offer);
  10293. },
  10294. function(err) {
  10295. self.trace('createOfferOnFailure', err);
  10296. self.eventEmitter.emit(XMPPEvents.CREATE_OFFER_FAILED, err,
  10297. self.peerconnection);
  10298. failureCallback(err);
  10299. },
  10300. constraints
  10301. );
  10302. };
  10303. TraceablePeerConnection.prototype.createAnswer
  10304. = function (successCallback, failureCallback, constraints) {
  10305. var self = this;
  10306. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  10307. this.peerconnection.createAnswer(
  10308. function (answer) {
  10309. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  10310. // if we're running on FF, transform to Plan A first.
  10311. if (RTCBrowserType.usesUnifiedPlan()) {
  10312. answer = self.interop.toPlanB(answer);
  10313. self.trace('createAnswerOnSuccess::postTransform (Plan B)',
  10314. dumpSDP(answer));
  10315. }
  10316. if (RTCBrowserType.isChrome())
  10317. {
  10318. answer = insertRecvOnlySSRC(answer);
  10319. self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC', dumpSDP(answer));
  10320. }
  10321. if (!self.session.room.options.disableSimulcast
  10322. && self.simulcast.isSupported()) {
  10323. answer = self.simulcast.mungeLocalDescription(answer);
  10324. self.trace('createAnswerOnSuccess::postTransform (simulcast)',
  10325. dumpSDP(answer));
  10326. }
  10327. successCallback(answer);
  10328. },
  10329. function(err) {
  10330. self.trace('createAnswerOnFailure', err);
  10331. self.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_FAILED, err,
  10332. self.peerconnection);
  10333. failureCallback(err);
  10334. },
  10335. constraints
  10336. );
  10337. };
  10338. TraceablePeerConnection.prototype.addIceCandidate
  10339. = function (candidate, successCallback, failureCallback) {
  10340. //var self = this;
  10341. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  10342. this.peerconnection.addIceCandidate(candidate);
  10343. /* maybe later
  10344. this.peerconnection.addIceCandidate(candidate,
  10345. function () {
  10346. self.trace('addIceCandidateOnSuccess');
  10347. successCallback();
  10348. },
  10349. function (err) {
  10350. self.trace('addIceCandidateOnFailure', err);
  10351. failureCallback(err);
  10352. }
  10353. );
  10354. */
  10355. };
  10356. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  10357. // TODO: Is this the correct way to handle Opera, Temasys?
  10358. if (RTCBrowserType.isFirefox()) {
  10359. // ignore for now...
  10360. if(!errback)
  10361. errback = function () {};
  10362. this.peerconnection.getStats(null, callback, errback);
  10363. } else {
  10364. this.peerconnection.getStats(callback);
  10365. }
  10366. };
  10367. module.exports = TraceablePeerConnection;
  10368. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  10369. },{"../../service/xmpp/XMPPEvents":138,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":26,"jitsi-meet-logger":49,"sdp-interop":68,"sdp-simulcast":75,"sdp-transform":78}],35:[function(require,module,exports){
  10370. (function (__filename){
  10371. /* global $, $iq, Promise, Strophe */
  10372. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10373. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10374. var AuthenticationEvents
  10375. = require("../../service/authentication/AuthenticationEvents");
  10376. function createExpBackoffTimer(step) {
  10377. var count = 1;
  10378. return function (reset) {
  10379. // Reset call
  10380. if (reset) {
  10381. count = 1;
  10382. return;
  10383. }
  10384. // Calculate next timeout
  10385. var timeout = Math.pow(2, count - 1);
  10386. count += 1;
  10387. return timeout * step;
  10388. };
  10389. }
  10390. function Moderator(roomName, xmpp, emitter, settings) {
  10391. this.roomName = roomName;
  10392. this.xmppService = xmpp;
  10393. this.getNextTimeout = createExpBackoffTimer(1000);
  10394. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  10395. // External authentication stuff
  10396. this.externalAuthEnabled = false;
  10397. this.settings = settings;
  10398. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  10399. // it will be enabled automatically if focus detects the component through
  10400. // service discovery.
  10401. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  10402. this.xmppService.options.hosts.call_control !== undefined;
  10403. this.eventEmitter = emitter;
  10404. this.connection = this.xmppService.connection;
  10405. this.focusUserJid;
  10406. //FIXME:
  10407. // Message listener that talks to POPUP window
  10408. function listener(event) {
  10409. if (event.data && event.data.sessionId) {
  10410. if (event.origin !== window.location.origin) {
  10411. logger.warn("Ignoring sessionId from different origin: " +
  10412. event.origin);
  10413. return;
  10414. }
  10415. localStorage.setItem('sessionId', event.data.sessionId);
  10416. // After popup is closed we will authenticate
  10417. }
  10418. }
  10419. // Register
  10420. if (window.addEventListener) {
  10421. window.addEventListener("message", listener, false);
  10422. } else {
  10423. window.attachEvent("onmessage", listener);
  10424. }
  10425. }
  10426. Moderator.prototype.isExternalAuthEnabled = function () {
  10427. return this.externalAuthEnabled;
  10428. };
  10429. Moderator.prototype.isSipGatewayEnabled = function () {
  10430. return this.sipGatewayEnabled;
  10431. };
  10432. Moderator.prototype.onMucMemberLeft = function (jid) {
  10433. logger.info("Someone left is it focus ? " + jid);
  10434. var resource = Strophe.getResourceFromJid(jid);
  10435. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  10436. logger.info(
  10437. "Focus has left the room - leaving conference");
  10438. //hangUp();
  10439. // We'd rather reload to have everything re-initialized
  10440. //FIXME: show some message before reload
  10441. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  10442. }
  10443. };
  10444. Moderator.prototype.setFocusUserJid = function (focusJid) {
  10445. if (!this.focusUserJid) {
  10446. this.focusUserJid = focusJid;
  10447. logger.info("Focus jid set to: " + this.focusUserJid);
  10448. }
  10449. };
  10450. Moderator.prototype.getFocusUserJid = function () {
  10451. return this.focusUserJid;
  10452. };
  10453. Moderator.prototype.getFocusComponent = function () {
  10454. // Get focus component address
  10455. var focusComponent = this.xmppService.options.hosts.focus;
  10456. // If not specified use default: 'focus.domain'
  10457. if (!focusComponent) {
  10458. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  10459. }
  10460. return focusComponent;
  10461. };
  10462. Moderator.prototype.createConferenceIq = function () {
  10463. // Generate create conference IQ
  10464. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  10465. // Session Id used for authentication
  10466. var sessionId = localStorage.getItem('sessionId');
  10467. var machineUID = this.settings.getSettings().uid;
  10468. logger.info(
  10469. "Session ID: " + sessionId + " machine UID: " + machineUID);
  10470. elem.c('conference', {
  10471. xmlns: 'http://jitsi.org/protocol/focus',
  10472. room: this.roomName,
  10473. 'machine-uid': machineUID
  10474. });
  10475. if (sessionId) {
  10476. elem.attrs({ 'session-id': sessionId});
  10477. }
  10478. if (this.xmppService.options.hosts.bridge !== undefined) {
  10479. elem.c(
  10480. 'property', {
  10481. name: 'bridge',
  10482. value: this.xmppService.options.hosts.bridge
  10483. }).up();
  10484. }
  10485. if (this.xmppService.options.enforcedBridge !== undefined) {
  10486. elem.c(
  10487. 'property', {
  10488. name: 'enforcedBridge',
  10489. value: this.xmppService.options.enforcedBridge
  10490. }).up();
  10491. }
  10492. // Tell the focus we have Jigasi configured
  10493. if (this.xmppService.options.hosts.call_control !== undefined) {
  10494. elem.c(
  10495. 'property', {
  10496. name: 'call_control',
  10497. value: this.xmppService.options.hosts.call_control
  10498. }).up();
  10499. }
  10500. if (this.xmppService.options.channelLastN !== undefined) {
  10501. elem.c(
  10502. 'property', {
  10503. name: 'channelLastN',
  10504. value: this.xmppService.options.channelLastN
  10505. }).up();
  10506. }
  10507. if (this.xmppService.options.adaptiveLastN !== undefined) {
  10508. elem.c(
  10509. 'property', {
  10510. name: 'adaptiveLastN',
  10511. value: this.xmppService.options.adaptiveLastN
  10512. }).up();
  10513. }
  10514. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  10515. elem.c(
  10516. 'property', {
  10517. name: 'adaptiveSimulcast',
  10518. value: this.xmppService.options.adaptiveSimulcast
  10519. }).up();
  10520. }
  10521. if (this.xmppService.options.openSctp !== undefined) {
  10522. elem.c(
  10523. 'property', {
  10524. name: 'openSctp',
  10525. value: this.xmppService.options.openSctp
  10526. }).up();
  10527. }
  10528. if (this.xmppService.options.startAudioMuted !== undefined)
  10529. {
  10530. elem.c(
  10531. 'property', {
  10532. name: 'startAudioMuted',
  10533. value: this.xmppService.options.startAudioMuted
  10534. }).up();
  10535. }
  10536. if (this.xmppService.options.startVideoMuted !== undefined)
  10537. {
  10538. elem.c(
  10539. 'property', {
  10540. name: 'startVideoMuted',
  10541. value: this.xmppService.options.startVideoMuted
  10542. }).up();
  10543. }
  10544. elem.c(
  10545. 'property', {
  10546. name: 'simulcastMode',
  10547. value: 'rewriting'
  10548. }).up();
  10549. elem.up();
  10550. return elem;
  10551. };
  10552. Moderator.prototype.parseSessionId = function (resultIq) {
  10553. var sessionId = $(resultIq).find('conference').attr('session-id');
  10554. if (sessionId) {
  10555. logger.info('Received sessionId: ' + sessionId);
  10556. localStorage.setItem('sessionId', sessionId);
  10557. }
  10558. };
  10559. Moderator.prototype.parseConfigOptions = function (resultIq) {
  10560. this.setFocusUserJid(
  10561. $(resultIq).find('conference').attr('focusjid'));
  10562. var authenticationEnabled
  10563. = $(resultIq).find(
  10564. '>conference>property' +
  10565. '[name=\'authentication\'][value=\'true\']').length > 0;
  10566. logger.info("Authentication enabled: " + authenticationEnabled);
  10567. this.externalAuthEnabled = $(resultIq).find(
  10568. '>conference>property' +
  10569. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  10570. console.info(
  10571. 'External authentication enabled: ' + this.externalAuthEnabled);
  10572. if (!this.externalAuthEnabled) {
  10573. // We expect to receive sessionId in 'internal' authentication mode
  10574. this.parseSessionId(resultIq);
  10575. }
  10576. var authIdentity = $(resultIq).find('>conference').attr('identity');
  10577. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  10578. authenticationEnabled, authIdentity);
  10579. // Check if focus has auto-detected Jigasi component(this will be also
  10580. // included if we have passed our host from the config)
  10581. if ($(resultIq).find(
  10582. '>conference>property' +
  10583. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  10584. this.sipGatewayEnabled = true;
  10585. }
  10586. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  10587. };
  10588. // FIXME = we need to show the fact that we're waiting for the focus
  10589. // to the user(or that focus is not available)
  10590. Moderator.prototype.allocateConferenceFocus = function (callback) {
  10591. // Try to use focus user JID from the config
  10592. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  10593. // Send create conference IQ
  10594. var iq = this.createConferenceIq();
  10595. var self = this;
  10596. this.connection.sendIQ(
  10597. iq,
  10598. function (result) {
  10599. // Setup config options
  10600. self.parseConfigOptions(result);
  10601. if ('true' === $(result).find('conference').attr('ready')) {
  10602. // Reset both timers
  10603. self.getNextTimeout(true);
  10604. self.getNextErrorTimeout(true);
  10605. // Exec callback
  10606. callback();
  10607. } else {
  10608. var waitMs = self.getNextTimeout();
  10609. logger.info("Waiting for the focus... " + waitMs);
  10610. // Reset error timeout
  10611. self.getNextErrorTimeout(true);
  10612. window.setTimeout(
  10613. function () {
  10614. self.allocateConferenceFocus(callback);
  10615. }, waitMs);
  10616. }
  10617. },
  10618. function (error) {
  10619. // Invalid session ? remove and try again
  10620. // without session ID to get a new one
  10621. var invalidSession
  10622. = $(error).find('>error>session-invalid').length;
  10623. if (invalidSession) {
  10624. logger.info("Session expired! - removing");
  10625. localStorage.removeItem("sessionId");
  10626. }
  10627. if ($(error).find('>error>graceful-shutdown').length) {
  10628. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  10629. return;
  10630. }
  10631. // Check for error returned by the reservation system
  10632. var reservationErr = $(error).find('>error>reservation-error');
  10633. if (reservationErr.length) {
  10634. // Trigger error event
  10635. var errorCode = reservationErr.attr('error-code');
  10636. var errorMsg;
  10637. if ($(error).find('>error>text')) {
  10638. errorMsg = $(error).find('>error>text').text();
  10639. }
  10640. self.eventEmitter.emit(
  10641. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  10642. return;
  10643. }
  10644. // Not authorized to create new room
  10645. if ($(error).find('>error>not-authorized').length) {
  10646. logger.warn("Unauthorized to start the conference", error);
  10647. var toDomain
  10648. = Strophe.getDomainFromJid(error.getAttribute('to'));
  10649. if (toDomain !==
  10650. this.xmppService.options.hosts.anonymousdomain) {
  10651. //FIXME: "is external" should come either from
  10652. // the focus or config.js
  10653. self.externalAuthEnabled = true;
  10654. }
  10655. self.eventEmitter.emit(
  10656. XMPPEvents.AUTHENTICATION_REQUIRED,
  10657. function () {
  10658. self.allocateConferenceFocus(
  10659. callback);
  10660. });
  10661. return;
  10662. }
  10663. var waitMs = self.getNextErrorTimeout();
  10664. logger.error("Focus error, retry after " + waitMs, error);
  10665. // Show message
  10666. var focusComponent = self.getFocusComponent();
  10667. var retrySec = waitMs / 1000;
  10668. //FIXME: message is duplicated ?
  10669. // Do not show in case of session invalid
  10670. // which means just a retry
  10671. if (!invalidSession) {
  10672. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  10673. focusComponent, retrySec);
  10674. }
  10675. // Reset response timeout
  10676. self.getNextTimeout(true);
  10677. window.setTimeout(
  10678. function () {
  10679. self.allocateConferenceFocus(callback);
  10680. }, waitMs);
  10681. }
  10682. );
  10683. };
  10684. Moderator.prototype.authenticate = function () {
  10685. var self = this;
  10686. return new Promise(function (resolve, reject) {
  10687. self.connection.sendIQ(
  10688. self.createConferenceIq(),
  10689. function (result) {
  10690. self.parseSessionId(result);
  10691. resolve();
  10692. }, function (error) {
  10693. var code = $(error).find('>error').attr('code');
  10694. reject(error, code);
  10695. }
  10696. );
  10697. });
  10698. };
  10699. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  10700. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10701. iq.c('login-url', {
  10702. xmlns: 'http://jitsi.org/protocol/focus',
  10703. room: this.roomName,
  10704. 'machine-uid': this.settings.getSettings().uid
  10705. });
  10706. this.connection.sendIQ(
  10707. iq,
  10708. function (result) {
  10709. var url = $(result).find('login-url').attr('url');
  10710. url = url = decodeURIComponent(url);
  10711. if (url) {
  10712. logger.info("Got auth url: " + url);
  10713. urlCallback(url);
  10714. } else {
  10715. logger.error(
  10716. "Failed to get auth url from the focus", result);
  10717. failureCallback(result);
  10718. }
  10719. },
  10720. function (error) {
  10721. logger.error("Get auth url error", error);
  10722. failureCallback(error);
  10723. }
  10724. );
  10725. };
  10726. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  10727. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10728. iq.c('login-url', {
  10729. xmlns: 'http://jitsi.org/protocol/focus',
  10730. room: this.roomName,
  10731. 'machine-uid': this.settings.getSettings().uid,
  10732. popup: true
  10733. });
  10734. this.connection.sendIQ(
  10735. iq,
  10736. function (result) {
  10737. var url = $(result).find('login-url').attr('url');
  10738. url = url = decodeURIComponent(url);
  10739. if (url) {
  10740. logger.info("Got POPUP auth url: " + url);
  10741. urlCallback(url);
  10742. } else {
  10743. logger.error(
  10744. "Failed to get POPUP auth url from the focus", result);
  10745. failureCallback(result);
  10746. }
  10747. },
  10748. function (error) {
  10749. logger.error('Get POPUP auth url error', error);
  10750. failureCallback(error);
  10751. }
  10752. );
  10753. };
  10754. Moderator.prototype.logout = function (callback) {
  10755. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  10756. var sessionId = localStorage.getItem('sessionId');
  10757. if (!sessionId) {
  10758. callback();
  10759. return;
  10760. }
  10761. iq.c('logout', {
  10762. xmlns: 'http://jitsi.org/protocol/focus',
  10763. 'session-id': sessionId
  10764. });
  10765. this.connection.sendIQ(
  10766. iq,
  10767. function (result) {
  10768. var logoutUrl = $(result).find('logout').attr('logout-url');
  10769. if (logoutUrl) {
  10770. logoutUrl = decodeURIComponent(logoutUrl);
  10771. }
  10772. logger.info("Log out OK, url: " + logoutUrl, result);
  10773. localStorage.removeItem('sessionId');
  10774. callback(logoutUrl);
  10775. },
  10776. function (error) {
  10777. logger.error("Logout error", error);
  10778. }
  10779. );
  10780. };
  10781. module.exports = Moderator;
  10782. }).call(this,"/modules/xmpp/moderator.js")
  10783. },{"../../service/authentication/AuthenticationEvents":134,"../../service/xmpp/XMPPEvents":138,"jitsi-meet-logger":49}],36:[function(require,module,exports){
  10784. (function (__filename){
  10785. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  10786. Toolbar, Util, Promise */
  10787. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10788. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10789. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  10790. roomjid) {
  10791. this.eventEmitter = eventEmitter;
  10792. this.connection = connection;
  10793. this.state = "off";
  10794. this.focusMucJid = focusMucJid;
  10795. this.jirecon = jirecon;
  10796. this.url = null;
  10797. this.type = type;
  10798. this._isSupported = ((type === Recording.types.JIBRI)
  10799. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  10800. /**
  10801. * The ID of the jirecon recording session. Jirecon generates it when we
  10802. * initially start recording, and it needs to be used in subsequent requests
  10803. * to jirecon.
  10804. */
  10805. this.jireconRid = null;
  10806. this.roomjid = roomjid;
  10807. }
  10808. Recording.types = {
  10809. COLIBRI: "colibri",
  10810. JIRECON: "jirecon",
  10811. JIBRI: "jibri"
  10812. };
  10813. Recording.prototype.handleJibriPresence = function (jibri) {
  10814. var attributes = jibri.attributes;
  10815. if(!attributes)
  10816. return;
  10817. this._isSupported =
  10818. (attributes.status && attributes.status !== "undefined");
  10819. if(this._isSupported) {
  10820. this.url = attributes.url || null;
  10821. this.state = attributes.status || "off";
  10822. }
  10823. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  10824. };
  10825. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  10826. options) {
  10827. if (state == this.state){
  10828. errCallback(new Error("Invalid state!"));
  10829. }
  10830. options = options || {};
  10831. // FIXME jibri does not accept IQ without 'url' attribute set ?
  10832. var iq = $iq({to: this.focusMucJid, type: 'set'})
  10833. .c('jibri', {
  10834. "xmlns": 'http://jitsi.org/protocol/jibri',
  10835. "action": (state === 'on') ? 'start' : 'stop',
  10836. "streamid": options.streamId,
  10837. "follow-entity": options.followEntity
  10838. }).up();
  10839. logger.log('Set jibri recording: '+state, iq.nodeTree);
  10840. console.log(iq.nodeTree);
  10841. this.connection.sendIQ(
  10842. iq,
  10843. function (result) {
  10844. callback($(result).find('jibri').attr('state'),
  10845. $(result).find('jibri').attr('url'));
  10846. },
  10847. function (error) {
  10848. logger.log('Failed to start recording, error: ', error);
  10849. errCallback(error);
  10850. });
  10851. };
  10852. Recording.prototype.setRecordingJirecon =
  10853. function (state, callback, errCallback, options) {
  10854. if (state == this.state){
  10855. errCallback(new Error("Invalid state!"));
  10856. }
  10857. var iq = $iq({to: this.jirecon, type: 'set'})
  10858. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  10859. action: (state === 'on') ? 'start' : 'stop',
  10860. mucjid: this.roomjid});
  10861. if (state === 'off'){
  10862. iq.attrs({rid: this.jireconRid});
  10863. }
  10864. console.log('Start recording');
  10865. var self = this;
  10866. this.connection.sendIQ(
  10867. iq,
  10868. function (result) {
  10869. // TODO wait for an IQ with the real status, since this is
  10870. // provisional?
  10871. self.jireconRid = $(result).find('recording').attr('rid');
  10872. console.log('Recording ' +
  10873. ((state === 'on') ? 'started' : 'stopped') +
  10874. '(jirecon)' + result);
  10875. self.state = state;
  10876. if (state === 'off'){
  10877. self.jireconRid = null;
  10878. }
  10879. callback(state);
  10880. },
  10881. function (error) {
  10882. console.log('Failed to start recording, error: ', error);
  10883. errCallback(error);
  10884. });
  10885. };
  10886. // Sends a COLIBRI message which enables or disables (according to 'state')
  10887. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  10888. // with the new recording state, according to the IQ.
  10889. Recording.prototype.setRecordingColibri =
  10890. function (state, callback, errCallback, options) {
  10891. var elem = $iq({to: this.focusMucJid, type: 'set'});
  10892. elem.c('conference', {
  10893. xmlns: 'http://jitsi.org/protocol/colibri'
  10894. });
  10895. elem.c('recording', {state: state, token: options.token});
  10896. var self = this;
  10897. this.connection.sendIQ(elem,
  10898. function (result) {
  10899. console.log('Set recording "', state, '". Result:', result);
  10900. var recordingElem = $(result).find('>conference>recording');
  10901. var newState = recordingElem.attr('state');
  10902. self.state = newState;
  10903. callback(newState);
  10904. if (newState === 'pending') {
  10905. self.connection.addHandler(function(iq){
  10906. var state = $(iq).find('recording').attr('state');
  10907. if (state) {
  10908. self.state = newState;
  10909. callback(state);
  10910. }
  10911. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  10912. }
  10913. },
  10914. function (error) {
  10915. console.warn(error);
  10916. errCallback(error);
  10917. }
  10918. );
  10919. };
  10920. Recording.prototype.setRecording =
  10921. function (state, callback, errCallback, options) {
  10922. switch(this.type){
  10923. case Recording.types.JIRECON:
  10924. this.setRecordingJirecon(state, callback, errCallback, options);
  10925. break;
  10926. case Recording.types.COLIBRI:
  10927. this.setRecordingColibri(state, callback, errCallback, options);
  10928. break;
  10929. case Recording.types.JIBRI:
  10930. this.setRecordingJibri(state, callback, errCallback, options);
  10931. break;
  10932. default:
  10933. console.error("Unknown recording type!");
  10934. return;
  10935. }
  10936. };
  10937. /**
  10938. *Starts/stops the recording
  10939. * @param token token for authentication
  10940. * @param statusChangeHandler {function} receives the new status as argument.
  10941. */
  10942. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  10943. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  10944. (!options.streamId && this.type === Recording.types.JIBRI)){
  10945. statusChangeHandler("error", new Error("No token passed!"));
  10946. logger.error("No token passed!");
  10947. return;
  10948. }
  10949. var oldState = this.state;
  10950. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  10951. var self = this;
  10952. this.setRecording(newState,
  10953. function (state, url) {
  10954. logger.log("New recording state: ", state);
  10955. if (state && state !== oldState) {
  10956. self.state = state;
  10957. self.url = url;
  10958. statusChangeHandler(state);
  10959. } else {
  10960. statusChangeHandler("error", new Error("Status not changed!"));
  10961. }
  10962. }, function (error) {
  10963. statusChangeHandler("error", error);
  10964. }, options);
  10965. };
  10966. /**
  10967. * Returns true if the recording is supproted and false if not.
  10968. */
  10969. Recording.prototype.isSupported = function () {
  10970. return this._isSupported;
  10971. };
  10972. /**
  10973. * Returns null if the recording is not supported, "on" if the recording started
  10974. * and "off" if the recording is not started.
  10975. */
  10976. Recording.prototype.getState = function () {
  10977. return this.state;
  10978. };
  10979. /**
  10980. * Returns the url of the recorded video.
  10981. */
  10982. Recording.prototype.getURL = function () {
  10983. return this.url;
  10984. };
  10985. module.exports = Recording;
  10986. }).call(this,"/modules/xmpp/recording.js")
  10987. },{"../../service/xmpp/XMPPEvents":138,"jitsi-meet-logger":49}],37:[function(require,module,exports){
  10988. (function (__filename){
  10989. /* jshint -W117 */
  10990. /* a simple MUC connection plugin
  10991. * can only handle a single MUC room
  10992. */
  10993. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10994. var ChatRoom = require("./ChatRoom");
  10995. module.exports = function(XMPP) {
  10996. Strophe.addConnectionPlugin('emuc', {
  10997. connection: null,
  10998. rooms: {},//map with the rooms
  10999. init: function (conn) {
  11000. this.connection = conn;
  11001. // add handlers (just once)
  11002. this.connection.addHandler(this.onPresence.bind(this), null,
  11003. 'presence', null, null, null, null);
  11004. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  11005. null, 'presence', 'unavailable', null);
  11006. this.connection.addHandler(this.onPresenceError.bind(this), null,
  11007. 'presence', 'error', null);
  11008. this.connection.addHandler(this.onMessage.bind(this), null,
  11009. 'message', null, null);
  11010. this.connection.addHandler(this.onMute.bind(this),
  11011. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  11012. },
  11013. createRoom: function (jid, password, options, settings) {
  11014. var roomJid = Strophe.getBareJidFromJid(jid);
  11015. if (this.rooms[roomJid]) {
  11016. logger.error("You are already in the room!");
  11017. return;
  11018. }
  11019. this.rooms[roomJid] = new ChatRoom(this.connection, jid,
  11020. password, XMPP, options, settings);
  11021. return this.rooms[roomJid];
  11022. },
  11023. doLeave: function (jid) {
  11024. this.rooms[jid].doLeave();
  11025. delete this.rooms[jid];
  11026. },
  11027. onPresence: function (pres) {
  11028. var from = pres.getAttribute('from');
  11029. // What is this for? A workaround for something?
  11030. if (pres.getAttribute('type')) {
  11031. return true;
  11032. }
  11033. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11034. if(!room)
  11035. return;
  11036. // Parse status.
  11037. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  11038. room.createNonAnonymousRoom();
  11039. }
  11040. room.onPresence(pres);
  11041. return true;
  11042. },
  11043. onPresenceUnavailable: function (pres) {
  11044. var from = pres.getAttribute('from');
  11045. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11046. if(!room)
  11047. return;
  11048. room.onPresenceUnavailable(pres, from);
  11049. return true;
  11050. },
  11051. onPresenceError: function (pres) {
  11052. var from = pres.getAttribute('from');
  11053. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11054. if(!room)
  11055. return;
  11056. room.onPresenceError(pres, from);
  11057. return true;
  11058. },
  11059. onMessage: function (msg) {
  11060. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  11061. var from = msg.getAttribute('from');
  11062. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11063. if(!room)
  11064. return;
  11065. room.onMessage(msg, from);
  11066. return true;
  11067. },
  11068. setJingleSession: function (from, session) {
  11069. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11070. if(!room)
  11071. return;
  11072. room.setJingleSession(session);
  11073. },
  11074. onMute: function(iq) {
  11075. var from = iq.getAttribute('from');
  11076. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11077. if(!room)
  11078. return;
  11079. room.onMute(iq);
  11080. return true;
  11081. }
  11082. });
  11083. };
  11084. }).call(this,"/modules/xmpp/strophe.emuc.js")
  11085. },{"./ChatRoom":28,"jitsi-meet-logger":49}],38:[function(require,module,exports){
  11086. (function (__filename){
  11087. /* jshint -W117 */
  11088. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11089. var JingleSession = require("./JingleSessionPC");
  11090. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11091. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11092. module.exports = function(XMPP, eventEmitter) {
  11093. Strophe.addConnectionPlugin('jingle', {
  11094. connection: null,
  11095. sessions: {},
  11096. jid2session: {},
  11097. ice_config: {iceServers: []},
  11098. media_constraints: {
  11099. mandatory: {
  11100. 'OfferToReceiveAudio': true,
  11101. 'OfferToReceiveVideo': true
  11102. }
  11103. // MozDontOfferDataChannel: true when this is firefox
  11104. },
  11105. init: function (conn) {
  11106. this.connection = conn;
  11107. if (this.connection.disco) {
  11108. // http://xmpp.org/extensions/xep-0167.html#support
  11109. // http://xmpp.org/extensions/xep-0176.html#support
  11110. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  11111. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  11112. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  11113. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  11114. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  11115. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  11116. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  11117. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  11118. || RTCBrowserType.isTemasysPluginUsed()) {
  11119. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  11120. }
  11121. // this is dealt with by SDP O/A so we don't need to announce this
  11122. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  11123. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  11124. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  11125. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  11126. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  11127. }
  11128. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  11129. },
  11130. onJingle: function (iq) {
  11131. var sid = $(iq).find('jingle').attr('sid');
  11132. var action = $(iq).find('jingle').attr('action');
  11133. var fromJid = iq.getAttribute('from');
  11134. // send ack first
  11135. var ack = $iq({type: 'result',
  11136. to: fromJid,
  11137. id: iq.getAttribute('id')
  11138. });
  11139. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  11140. var sess = this.sessions[sid];
  11141. if ('session-initiate' != action) {
  11142. if (sess === null) {
  11143. ack.type = 'error';
  11144. ack.c('error', {type: 'cancel'})
  11145. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11146. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11147. this.connection.send(ack);
  11148. return true;
  11149. }
  11150. // local jid is not checked
  11151. if (fromJid != sess.peerjid) {
  11152. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  11153. ack.type = 'error';
  11154. ack.c('error', {type: 'cancel'})
  11155. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11156. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11157. this.connection.send(ack);
  11158. return true;
  11159. }
  11160. } else if (sess !== undefined) {
  11161. // existing session with same session id
  11162. // this might be out-of-order if the sess.peerjid is the same as from
  11163. ack.type = 'error';
  11164. ack.c('error', {type: 'cancel'})
  11165. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  11166. logger.warn('duplicate session id', sid);
  11167. this.connection.send(ack);
  11168. return true;
  11169. }
  11170. // FIXME: check for a defined action
  11171. this.connection.send(ack);
  11172. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  11173. switch (action) {
  11174. case 'session-initiate':
  11175. console.log("(TIME) received session-initiate:\t",
  11176. window.performance.now());
  11177. var startMuted = $(iq).find('jingle>startmuted');
  11178. if (startMuted && startMuted.length > 0) {
  11179. var audioMuted = startMuted.attr("audio");
  11180. var videoMuted = startMuted.attr("video");
  11181. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  11182. audioMuted === "true", videoMuted === "true");
  11183. }
  11184. sess = new JingleSession(
  11185. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  11186. this.connection, XMPP);
  11187. // configure session
  11188. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  11189. this.connection.emuc.setJingleSession(fromBareJid, sess);
  11190. sess.media_constraints = this.media_constraints;
  11191. sess.ice_config = this.ice_config;
  11192. sess.initialize(fromJid, false);
  11193. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  11194. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  11195. sess.setOffer($(iq).find('>jingle'));
  11196. this.sessions[sess.sid] = sess;
  11197. this.jid2session[sess.peerjid] = sess;
  11198. // the callback should either
  11199. // .sendAnswer and .accept
  11200. // or .sendTerminate -- not necessarily synchronous
  11201. sess.sendAnswer();
  11202. sess.accept();
  11203. break;
  11204. case 'session-accept':
  11205. sess.setAnswer($(iq).find('>jingle'));
  11206. sess.accept();
  11207. break;
  11208. case 'session-terminate':
  11209. // If this is not the focus sending the terminate, we have
  11210. // nothing more to do here.
  11211. if (Object.keys(this.sessions).length < 1
  11212. || !(this.sessions[Object.keys(this.sessions)[0]]
  11213. instanceof JingleSession))
  11214. {
  11215. break;
  11216. }
  11217. logger.log('terminating...', sess.sid);
  11218. sess.terminate();
  11219. this.terminate(sess.sid);
  11220. if ($(iq).find('>jingle>reason').length) {
  11221. $(document).trigger('callterminated.jingle', [
  11222. sess.sid,
  11223. sess.peerjid,
  11224. $(iq).find('>jingle>reason>:first')[0].tagName,
  11225. $(iq).find('>jingle>reason>text').text()
  11226. ]);
  11227. } else {
  11228. $(document).trigger('callterminated.jingle',
  11229. [sess.sid, sess.peerjid]);
  11230. }
  11231. break;
  11232. case 'transport-info':
  11233. sess.addIceCandidate($(iq).find('>jingle>content'));
  11234. break;
  11235. case 'session-info':
  11236. var affected;
  11237. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11238. $(document).trigger('ringing.jingle', [sess.sid]);
  11239. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11240. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11241. $(document).trigger('mute.jingle', [sess.sid, affected]);
  11242. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11243. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11244. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  11245. }
  11246. break;
  11247. case 'addsource': // FIXME: proprietary, un-jingleish
  11248. case 'source-add': // FIXME: proprietary
  11249. sess.addSource($(iq).find('>jingle>content'));
  11250. break;
  11251. case 'removesource': // FIXME: proprietary, un-jingleish
  11252. case 'source-remove': // FIXME: proprietary
  11253. sess.removeSource($(iq).find('>jingle>content'));
  11254. break;
  11255. default:
  11256. logger.warn('jingle action not implemented', action);
  11257. break;
  11258. }
  11259. return true;
  11260. },
  11261. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  11262. if (sid === null || sid === undefined) {
  11263. for (sid in this.sessions) {
  11264. if (this.sessions[sid].state != 'ended') {
  11265. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11266. this.sessions[sid].terminate();
  11267. }
  11268. delete this.jid2session[this.sessions[sid].peerjid];
  11269. delete this.sessions[sid];
  11270. }
  11271. } else if (this.sessions.hasOwnProperty(sid)) {
  11272. if (this.sessions[sid].state != 'ended') {
  11273. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11274. this.sessions[sid].terminate();
  11275. }
  11276. delete this.jid2session[this.sessions[sid].peerjid];
  11277. delete this.sessions[sid];
  11278. }
  11279. },
  11280. getStunAndTurnCredentials: function () {
  11281. // get stun and turn configuration from server via xep-0215
  11282. // uses time-limited credentials as described in
  11283. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  11284. //
  11285. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  11286. // for a prosody module which implements this
  11287. //
  11288. // currently, this doesn't work with updateIce and therefore credentials with a long
  11289. // validity have to be fetched before creating the peerconnection
  11290. // TODO: implement refresh via updateIce as described in
  11291. // https://code.google.com/p/webrtc/issues/detail?id=1650
  11292. var self = this;
  11293. this.connection.sendIQ(
  11294. $iq({type: 'get', to: this.connection.domain})
  11295. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  11296. function (res) {
  11297. var iceservers = [];
  11298. $(res).find('>services>service').each(function (idx, el) {
  11299. el = $(el);
  11300. var dict = {};
  11301. var type = el.attr('type');
  11302. switch (type) {
  11303. case 'stun':
  11304. dict.url = 'stun:' + el.attr('host');
  11305. if (el.attr('port')) {
  11306. dict.url += ':' + el.attr('port');
  11307. }
  11308. iceservers.push(dict);
  11309. break;
  11310. case 'turn':
  11311. case 'turns':
  11312. dict.url = type + ':';
  11313. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  11314. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  11315. dict.url += el.attr('username') + '@';
  11316. } else {
  11317. dict.username = el.attr('username'); // only works in M28
  11318. }
  11319. }
  11320. dict.url += el.attr('host');
  11321. if (el.attr('port') && el.attr('port') != '3478') {
  11322. dict.url += ':' + el.attr('port');
  11323. }
  11324. if (el.attr('transport') && el.attr('transport') != 'udp') {
  11325. dict.url += '?transport=' + el.attr('transport');
  11326. }
  11327. if (el.attr('password')) {
  11328. dict.credential = el.attr('password');
  11329. }
  11330. iceservers.push(dict);
  11331. break;
  11332. }
  11333. });
  11334. self.ice_config.iceServers = iceservers;
  11335. },
  11336. function (err) {
  11337. logger.warn('getting turn credentials failed', err);
  11338. logger.warn('is mod_turncredentials or similar installed?');
  11339. }
  11340. );
  11341. // implement push?
  11342. },
  11343. /**
  11344. * Returns the data saved in 'updateLog' in a format to be logged.
  11345. */
  11346. getLog: function () {
  11347. var data = {};
  11348. var self = this;
  11349. Object.keys(this.sessions).forEach(function (sid) {
  11350. var session = self.sessions[sid];
  11351. if (session.peerconnection && session.peerconnection.updateLog) {
  11352. // FIXME: should probably be a .dump call
  11353. data["jingle_" + session.sid] = {
  11354. updateLog: session.peerconnection.updateLog,
  11355. stats: session.peerconnection.stats,
  11356. url: window.location.href
  11357. };
  11358. }
  11359. });
  11360. return data;
  11361. }
  11362. });
  11363. };
  11364. }).call(this,"/modules/xmpp/strophe.jingle.js")
  11365. },{"../../service/xmpp/XMPPEvents":138,"../RTC/RTCBrowserType":17,"./JingleSessionPC":30,"jitsi-meet-logger":49}],39:[function(require,module,exports){
  11366. /* global Strophe */
  11367. module.exports = function () {
  11368. Strophe.addConnectionPlugin('logger', {
  11369. // logs raw stanzas and makes them available for download as JSON
  11370. connection: null,
  11371. log: [],
  11372. init: function (conn) {
  11373. this.connection = conn;
  11374. this.connection.rawInput = this.log_incoming.bind(this);
  11375. this.connection.rawOutput = this.log_outgoing.bind(this);
  11376. },
  11377. log_incoming: function (stanza) {
  11378. this.log.push([new Date().getTime(), 'incoming', stanza]);
  11379. },
  11380. log_outgoing: function (stanza) {
  11381. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  11382. }
  11383. });
  11384. };
  11385. },{}],40:[function(require,module,exports){
  11386. (function (__filename){
  11387. /* global $, $iq, Strophe */
  11388. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11389. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11390. /**
  11391. * Ping every 10 sec
  11392. */
  11393. var PING_INTERVAL = 10000;
  11394. /**
  11395. * Ping timeout error after 15 sec of waiting.
  11396. */
  11397. var PING_TIMEOUT = 15000;
  11398. /**
  11399. * Will close the connection after 3 consecutive ping errors.
  11400. */
  11401. var PING_THRESHOLD = 3;
  11402. /**
  11403. * XEP-0199 ping plugin.
  11404. *
  11405. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  11406. */
  11407. module.exports = function (XMPP, eventEmitter) {
  11408. Strophe.addConnectionPlugin('ping', {
  11409. connection: null,
  11410. failedPings: 0,
  11411. /**
  11412. * Initializes the plugin. Method called by Strophe.
  11413. * @param connection Strophe connection instance.
  11414. */
  11415. init: function (connection) {
  11416. this.connection = connection;
  11417. Strophe.addNamespace('PING', "urn:xmpp:ping");
  11418. },
  11419. /**
  11420. * Sends "ping" to given <tt>jid</tt>
  11421. * @param jid the JID to which ping request will be sent.
  11422. * @param success callback called on success.
  11423. * @param error callback called on error.
  11424. * @param timeout ms how long are we going to wait for the response. On
  11425. * timeout <tt>error<//t> callback is called with undefined error
  11426. * argument.
  11427. */
  11428. ping: function (jid, success, error, timeout) {
  11429. var iq = $iq({type: 'get', to: jid});
  11430. iq.c('ping', {xmlns: Strophe.NS.PING});
  11431. this.connection.sendIQ(iq, success, error, timeout);
  11432. },
  11433. /**
  11434. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  11435. * @param jid the JID to be checked for ping support.
  11436. * @param callback function with boolean argument which will be
  11437. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  11438. */
  11439. hasPingSupport: function (jid, callback) {
  11440. this.connection.disco.info(
  11441. jid, null,
  11442. function (result) {
  11443. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  11444. callback(ping.length > 0);
  11445. },
  11446. function (error) {
  11447. logger.error("Ping feature discovery error", error);
  11448. callback(false);
  11449. }
  11450. );
  11451. },
  11452. /**
  11453. * Starts to send ping in given interval to specified remote JID.
  11454. * This plugin supports only one such task and <tt>stopInterval</tt>
  11455. * must be called before starting a new one.
  11456. * @param remoteJid remote JID to which ping requests will be sent to.
  11457. * @param interval task interval in ms.
  11458. */
  11459. startInterval: function (remoteJid, interval) {
  11460. if (this.intervalId) {
  11461. logger.error("Ping task scheduled already");
  11462. return;
  11463. }
  11464. if (!interval)
  11465. interval = PING_INTERVAL;
  11466. var self = this;
  11467. this.intervalId = window.setInterval(function () {
  11468. self.ping(remoteJid,
  11469. function (result) {
  11470. // Ping OK
  11471. self.failedPings = 0;
  11472. },
  11473. function (error) {
  11474. self.failedPings += 1;
  11475. logger.error(
  11476. "Ping " + (error ? "error" : "timeout"), error);
  11477. if (self.failedPings >= PING_THRESHOLD) {
  11478. self.connection.disconnect();
  11479. }
  11480. }, PING_TIMEOUT);
  11481. }, interval);
  11482. logger.info("XMPP pings will be sent every " + interval + " ms");
  11483. },
  11484. /**
  11485. * Stops current "ping" interval task.
  11486. */
  11487. stopInterval: function () {
  11488. if (this.intervalId) {
  11489. window.clearInterval(this.intervalId);
  11490. this.intervalId = null;
  11491. this.failedPings = 0;
  11492. logger.info("Ping interval cleared");
  11493. }
  11494. }
  11495. });
  11496. };
  11497. }).call(this,"/modules/xmpp/strophe.ping.js")
  11498. },{"../../service/xmpp/XMPPEvents":138,"jitsi-meet-logger":49}],41:[function(require,module,exports){
  11499. (function (__filename){
  11500. /* jshint -W117 */
  11501. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11502. module.exports = function() {
  11503. Strophe.addConnectionPlugin('rayo',
  11504. {
  11505. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  11506. connection: null,
  11507. init: function (conn) {
  11508. this.connection = conn;
  11509. if (this.connection.disco) {
  11510. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  11511. }
  11512. this.connection.addHandler(
  11513. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  11514. null, null);
  11515. },
  11516. onRayo: function (iq) {
  11517. logger.info("Rayo IQ", iq);
  11518. },
  11519. dial: function (to, from, roomName, roomPass, focusMucJid) {
  11520. var self = this;
  11521. return new Promise(function (resolve, reject) {
  11522. if(!focusMucJid) {
  11523. reject(new Error("Internal error!"));
  11524. return;
  11525. }
  11526. var req = $iq(
  11527. {
  11528. type: 'set',
  11529. to: focusMucJid
  11530. }
  11531. );
  11532. req.c('dial',
  11533. {
  11534. xmlns: self.RAYO_XMLNS,
  11535. to: to,
  11536. from: from
  11537. });
  11538. req.c('header',
  11539. {
  11540. name: 'JvbRoomName',
  11541. value: roomName
  11542. }).up();
  11543. if (roomPass !== null && roomPass.length) {
  11544. req.c('header',
  11545. {
  11546. name: 'JvbRoomPassword',
  11547. value: roomPass
  11548. }).up();
  11549. }
  11550. self.connection.sendIQ(
  11551. req,
  11552. function (result) {
  11553. logger.info('Dial result ', result);
  11554. var resource = $(result).find('ref').attr('uri');
  11555. self.call_resource =
  11556. resource.substr('xmpp:'.length);
  11557. logger.info(
  11558. "Received call resource: " +
  11559. self.call_resource);
  11560. resolve();
  11561. },
  11562. function (error) {
  11563. logger.info('Dial error ', error);
  11564. reject(error);
  11565. }
  11566. );
  11567. });
  11568. },
  11569. hangup: function () {
  11570. var self = this;
  11571. return new Promise(function (resolve, reject) {
  11572. if (!self.call_resource) {
  11573. reject(new Error("No call in progress"));
  11574. logger.warn("No call in progress");
  11575. return;
  11576. }
  11577. var req = $iq(
  11578. {
  11579. type: 'set',
  11580. to: self.call_resource
  11581. }
  11582. );
  11583. req.c('hangup',
  11584. {
  11585. xmlns: self.RAYO_XMLNS
  11586. });
  11587. self.connection.sendIQ(
  11588. req,
  11589. function (result) {
  11590. logger.info('Hangup result ', result);
  11591. self.call_resource = null;
  11592. resolve();
  11593. },
  11594. function (error) {
  11595. logger.info('Hangup error ', error);
  11596. self.call_resource = null;
  11597. reject(new Error('Hangup error '));
  11598. }
  11599. );
  11600. });
  11601. }
  11602. }
  11603. );
  11604. };
  11605. }).call(this,"/modules/xmpp/strophe.rayo.js")
  11606. },{"jitsi-meet-logger":49}],42:[function(require,module,exports){
  11607. (function (__filename){
  11608. /* global Strophe */
  11609. /**
  11610. * Strophe logger implementation. Logs from level WARN and above.
  11611. */
  11612. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11613. module.exports = function () {
  11614. Strophe.log = function (level, msg) {
  11615. switch (level) {
  11616. case Strophe.LogLevel.WARN:
  11617. logger.warn("Strophe: " + msg);
  11618. break;
  11619. case Strophe.LogLevel.ERROR:
  11620. case Strophe.LogLevel.FATAL:
  11621. logger.error("Strophe: " + msg);
  11622. break;
  11623. }
  11624. };
  11625. Strophe.getStatusString = function (status) {
  11626. switch (status) {
  11627. case Strophe.Status.ERROR:
  11628. return "ERROR";
  11629. case Strophe.Status.CONNECTING:
  11630. return "CONNECTING";
  11631. case Strophe.Status.CONNFAIL:
  11632. return "CONNFAIL";
  11633. case Strophe.Status.AUTHENTICATING:
  11634. return "AUTHENTICATING";
  11635. case Strophe.Status.AUTHFAIL:
  11636. return "AUTHFAIL";
  11637. case Strophe.Status.CONNECTED:
  11638. return "CONNECTED";
  11639. case Strophe.Status.DISCONNECTED:
  11640. return "DISCONNECTED";
  11641. case Strophe.Status.DISCONNECTING:
  11642. return "DISCONNECTING";
  11643. case Strophe.Status.ATTACHED:
  11644. return "ATTACHED";
  11645. default:
  11646. return "unknown";
  11647. }
  11648. };
  11649. };
  11650. }).call(this,"/modules/xmpp/strophe.util.js")
  11651. },{"jitsi-meet-logger":49}],43:[function(require,module,exports){
  11652. (function (__filename){
  11653. /* global $, APP, config, Strophe*/
  11654. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11655. var EventEmitter = require("events");
  11656. var Pako = require("pako");
  11657. var RTCEvents = require("../../service/RTC/RTCEvents");
  11658. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11659. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  11660. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  11661. var RTC = require("../RTC/RTC");
  11662. var authenticatedUser = false;
  11663. function createConnection(bosh) {
  11664. bosh = bosh || '/http-bind';
  11665. // Append token as URL param
  11666. if (this.token) {
  11667. bosh += bosh.indexOf('?') == -1 ?
  11668. '?token=' + this.token : '&token=' + this.token;
  11669. }
  11670. return new Strophe.Connection(bosh);
  11671. };
  11672. //!!!!!!!!!! FIXME: ...
  11673. function initStrophePlugins(XMPP)
  11674. {
  11675. require("./strophe.emuc")(XMPP);
  11676. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  11677. // require("./strophe.moderate")(XMPP, eventEmitter);
  11678. require("./strophe.util")();
  11679. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  11680. require("./strophe.rayo")();
  11681. require("./strophe.logger")();
  11682. }
  11683. //!!!!!!!!!! FIXME: ...
  11684. ///**
  11685. // * If given <tt>localStream</tt> is video one this method will advertise it's
  11686. // * video type in MUC presence.
  11687. // * @param localStream new or modified <tt>LocalStream</tt>.
  11688. // */
  11689. //function broadcastLocalVideoType(localStream) {
  11690. // if (localStream.videoType)
  11691. // XMPP.addToPresence('videoType', localStream.videoType);
  11692. //}
  11693. //
  11694. //function registerListeners() {
  11695. // RTC.addStreamListener(
  11696. // broadcastLocalVideoType,
  11697. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  11698. // );
  11699. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  11700. // XMPP.addToPresence("devices", devices);
  11701. // });
  11702. //}
  11703. function XMPP(options) {
  11704. this.eventEmitter = new EventEmitter();
  11705. this.connection = null;
  11706. this.disconnectInProgress = false;
  11707. this.forceMuted = false;
  11708. this.options = options;
  11709. initStrophePlugins(this);
  11710. // registerListeners();
  11711. this.connection = createConnection(options.bosh);
  11712. }
  11713. XMPP.prototype.getConnection = function(){ return connection; };
  11714. XMPP.prototype._connect = function (jid, password) {
  11715. var self = this;
  11716. // connection.connect() starts the connection process.
  11717. //
  11718. // As the connection process proceeds, the user supplied callback will
  11719. // be triggered multiple times with status updates. The callback should
  11720. // take two arguments - the status code and the error condition.
  11721. //
  11722. // The status code will be one of the values in the Strophe.Status
  11723. // constants. The error condition will be one of the conditions defined
  11724. // in RFC 3920 or the condition ‘strophe-parsererror’.
  11725. //
  11726. // The Parameters wait, hold and route are optional and only relevant
  11727. // for BOSH connections. Please see XEP 124 for a more detailed
  11728. // explanation of the optional parameters.
  11729. //
  11730. // Connection status constants for use by the connection handler
  11731. // callback.
  11732. //
  11733. // Status.ERROR - An error has occurred (websockets specific)
  11734. // Status.CONNECTING - The connection is currently being made
  11735. // Status.CONNFAIL - The connection attempt failed
  11736. // Status.AUTHENTICATING - The connection is authenticating
  11737. // Status.AUTHFAIL - The authentication attempt failed
  11738. // Status.CONNECTED - The connection has succeeded
  11739. // Status.DISCONNECTED - The connection has been terminated
  11740. // Status.DISCONNECTING - The connection is currently being terminated
  11741. // Status.ATTACHED - The connection has been attached
  11742. var anonymousConnectionFailed = false;
  11743. var connectionFailed = false;
  11744. var lastErrorMsg;
  11745. this.connection.connect(jid, password, function (status, msg) {
  11746. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  11747. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  11748. if (status === Strophe.Status.CONNECTED) {
  11749. if (self.options.useStunTurn) {
  11750. self.connection.jingle.getStunAndTurnCredentials();
  11751. }
  11752. logger.info("My Jabber ID: " + self.connection.jid);
  11753. // Schedule ping ?
  11754. var pingJid = self.connection.domain;
  11755. self.connection.ping.hasPingSupport(
  11756. pingJid,
  11757. function (hasPing) {
  11758. if (hasPing)
  11759. self.connection.ping.startInterval(pingJid);
  11760. else
  11761. logger.warn("Ping NOT supported by " + pingJid);
  11762. }
  11763. );
  11764. if (password)
  11765. authenticatedUser = true;
  11766. if (self.connection && self.connection.connected &&
  11767. Strophe.getResourceFromJid(self.connection.jid)) {
  11768. // .connected is true while connecting?
  11769. // self.connection.send($pres());
  11770. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  11771. Strophe.getResourceFromJid(self.connection.jid));
  11772. }
  11773. } else if (status === Strophe.Status.CONNFAIL) {
  11774. if (msg === 'x-strophe-bad-non-anon-jid') {
  11775. anonymousConnectionFailed = true;
  11776. }
  11777. else
  11778. {
  11779. connectionFailed = true;
  11780. }
  11781. lastErrorMsg = msg;
  11782. } else if (status === Strophe.Status.DISCONNECTED) {
  11783. // Stop ping interval
  11784. self.connection.ping.stopInterval();
  11785. self.disconnectInProgress = false;
  11786. if (anonymousConnectionFailed) {
  11787. // prompt user for username and password
  11788. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11789. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11790. } else if(connectionFailed) {
  11791. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11792. JitsiConnectionErrors.OTHER_ERROR,
  11793. msg ? msg : lastErrorMsg);
  11794. } else {
  11795. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  11796. msg ? msg : lastErrorMsg);
  11797. }
  11798. } else if (status === Strophe.Status.AUTHFAIL) {
  11799. // wrong password or username, prompt user
  11800. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11801. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11802. }
  11803. });
  11804. }
  11805. XMPP.prototype.connect = function (jid, password) {
  11806. if(!jid) {
  11807. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  11808. // Force authenticated domain if room is appended with '?login=true'
  11809. if (this.options.hosts.anonymousdomain &&
  11810. window.location.search.indexOf("login=true") !== -1) {
  11811. configDomain = this.options.hosts.domain;
  11812. }
  11813. jid = configDomain || window.location.hostname;
  11814. }
  11815. return this._connect(jid, password);
  11816. };
  11817. XMPP.prototype.createRoom = function (roomName, options, settings) {
  11818. var roomjid = roomName + '@' + this.options.hosts.muc;
  11819. if (options.useNicks) {
  11820. if (options.nick) {
  11821. roomjid += '/' + options.nick;
  11822. } else {
  11823. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  11824. }
  11825. } else {
  11826. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  11827. if(!authenticatedUser)
  11828. tmpJid = tmpJid.substr(0, 8);
  11829. roomjid += '/' + tmpJid;
  11830. }
  11831. return this.connection.emuc.createRoom(roomjid, null, options, settings);
  11832. }
  11833. XMPP.prototype.addListener = function(type, listener) {
  11834. this.eventEmitter.on(type, listener);
  11835. };
  11836. XMPP.prototype.removeListener = function (type, listener) {
  11837. this.eventEmitter.removeListener(type, listener);
  11838. };
  11839. //FIXME: this should work with the room
  11840. XMPP.prototype.leaveRoom = function (jid) {
  11841. var handler = this.connection.jingle.jid2session[jid];
  11842. if (handler && handler.peerconnection) {
  11843. // FIXME: probably removing streams is not required and close() should
  11844. // be enough
  11845. if (RTC.localAudio) {
  11846. handler.peerconnection.removeStream(
  11847. RTC.localAudio.getOriginalStream(), true);
  11848. }
  11849. if (RTC.localVideo) {
  11850. handler.peerconnection.removeStream(
  11851. RTC.localVideo.getOriginalStream(), true);
  11852. }
  11853. handler.peerconnection.close();
  11854. }
  11855. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  11856. this.connection.emuc.doLeave(jid);
  11857. };
  11858. /**
  11859. * Sends 'data' as a log message to the focus. Returns true iff a message
  11860. * was sent.
  11861. * @param data
  11862. * @returns {boolean} true iff a message was sent.
  11863. */
  11864. XMPP.prototype.sendLogs = function (data) {
  11865. if(!this.connection.emuc.focusMucJid)
  11866. return false;
  11867. var deflate = true;
  11868. var content = JSON.stringify(data);
  11869. if (deflate) {
  11870. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  11871. }
  11872. content = Base64.encode(content);
  11873. // XEP-0337-ish
  11874. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  11875. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  11876. id: 'PeerConnectionStats'});
  11877. message.c('message').t(content).up();
  11878. if (deflate) {
  11879. message.c('tag', {name: "deflated", value: "true"}).up();
  11880. }
  11881. message.up();
  11882. this.connection.send(message);
  11883. return true;
  11884. };
  11885. // Gets the logs from strophe.jingle.
  11886. XMPP.prototype.getJingleLog = function () {
  11887. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  11888. };
  11889. // Gets the logs from strophe.
  11890. XMPP.prototype.getXmppLog = function () {
  11891. return this.connection.logger ? this.connection.logger.log : null;
  11892. };
  11893. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  11894. this.connection.rayo.dial(to, from, roomName,roomPass);
  11895. };
  11896. XMPP.prototype.setMute = function (jid, mute) {
  11897. this.connection.moderate.setMute(jid, mute);
  11898. };
  11899. XMPP.prototype.eject = function (jid) {
  11900. this.connection.moderate.eject(jid);
  11901. };
  11902. XMPP.prototype.getSessions = function () {
  11903. return this.connection.jingle.sessions;
  11904. };
  11905. XMPP.prototype.disconnect = function () {
  11906. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  11907. {
  11908. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  11909. return;
  11910. }
  11911. this.disconnectInProgress = true;
  11912. this.connection.disconnect();
  11913. };
  11914. module.exports = XMPP;
  11915. }).call(this,"/modules/xmpp/xmpp.js")
  11916. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":132,"../../service/xmpp/XMPPEvents":138,"../RTC/RTC":16,"./strophe.emuc":37,"./strophe.jingle":38,"./strophe.logger":39,"./strophe.ping":40,"./strophe.rayo":41,"./strophe.util":42,"events":45,"jitsi-meet-logger":49,"pako":51}],44:[function(require,module,exports){
  11917. (function (process){
  11918. /*!
  11919. * async
  11920. * https://github.com/caolan/async
  11921. *
  11922. * Copyright 2010-2014 Caolan McMahon
  11923. * Released under the MIT license
  11924. */
  11925. /*jshint onevar: false, indent:4 */
  11926. /*global setImmediate: false, setTimeout: false, console: false */
  11927. (function () {
  11928. var async = {};
  11929. // global on the server, window in the browser
  11930. var root, previous_async;
  11931. root = this;
  11932. if (root != null) {
  11933. previous_async = root.async;
  11934. }
  11935. async.noConflict = function () {
  11936. root.async = previous_async;
  11937. return async;
  11938. };
  11939. function only_once(fn) {
  11940. var called = false;
  11941. return function() {
  11942. if (called) throw new Error("Callback was already called.");
  11943. called = true;
  11944. fn.apply(root, arguments);
  11945. }
  11946. }
  11947. //// cross-browser compatiblity functions ////
  11948. var _toString = Object.prototype.toString;
  11949. var _isArray = Array.isArray || function (obj) {
  11950. return _toString.call(obj) === '[object Array]';
  11951. };
  11952. var _each = function (arr, iterator) {
  11953. if (arr.forEach) {
  11954. return arr.forEach(iterator);
  11955. }
  11956. for (var i = 0; i < arr.length; i += 1) {
  11957. iterator(arr[i], i, arr);
  11958. }
  11959. };
  11960. var _map = function (arr, iterator) {
  11961. if (arr.map) {
  11962. return arr.map(iterator);
  11963. }
  11964. var results = [];
  11965. _each(arr, function (x, i, a) {
  11966. results.push(iterator(x, i, a));
  11967. });
  11968. return results;
  11969. };
  11970. var _reduce = function (arr, iterator, memo) {
  11971. if (arr.reduce) {
  11972. return arr.reduce(iterator, memo);
  11973. }
  11974. _each(arr, function (x, i, a) {
  11975. memo = iterator(memo, x, i, a);
  11976. });
  11977. return memo;
  11978. };
  11979. var _keys = function (obj) {
  11980. if (Object.keys) {
  11981. return Object.keys(obj);
  11982. }
  11983. var keys = [];
  11984. for (var k in obj) {
  11985. if (obj.hasOwnProperty(k)) {
  11986. keys.push(k);
  11987. }
  11988. }
  11989. return keys;
  11990. };
  11991. //// exported async module functions ////
  11992. //// nextTick implementation with browser-compatible fallback ////
  11993. if (typeof process === 'undefined' || !(process.nextTick)) {
  11994. if (typeof setImmediate === 'function') {
  11995. async.nextTick = function (fn) {
  11996. // not a direct alias for IE10 compatibility
  11997. setImmediate(fn);
  11998. };
  11999. async.setImmediate = async.nextTick;
  12000. }
  12001. else {
  12002. async.nextTick = function (fn) {
  12003. setTimeout(fn, 0);
  12004. };
  12005. async.setImmediate = async.nextTick;
  12006. }
  12007. }
  12008. else {
  12009. async.nextTick = process.nextTick;
  12010. if (typeof setImmediate !== 'undefined') {
  12011. async.setImmediate = function (fn) {
  12012. // not a direct alias for IE10 compatibility
  12013. setImmediate(fn);
  12014. };
  12015. }
  12016. else {
  12017. async.setImmediate = async.nextTick;
  12018. }
  12019. }
  12020. async.each = function (arr, iterator, callback) {
  12021. callback = callback || function () {};
  12022. if (!arr.length) {
  12023. return callback();
  12024. }
  12025. var completed = 0;
  12026. _each(arr, function (x) {
  12027. iterator(x, only_once(done) );
  12028. });
  12029. function done(err) {
  12030. if (err) {
  12031. callback(err);
  12032. callback = function () {};
  12033. }
  12034. else {
  12035. completed += 1;
  12036. if (completed >= arr.length) {
  12037. callback();
  12038. }
  12039. }
  12040. }
  12041. };
  12042. async.forEach = async.each;
  12043. async.eachSeries = function (arr, iterator, callback) {
  12044. callback = callback || function () {};
  12045. if (!arr.length) {
  12046. return callback();
  12047. }
  12048. var completed = 0;
  12049. var iterate = function () {
  12050. iterator(arr[completed], function (err) {
  12051. if (err) {
  12052. callback(err);
  12053. callback = function () {};
  12054. }
  12055. else {
  12056. completed += 1;
  12057. if (completed >= arr.length) {
  12058. callback();
  12059. }
  12060. else {
  12061. iterate();
  12062. }
  12063. }
  12064. });
  12065. };
  12066. iterate();
  12067. };
  12068. async.forEachSeries = async.eachSeries;
  12069. async.eachLimit = function (arr, limit, iterator, callback) {
  12070. var fn = _eachLimit(limit);
  12071. fn.apply(null, [arr, iterator, callback]);
  12072. };
  12073. async.forEachLimit = async.eachLimit;
  12074. var _eachLimit = function (limit) {
  12075. return function (arr, iterator, callback) {
  12076. callback = callback || function () {};
  12077. if (!arr.length || limit <= 0) {
  12078. return callback();
  12079. }
  12080. var completed = 0;
  12081. var started = 0;
  12082. var running = 0;
  12083. (function replenish () {
  12084. if (completed >= arr.length) {
  12085. return callback();
  12086. }
  12087. while (running < limit && started < arr.length) {
  12088. started += 1;
  12089. running += 1;
  12090. iterator(arr[started - 1], function (err) {
  12091. if (err) {
  12092. callback(err);
  12093. callback = function () {};
  12094. }
  12095. else {
  12096. completed += 1;
  12097. running -= 1;
  12098. if (completed >= arr.length) {
  12099. callback();
  12100. }
  12101. else {
  12102. replenish();
  12103. }
  12104. }
  12105. });
  12106. }
  12107. })();
  12108. };
  12109. };
  12110. var doParallel = function (fn) {
  12111. return function () {
  12112. var args = Array.prototype.slice.call(arguments);
  12113. return fn.apply(null, [async.each].concat(args));
  12114. };
  12115. };
  12116. var doParallelLimit = function(limit, fn) {
  12117. return function () {
  12118. var args = Array.prototype.slice.call(arguments);
  12119. return fn.apply(null, [_eachLimit(limit)].concat(args));
  12120. };
  12121. };
  12122. var doSeries = function (fn) {
  12123. return function () {
  12124. var args = Array.prototype.slice.call(arguments);
  12125. return fn.apply(null, [async.eachSeries].concat(args));
  12126. };
  12127. };
  12128. var _asyncMap = function (eachfn, arr, iterator, callback) {
  12129. arr = _map(arr, function (x, i) {
  12130. return {index: i, value: x};
  12131. });
  12132. if (!callback) {
  12133. eachfn(arr, function (x, callback) {
  12134. iterator(x.value, function (err) {
  12135. callback(err);
  12136. });
  12137. });
  12138. } else {
  12139. var results = [];
  12140. eachfn(arr, function (x, callback) {
  12141. iterator(x.value, function (err, v) {
  12142. results[x.index] = v;
  12143. callback(err);
  12144. });
  12145. }, function (err) {
  12146. callback(err, results);
  12147. });
  12148. }
  12149. };
  12150. async.map = doParallel(_asyncMap);
  12151. async.mapSeries = doSeries(_asyncMap);
  12152. async.mapLimit = function (arr, limit, iterator, callback) {
  12153. return _mapLimit(limit)(arr, iterator, callback);
  12154. };
  12155. var _mapLimit = function(limit) {
  12156. return doParallelLimit(limit, _asyncMap);
  12157. };
  12158. // reduce only has a series version, as doing reduce in parallel won't
  12159. // work in many situations.
  12160. async.reduce = function (arr, memo, iterator, callback) {
  12161. async.eachSeries(arr, function (x, callback) {
  12162. iterator(memo, x, function (err, v) {
  12163. memo = v;
  12164. callback(err);
  12165. });
  12166. }, function (err) {
  12167. callback(err, memo);
  12168. });
  12169. };
  12170. // inject alias
  12171. async.inject = async.reduce;
  12172. // foldl alias
  12173. async.foldl = async.reduce;
  12174. async.reduceRight = function (arr, memo, iterator, callback) {
  12175. var reversed = _map(arr, function (x) {
  12176. return x;
  12177. }).reverse();
  12178. async.reduce(reversed, memo, iterator, callback);
  12179. };
  12180. // foldr alias
  12181. async.foldr = async.reduceRight;
  12182. var _filter = function (eachfn, arr, iterator, callback) {
  12183. var results = [];
  12184. arr = _map(arr, function (x, i) {
  12185. return {index: i, value: x};
  12186. });
  12187. eachfn(arr, function (x, callback) {
  12188. iterator(x.value, function (v) {
  12189. if (v) {
  12190. results.push(x);
  12191. }
  12192. callback();
  12193. });
  12194. }, function (err) {
  12195. callback(_map(results.sort(function (a, b) {
  12196. return a.index - b.index;
  12197. }), function (x) {
  12198. return x.value;
  12199. }));
  12200. });
  12201. };
  12202. async.filter = doParallel(_filter);
  12203. async.filterSeries = doSeries(_filter);
  12204. // select alias
  12205. async.select = async.filter;
  12206. async.selectSeries = async.filterSeries;
  12207. var _reject = function (eachfn, arr, iterator, callback) {
  12208. var results = [];
  12209. arr = _map(arr, function (x, i) {
  12210. return {index: i, value: x};
  12211. });
  12212. eachfn(arr, function (x, callback) {
  12213. iterator(x.value, function (v) {
  12214. if (!v) {
  12215. results.push(x);
  12216. }
  12217. callback();
  12218. });
  12219. }, function (err) {
  12220. callback(_map(results.sort(function (a, b) {
  12221. return a.index - b.index;
  12222. }), function (x) {
  12223. return x.value;
  12224. }));
  12225. });
  12226. };
  12227. async.reject = doParallel(_reject);
  12228. async.rejectSeries = doSeries(_reject);
  12229. var _detect = function (eachfn, arr, iterator, main_callback) {
  12230. eachfn(arr, function (x, callback) {
  12231. iterator(x, function (result) {
  12232. if (result) {
  12233. main_callback(x);
  12234. main_callback = function () {};
  12235. }
  12236. else {
  12237. callback();
  12238. }
  12239. });
  12240. }, function (err) {
  12241. main_callback();
  12242. });
  12243. };
  12244. async.detect = doParallel(_detect);
  12245. async.detectSeries = doSeries(_detect);
  12246. async.some = function (arr, iterator, main_callback) {
  12247. async.each(arr, function (x, callback) {
  12248. iterator(x, function (v) {
  12249. if (v) {
  12250. main_callback(true);
  12251. main_callback = function () {};
  12252. }
  12253. callback();
  12254. });
  12255. }, function (err) {
  12256. main_callback(false);
  12257. });
  12258. };
  12259. // any alias
  12260. async.any = async.some;
  12261. async.every = function (arr, iterator, main_callback) {
  12262. async.each(arr, function (x, callback) {
  12263. iterator(x, function (v) {
  12264. if (!v) {
  12265. main_callback(false);
  12266. main_callback = function () {};
  12267. }
  12268. callback();
  12269. });
  12270. }, function (err) {
  12271. main_callback(true);
  12272. });
  12273. };
  12274. // all alias
  12275. async.all = async.every;
  12276. async.sortBy = function (arr, iterator, callback) {
  12277. async.map(arr, function (x, callback) {
  12278. iterator(x, function (err, criteria) {
  12279. if (err) {
  12280. callback(err);
  12281. }
  12282. else {
  12283. callback(null, {value: x, criteria: criteria});
  12284. }
  12285. });
  12286. }, function (err, results) {
  12287. if (err) {
  12288. return callback(err);
  12289. }
  12290. else {
  12291. var fn = function (left, right) {
  12292. var a = left.criteria, b = right.criteria;
  12293. return a < b ? -1 : a > b ? 1 : 0;
  12294. };
  12295. callback(null, _map(results.sort(fn), function (x) {
  12296. return x.value;
  12297. }));
  12298. }
  12299. });
  12300. };
  12301. async.auto = function (tasks, callback) {
  12302. callback = callback || function () {};
  12303. var keys = _keys(tasks);
  12304. var remainingTasks = keys.length
  12305. if (!remainingTasks) {
  12306. return callback();
  12307. }
  12308. var results = {};
  12309. var listeners = [];
  12310. var addListener = function (fn) {
  12311. listeners.unshift(fn);
  12312. };
  12313. var removeListener = function (fn) {
  12314. for (var i = 0; i < listeners.length; i += 1) {
  12315. if (listeners[i] === fn) {
  12316. listeners.splice(i, 1);
  12317. return;
  12318. }
  12319. }
  12320. };
  12321. var taskComplete = function () {
  12322. remainingTasks--
  12323. _each(listeners.slice(0), function (fn) {
  12324. fn();
  12325. });
  12326. };
  12327. addListener(function () {
  12328. if (!remainingTasks) {
  12329. var theCallback = callback;
  12330. // prevent final callback from calling itself if it errors
  12331. callback = function () {};
  12332. theCallback(null, results);
  12333. }
  12334. });
  12335. _each(keys, function (k) {
  12336. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  12337. var taskCallback = function (err) {
  12338. var args = Array.prototype.slice.call(arguments, 1);
  12339. if (args.length <= 1) {
  12340. args = args[0];
  12341. }
  12342. if (err) {
  12343. var safeResults = {};
  12344. _each(_keys(results), function(rkey) {
  12345. safeResults[rkey] = results[rkey];
  12346. });
  12347. safeResults[k] = args;
  12348. callback(err, safeResults);
  12349. // stop subsequent errors hitting callback multiple times
  12350. callback = function () {};
  12351. }
  12352. else {
  12353. results[k] = args;
  12354. async.setImmediate(taskComplete);
  12355. }
  12356. };
  12357. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  12358. var ready = function () {
  12359. return _reduce(requires, function (a, x) {
  12360. return (a && results.hasOwnProperty(x));
  12361. }, true) && !results.hasOwnProperty(k);
  12362. };
  12363. if (ready()) {
  12364. task[task.length - 1](taskCallback, results);
  12365. }
  12366. else {
  12367. var listener = function () {
  12368. if (ready()) {
  12369. removeListener(listener);
  12370. task[task.length - 1](taskCallback, results);
  12371. }
  12372. };
  12373. addListener(listener);
  12374. }
  12375. });
  12376. };
  12377. async.retry = function(times, task, callback) {
  12378. var DEFAULT_TIMES = 5;
  12379. var attempts = [];
  12380. // Use defaults if times not passed
  12381. if (typeof times === 'function') {
  12382. callback = task;
  12383. task = times;
  12384. times = DEFAULT_TIMES;
  12385. }
  12386. // Make sure times is a number
  12387. times = parseInt(times, 10) || DEFAULT_TIMES;
  12388. var wrappedTask = function(wrappedCallback, wrappedResults) {
  12389. var retryAttempt = function(task, finalAttempt) {
  12390. return function(seriesCallback) {
  12391. task(function(err, result){
  12392. seriesCallback(!err || finalAttempt, {err: err, result: result});
  12393. }, wrappedResults);
  12394. };
  12395. };
  12396. while (times) {
  12397. attempts.push(retryAttempt(task, !(times-=1)));
  12398. }
  12399. async.series(attempts, function(done, data){
  12400. data = data[data.length - 1];
  12401. (wrappedCallback || callback)(data.err, data.result);
  12402. });
  12403. }
  12404. // If a callback is passed, run this as a controll flow
  12405. return callback ? wrappedTask() : wrappedTask
  12406. };
  12407. async.waterfall = function (tasks, callback) {
  12408. callback = callback || function () {};
  12409. if (!_isArray(tasks)) {
  12410. var err = new Error('First argument to waterfall must be an array of functions');
  12411. return callback(err);
  12412. }
  12413. if (!tasks.length) {
  12414. return callback();
  12415. }
  12416. var wrapIterator = function (iterator) {
  12417. return function (err) {
  12418. if (err) {
  12419. callback.apply(null, arguments);
  12420. callback = function () {};
  12421. }
  12422. else {
  12423. var args = Array.prototype.slice.call(arguments, 1);
  12424. var next = iterator.next();
  12425. if (next) {
  12426. args.push(wrapIterator(next));
  12427. }
  12428. else {
  12429. args.push(callback);
  12430. }
  12431. async.setImmediate(function () {
  12432. iterator.apply(null, args);
  12433. });
  12434. }
  12435. };
  12436. };
  12437. wrapIterator(async.iterator(tasks))();
  12438. };
  12439. var _parallel = function(eachfn, tasks, callback) {
  12440. callback = callback || function () {};
  12441. if (_isArray(tasks)) {
  12442. eachfn.map(tasks, function (fn, callback) {
  12443. if (fn) {
  12444. fn(function (err) {
  12445. var args = Array.prototype.slice.call(arguments, 1);
  12446. if (args.length <= 1) {
  12447. args = args[0];
  12448. }
  12449. callback.call(null, err, args);
  12450. });
  12451. }
  12452. }, callback);
  12453. }
  12454. else {
  12455. var results = {};
  12456. eachfn.each(_keys(tasks), function (k, callback) {
  12457. tasks[k](function (err) {
  12458. var args = Array.prototype.slice.call(arguments, 1);
  12459. if (args.length <= 1) {
  12460. args = args[0];
  12461. }
  12462. results[k] = args;
  12463. callback(err);
  12464. });
  12465. }, function (err) {
  12466. callback(err, results);
  12467. });
  12468. }
  12469. };
  12470. async.parallel = function (tasks, callback) {
  12471. _parallel({ map: async.map, each: async.each }, tasks, callback);
  12472. };
  12473. async.parallelLimit = function(tasks, limit, callback) {
  12474. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  12475. };
  12476. async.series = function (tasks, callback) {
  12477. callback = callback || function () {};
  12478. if (_isArray(tasks)) {
  12479. async.mapSeries(tasks, function (fn, callback) {
  12480. if (fn) {
  12481. fn(function (err) {
  12482. var args = Array.prototype.slice.call(arguments, 1);
  12483. if (args.length <= 1) {
  12484. args = args[0];
  12485. }
  12486. callback.call(null, err, args);
  12487. });
  12488. }
  12489. }, callback);
  12490. }
  12491. else {
  12492. var results = {};
  12493. async.eachSeries(_keys(tasks), function (k, callback) {
  12494. tasks[k](function (err) {
  12495. var args = Array.prototype.slice.call(arguments, 1);
  12496. if (args.length <= 1) {
  12497. args = args[0];
  12498. }
  12499. results[k] = args;
  12500. callback(err);
  12501. });
  12502. }, function (err) {
  12503. callback(err, results);
  12504. });
  12505. }
  12506. };
  12507. async.iterator = function (tasks) {
  12508. var makeCallback = function (index) {
  12509. var fn = function () {
  12510. if (tasks.length) {
  12511. tasks[index].apply(null, arguments);
  12512. }
  12513. return fn.next();
  12514. };
  12515. fn.next = function () {
  12516. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  12517. };
  12518. return fn;
  12519. };
  12520. return makeCallback(0);
  12521. };
  12522. async.apply = function (fn) {
  12523. var args = Array.prototype.slice.call(arguments, 1);
  12524. return function () {
  12525. return fn.apply(
  12526. null, args.concat(Array.prototype.slice.call(arguments))
  12527. );
  12528. };
  12529. };
  12530. var _concat = function (eachfn, arr, fn, callback) {
  12531. var r = [];
  12532. eachfn(arr, function (x, cb) {
  12533. fn(x, function (err, y) {
  12534. r = r.concat(y || []);
  12535. cb(err);
  12536. });
  12537. }, function (err) {
  12538. callback(err, r);
  12539. });
  12540. };
  12541. async.concat = doParallel(_concat);
  12542. async.concatSeries = doSeries(_concat);
  12543. async.whilst = function (test, iterator, callback) {
  12544. if (test()) {
  12545. iterator(function (err) {
  12546. if (err) {
  12547. return callback(err);
  12548. }
  12549. async.whilst(test, iterator, callback);
  12550. });
  12551. }
  12552. else {
  12553. callback();
  12554. }
  12555. };
  12556. async.doWhilst = function (iterator, test, callback) {
  12557. iterator(function (err) {
  12558. if (err) {
  12559. return callback(err);
  12560. }
  12561. var args = Array.prototype.slice.call(arguments, 1);
  12562. if (test.apply(null, args)) {
  12563. async.doWhilst(iterator, test, callback);
  12564. }
  12565. else {
  12566. callback();
  12567. }
  12568. });
  12569. };
  12570. async.until = function (test, iterator, callback) {
  12571. if (!test()) {
  12572. iterator(function (err) {
  12573. if (err) {
  12574. return callback(err);
  12575. }
  12576. async.until(test, iterator, callback);
  12577. });
  12578. }
  12579. else {
  12580. callback();
  12581. }
  12582. };
  12583. async.doUntil = function (iterator, test, callback) {
  12584. iterator(function (err) {
  12585. if (err) {
  12586. return callback(err);
  12587. }
  12588. var args = Array.prototype.slice.call(arguments, 1);
  12589. if (!test.apply(null, args)) {
  12590. async.doUntil(iterator, test, callback);
  12591. }
  12592. else {
  12593. callback();
  12594. }
  12595. });
  12596. };
  12597. async.queue = function (worker, concurrency) {
  12598. if (concurrency === undefined) {
  12599. concurrency = 1;
  12600. }
  12601. function _insert(q, data, pos, callback) {
  12602. if (!q.started){
  12603. q.started = true;
  12604. }
  12605. if (!_isArray(data)) {
  12606. data = [data];
  12607. }
  12608. if(data.length == 0) {
  12609. // call drain immediately if there are no tasks
  12610. return async.setImmediate(function() {
  12611. if (q.drain) {
  12612. q.drain();
  12613. }
  12614. });
  12615. }
  12616. _each(data, function(task) {
  12617. var item = {
  12618. data: task,
  12619. callback: typeof callback === 'function' ? callback : null
  12620. };
  12621. if (pos) {
  12622. q.tasks.unshift(item);
  12623. } else {
  12624. q.tasks.push(item);
  12625. }
  12626. if (q.saturated && q.tasks.length === q.concurrency) {
  12627. q.saturated();
  12628. }
  12629. async.setImmediate(q.process);
  12630. });
  12631. }
  12632. var workers = 0;
  12633. var q = {
  12634. tasks: [],
  12635. concurrency: concurrency,
  12636. saturated: null,
  12637. empty: null,
  12638. drain: null,
  12639. started: false,
  12640. paused: false,
  12641. push: function (data, callback) {
  12642. _insert(q, data, false, callback);
  12643. },
  12644. kill: function () {
  12645. q.drain = null;
  12646. q.tasks = [];
  12647. },
  12648. unshift: function (data, callback) {
  12649. _insert(q, data, true, callback);
  12650. },
  12651. process: function () {
  12652. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  12653. var task = q.tasks.shift();
  12654. if (q.empty && q.tasks.length === 0) {
  12655. q.empty();
  12656. }
  12657. workers += 1;
  12658. var next = function () {
  12659. workers -= 1;
  12660. if (task.callback) {
  12661. task.callback.apply(task, arguments);
  12662. }
  12663. if (q.drain && q.tasks.length + workers === 0) {
  12664. q.drain();
  12665. }
  12666. q.process();
  12667. };
  12668. var cb = only_once(next);
  12669. worker(task.data, cb);
  12670. }
  12671. },
  12672. length: function () {
  12673. return q.tasks.length;
  12674. },
  12675. running: function () {
  12676. return workers;
  12677. },
  12678. idle: function() {
  12679. return q.tasks.length + workers === 0;
  12680. },
  12681. pause: function () {
  12682. if (q.paused === true) { return; }
  12683. q.paused = true;
  12684. q.process();
  12685. },
  12686. resume: function () {
  12687. if (q.paused === false) { return; }
  12688. q.paused = false;
  12689. q.process();
  12690. }
  12691. };
  12692. return q;
  12693. };
  12694. async.priorityQueue = function (worker, concurrency) {
  12695. function _compareTasks(a, b){
  12696. return a.priority - b.priority;
  12697. };
  12698. function _binarySearch(sequence, item, compare) {
  12699. var beg = -1,
  12700. end = sequence.length - 1;
  12701. while (beg < end) {
  12702. var mid = beg + ((end - beg + 1) >>> 1);
  12703. if (compare(item, sequence[mid]) >= 0) {
  12704. beg = mid;
  12705. } else {
  12706. end = mid - 1;
  12707. }
  12708. }
  12709. return beg;
  12710. }
  12711. function _insert(q, data, priority, callback) {
  12712. if (!q.started){
  12713. q.started = true;
  12714. }
  12715. if (!_isArray(data)) {
  12716. data = [data];
  12717. }
  12718. if(data.length == 0) {
  12719. // call drain immediately if there are no tasks
  12720. return async.setImmediate(function() {
  12721. if (q.drain) {
  12722. q.drain();
  12723. }
  12724. });
  12725. }
  12726. _each(data, function(task) {
  12727. var item = {
  12728. data: task,
  12729. priority: priority,
  12730. callback: typeof callback === 'function' ? callback : null
  12731. };
  12732. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  12733. if (q.saturated && q.tasks.length === q.concurrency) {
  12734. q.saturated();
  12735. }
  12736. async.setImmediate(q.process);
  12737. });
  12738. }
  12739. // Start with a normal queue
  12740. var q = async.queue(worker, concurrency);
  12741. // Override push to accept second parameter representing priority
  12742. q.push = function (data, priority, callback) {
  12743. _insert(q, data, priority, callback);
  12744. };
  12745. // Remove unshift function
  12746. delete q.unshift;
  12747. return q;
  12748. };
  12749. async.cargo = function (worker, payload) {
  12750. var working = false,
  12751. tasks = [];
  12752. var cargo = {
  12753. tasks: tasks,
  12754. payload: payload,
  12755. saturated: null,
  12756. empty: null,
  12757. drain: null,
  12758. drained: true,
  12759. push: function (data, callback) {
  12760. if (!_isArray(data)) {
  12761. data = [data];
  12762. }
  12763. _each(data, function(task) {
  12764. tasks.push({
  12765. data: task,
  12766. callback: typeof callback === 'function' ? callback : null
  12767. });
  12768. cargo.drained = false;
  12769. if (cargo.saturated && tasks.length === payload) {
  12770. cargo.saturated();
  12771. }
  12772. });
  12773. async.setImmediate(cargo.process);
  12774. },
  12775. process: function process() {
  12776. if (working) return;
  12777. if (tasks.length === 0) {
  12778. if(cargo.drain && !cargo.drained) cargo.drain();
  12779. cargo.drained = true;
  12780. return;
  12781. }
  12782. var ts = typeof payload === 'number'
  12783. ? tasks.splice(0, payload)
  12784. : tasks.splice(0, tasks.length);
  12785. var ds = _map(ts, function (task) {
  12786. return task.data;
  12787. });
  12788. if(cargo.empty) cargo.empty();
  12789. working = true;
  12790. worker(ds, function () {
  12791. working = false;
  12792. var args = arguments;
  12793. _each(ts, function (data) {
  12794. if (data.callback) {
  12795. data.callback.apply(null, args);
  12796. }
  12797. });
  12798. process();
  12799. });
  12800. },
  12801. length: function () {
  12802. return tasks.length;
  12803. },
  12804. running: function () {
  12805. return working;
  12806. }
  12807. };
  12808. return cargo;
  12809. };
  12810. var _console_fn = function (name) {
  12811. return function (fn) {
  12812. var args = Array.prototype.slice.call(arguments, 1);
  12813. fn.apply(null, args.concat([function (err) {
  12814. var args = Array.prototype.slice.call(arguments, 1);
  12815. if (typeof console !== 'undefined') {
  12816. if (err) {
  12817. if (console.error) {
  12818. console.error(err);
  12819. }
  12820. }
  12821. else if (console[name]) {
  12822. _each(args, function (x) {
  12823. console[name](x);
  12824. });
  12825. }
  12826. }
  12827. }]));
  12828. };
  12829. };
  12830. async.log = _console_fn('log');
  12831. async.dir = _console_fn('dir');
  12832. /*async.info = _console_fn('info');
  12833. async.warn = _console_fn('warn');
  12834. async.error = _console_fn('error');*/
  12835. async.memoize = function (fn, hasher) {
  12836. var memo = {};
  12837. var queues = {};
  12838. hasher = hasher || function (x) {
  12839. return x;
  12840. };
  12841. var memoized = function () {
  12842. var args = Array.prototype.slice.call(arguments);
  12843. var callback = args.pop();
  12844. var key = hasher.apply(null, args);
  12845. if (key in memo) {
  12846. async.nextTick(function () {
  12847. callback.apply(null, memo[key]);
  12848. });
  12849. }
  12850. else if (key in queues) {
  12851. queues[key].push(callback);
  12852. }
  12853. else {
  12854. queues[key] = [callback];
  12855. fn.apply(null, args.concat([function () {
  12856. memo[key] = arguments;
  12857. var q = queues[key];
  12858. delete queues[key];
  12859. for (var i = 0, l = q.length; i < l; i++) {
  12860. q[i].apply(null, arguments);
  12861. }
  12862. }]));
  12863. }
  12864. };
  12865. memoized.memo = memo;
  12866. memoized.unmemoized = fn;
  12867. return memoized;
  12868. };
  12869. async.unmemoize = function (fn) {
  12870. return function () {
  12871. return (fn.unmemoized || fn).apply(null, arguments);
  12872. };
  12873. };
  12874. async.times = function (count, iterator, callback) {
  12875. var counter = [];
  12876. for (var i = 0; i < count; i++) {
  12877. counter.push(i);
  12878. }
  12879. return async.map(counter, iterator, callback);
  12880. };
  12881. async.timesSeries = function (count, iterator, callback) {
  12882. var counter = [];
  12883. for (var i = 0; i < count; i++) {
  12884. counter.push(i);
  12885. }
  12886. return async.mapSeries(counter, iterator, callback);
  12887. };
  12888. async.seq = function (/* functions... */) {
  12889. var fns = arguments;
  12890. return function () {
  12891. var that = this;
  12892. var args = Array.prototype.slice.call(arguments);
  12893. var callback = args.pop();
  12894. async.reduce(fns, args, function (newargs, fn, cb) {
  12895. fn.apply(that, newargs.concat([function () {
  12896. var err = arguments[0];
  12897. var nextargs = Array.prototype.slice.call(arguments, 1);
  12898. cb(err, nextargs);
  12899. }]))
  12900. },
  12901. function (err, results) {
  12902. callback.apply(that, [err].concat(results));
  12903. });
  12904. };
  12905. };
  12906. async.compose = function (/* functions... */) {
  12907. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  12908. };
  12909. var _applyEach = function (eachfn, fns /*args...*/) {
  12910. var go = function () {
  12911. var that = this;
  12912. var args = Array.prototype.slice.call(arguments);
  12913. var callback = args.pop();
  12914. return eachfn(fns, function (fn, cb) {
  12915. fn.apply(that, args.concat([cb]));
  12916. },
  12917. callback);
  12918. };
  12919. if (arguments.length > 2) {
  12920. var args = Array.prototype.slice.call(arguments, 2);
  12921. return go.apply(this, args);
  12922. }
  12923. else {
  12924. return go;
  12925. }
  12926. };
  12927. async.applyEach = doParallel(_applyEach);
  12928. async.applyEachSeries = doSeries(_applyEach);
  12929. async.forever = function (fn, callback) {
  12930. function next(err) {
  12931. if (err) {
  12932. if (callback) {
  12933. return callback(err);
  12934. }
  12935. throw err;
  12936. }
  12937. fn(next);
  12938. }
  12939. next();
  12940. };
  12941. // Node.js
  12942. if (typeof module !== 'undefined' && module.exports) {
  12943. module.exports = async;
  12944. }
  12945. // AMD / RequireJS
  12946. else if (typeof define !== 'undefined' && define.amd) {
  12947. define([], function () {
  12948. return async;
  12949. });
  12950. }
  12951. // included directly via <script> tag
  12952. else {
  12953. root.async = async;
  12954. }
  12955. }());
  12956. }).call(this,require('_process'))
  12957. },{"_process":46}],45:[function(require,module,exports){
  12958. // Copyright Joyent, Inc. and other Node contributors.
  12959. //
  12960. // Permission is hereby granted, free of charge, to any person obtaining a
  12961. // copy of this software and associated documentation files (the
  12962. // "Software"), to deal in the Software without restriction, including
  12963. // without limitation the rights to use, copy, modify, merge, publish,
  12964. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12965. // persons to whom the Software is furnished to do so, subject to the
  12966. // following conditions:
  12967. //
  12968. // The above copyright notice and this permission notice shall be included
  12969. // in all copies or substantial portions of the Software.
  12970. //
  12971. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12972. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12973. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12974. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12975. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12976. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12977. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12978. function EventEmitter() {
  12979. this._events = this._events || {};
  12980. this._maxListeners = this._maxListeners || undefined;
  12981. }
  12982. module.exports = EventEmitter;
  12983. // Backwards-compat with node 0.10.x
  12984. EventEmitter.EventEmitter = EventEmitter;
  12985. EventEmitter.prototype._events = undefined;
  12986. EventEmitter.prototype._maxListeners = undefined;
  12987. // By default EventEmitters will print a warning if more than 10 listeners are
  12988. // added to it. This is a useful default which helps finding memory leaks.
  12989. EventEmitter.defaultMaxListeners = 10;
  12990. // Obviously not all Emitters should be limited to 10. This function allows
  12991. // that to be increased. Set to zero for unlimited.
  12992. EventEmitter.prototype.setMaxListeners = function(n) {
  12993. if (!isNumber(n) || n < 0 || isNaN(n))
  12994. throw TypeError('n must be a positive number');
  12995. this._maxListeners = n;
  12996. return this;
  12997. };
  12998. EventEmitter.prototype.emit = function(type) {
  12999. var er, handler, len, args, i, listeners;
  13000. if (!this._events)
  13001. this._events = {};
  13002. // If there is no 'error' event listener then throw.
  13003. if (type === 'error') {
  13004. if (!this._events.error ||
  13005. (isObject(this._events.error) && !this._events.error.length)) {
  13006. er = arguments[1];
  13007. if (er instanceof Error) {
  13008. throw er; // Unhandled 'error' event
  13009. }
  13010. throw TypeError('Uncaught, unspecified "error" event.');
  13011. }
  13012. }
  13013. handler = this._events[type];
  13014. if (isUndefined(handler))
  13015. return false;
  13016. if (isFunction(handler)) {
  13017. switch (arguments.length) {
  13018. // fast cases
  13019. case 1:
  13020. handler.call(this);
  13021. break;
  13022. case 2:
  13023. handler.call(this, arguments[1]);
  13024. break;
  13025. case 3:
  13026. handler.call(this, arguments[1], arguments[2]);
  13027. break;
  13028. // slower
  13029. default:
  13030. len = arguments.length;
  13031. args = new Array(len - 1);
  13032. for (i = 1; i < len; i++)
  13033. args[i - 1] = arguments[i];
  13034. handler.apply(this, args);
  13035. }
  13036. } else if (isObject(handler)) {
  13037. len = arguments.length;
  13038. args = new Array(len - 1);
  13039. for (i = 1; i < len; i++)
  13040. args[i - 1] = arguments[i];
  13041. listeners = handler.slice();
  13042. len = listeners.length;
  13043. for (i = 0; i < len; i++)
  13044. listeners[i].apply(this, args);
  13045. }
  13046. return true;
  13047. };
  13048. EventEmitter.prototype.addListener = function(type, listener) {
  13049. var m;
  13050. if (!isFunction(listener))
  13051. throw TypeError('listener must be a function');
  13052. if (!this._events)
  13053. this._events = {};
  13054. // To avoid recursion in the case that type === "newListener"! Before
  13055. // adding it to the listeners, first emit "newListener".
  13056. if (this._events.newListener)
  13057. this.emit('newListener', type,
  13058. isFunction(listener.listener) ?
  13059. listener.listener : listener);
  13060. if (!this._events[type])
  13061. // Optimize the case of one listener. Don't need the extra array object.
  13062. this._events[type] = listener;
  13063. else if (isObject(this._events[type]))
  13064. // If we've already got an array, just append.
  13065. this._events[type].push(listener);
  13066. else
  13067. // Adding the second element, need to change to array.
  13068. this._events[type] = [this._events[type], listener];
  13069. // Check for listener leak
  13070. if (isObject(this._events[type]) && !this._events[type].warned) {
  13071. var m;
  13072. if (!isUndefined(this._maxListeners)) {
  13073. m = this._maxListeners;
  13074. } else {
  13075. m = EventEmitter.defaultMaxListeners;
  13076. }
  13077. if (m && m > 0 && this._events[type].length > m) {
  13078. this._events[type].warned = true;
  13079. console.error('(node) warning: possible EventEmitter memory ' +
  13080. 'leak detected. %d listeners added. ' +
  13081. 'Use emitter.setMaxListeners() to increase limit.',
  13082. this._events[type].length);
  13083. if (typeof console.trace === 'function') {
  13084. // not supported in IE 10
  13085. console.trace();
  13086. }
  13087. }
  13088. }
  13089. return this;
  13090. };
  13091. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  13092. EventEmitter.prototype.once = function(type, listener) {
  13093. if (!isFunction(listener))
  13094. throw TypeError('listener must be a function');
  13095. var fired = false;
  13096. function g() {
  13097. this.removeListener(type, g);
  13098. if (!fired) {
  13099. fired = true;
  13100. listener.apply(this, arguments);
  13101. }
  13102. }
  13103. g.listener = listener;
  13104. this.on(type, g);
  13105. return this;
  13106. };
  13107. // emits a 'removeListener' event iff the listener was removed
  13108. EventEmitter.prototype.removeListener = function(type, listener) {
  13109. var list, position, length, i;
  13110. if (!isFunction(listener))
  13111. throw TypeError('listener must be a function');
  13112. if (!this._events || !this._events[type])
  13113. return this;
  13114. list = this._events[type];
  13115. length = list.length;
  13116. position = -1;
  13117. if (list === listener ||
  13118. (isFunction(list.listener) && list.listener === listener)) {
  13119. delete this._events[type];
  13120. if (this._events.removeListener)
  13121. this.emit('removeListener', type, listener);
  13122. } else if (isObject(list)) {
  13123. for (i = length; i-- > 0;) {
  13124. if (list[i] === listener ||
  13125. (list[i].listener && list[i].listener === listener)) {
  13126. position = i;
  13127. break;
  13128. }
  13129. }
  13130. if (position < 0)
  13131. return this;
  13132. if (list.length === 1) {
  13133. list.length = 0;
  13134. delete this._events[type];
  13135. } else {
  13136. list.splice(position, 1);
  13137. }
  13138. if (this._events.removeListener)
  13139. this.emit('removeListener', type, listener);
  13140. }
  13141. return this;
  13142. };
  13143. EventEmitter.prototype.removeAllListeners = function(type) {
  13144. var key, listeners;
  13145. if (!this._events)
  13146. return this;
  13147. // not listening for removeListener, no need to emit
  13148. if (!this._events.removeListener) {
  13149. if (arguments.length === 0)
  13150. this._events = {};
  13151. else if (this._events[type])
  13152. delete this._events[type];
  13153. return this;
  13154. }
  13155. // emit removeListener for all listeners on all events
  13156. if (arguments.length === 0) {
  13157. for (key in this._events) {
  13158. if (key === 'removeListener') continue;
  13159. this.removeAllListeners(key);
  13160. }
  13161. this.removeAllListeners('removeListener');
  13162. this._events = {};
  13163. return this;
  13164. }
  13165. listeners = this._events[type];
  13166. if (isFunction(listeners)) {
  13167. this.removeListener(type, listeners);
  13168. } else {
  13169. // LIFO order
  13170. while (listeners.length)
  13171. this.removeListener(type, listeners[listeners.length - 1]);
  13172. }
  13173. delete this._events[type];
  13174. return this;
  13175. };
  13176. EventEmitter.prototype.listeners = function(type) {
  13177. var ret;
  13178. if (!this._events || !this._events[type])
  13179. ret = [];
  13180. else if (isFunction(this._events[type]))
  13181. ret = [this._events[type]];
  13182. else
  13183. ret = this._events[type].slice();
  13184. return ret;
  13185. };
  13186. EventEmitter.listenerCount = function(emitter, type) {
  13187. var ret;
  13188. if (!emitter._events || !emitter._events[type])
  13189. ret = 0;
  13190. else if (isFunction(emitter._events[type]))
  13191. ret = 1;
  13192. else
  13193. ret = emitter._events[type].length;
  13194. return ret;
  13195. };
  13196. function isFunction(arg) {
  13197. return typeof arg === 'function';
  13198. }
  13199. function isNumber(arg) {
  13200. return typeof arg === 'number';
  13201. }
  13202. function isObject(arg) {
  13203. return typeof arg === 'object' && arg !== null;
  13204. }
  13205. function isUndefined(arg) {
  13206. return arg === void 0;
  13207. }
  13208. },{}],46:[function(require,module,exports){
  13209. // shim for using process in browser
  13210. var process = module.exports = {};
  13211. var queue = [];
  13212. var draining = false;
  13213. var currentQueue;
  13214. var queueIndex = -1;
  13215. function cleanUpNextTick() {
  13216. draining = false;
  13217. if (currentQueue.length) {
  13218. queue = currentQueue.concat(queue);
  13219. } else {
  13220. queueIndex = -1;
  13221. }
  13222. if (queue.length) {
  13223. drainQueue();
  13224. }
  13225. }
  13226. function drainQueue() {
  13227. if (draining) {
  13228. return;
  13229. }
  13230. var timeout = setTimeout(cleanUpNextTick);
  13231. draining = true;
  13232. var len = queue.length;
  13233. while(len) {
  13234. currentQueue = queue;
  13235. queue = [];
  13236. while (++queueIndex < len) {
  13237. if (currentQueue) {
  13238. currentQueue[queueIndex].run();
  13239. }
  13240. }
  13241. queueIndex = -1;
  13242. len = queue.length;
  13243. }
  13244. currentQueue = null;
  13245. draining = false;
  13246. clearTimeout(timeout);
  13247. }
  13248. process.nextTick = function (fun) {
  13249. var args = new Array(arguments.length - 1);
  13250. if (arguments.length > 1) {
  13251. for (var i = 1; i < arguments.length; i++) {
  13252. args[i - 1] = arguments[i];
  13253. }
  13254. }
  13255. queue.push(new Item(fun, args));
  13256. if (queue.length === 1 && !draining) {
  13257. setTimeout(drainQueue, 0);
  13258. }
  13259. };
  13260. // v8 likes predictible objects
  13261. function Item(fun, array) {
  13262. this.fun = fun;
  13263. this.array = array;
  13264. }
  13265. Item.prototype.run = function () {
  13266. this.fun.apply(null, this.array);
  13267. };
  13268. process.title = 'browser';
  13269. process.browser = true;
  13270. process.env = {};
  13271. process.argv = [];
  13272. process.version = ''; // empty string to avoid regexp issues
  13273. process.versions = {};
  13274. function noop() {}
  13275. process.on = noop;
  13276. process.addListener = noop;
  13277. process.once = noop;
  13278. process.off = noop;
  13279. process.removeListener = noop;
  13280. process.removeAllListeners = noop;
  13281. process.emit = noop;
  13282. process.binding = function (name) {
  13283. throw new Error('process.binding is not supported');
  13284. };
  13285. process.cwd = function () { return '/' };
  13286. process.chdir = function (dir) {
  13287. throw new Error('process.chdir is not supported');
  13288. };
  13289. process.umask = function() { return 0; };
  13290. },{}],47:[function(require,module,exports){
  13291. (function (process,global){
  13292. /*!
  13293. * @overview es6-promise - a tiny implementation of Promises/A+.
  13294. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  13295. * @license Licensed under MIT license
  13296. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  13297. * @version 3.0.2
  13298. */
  13299. (function() {
  13300. "use strict";
  13301. function lib$es6$promise$utils$$objectOrFunction(x) {
  13302. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  13303. }
  13304. function lib$es6$promise$utils$$isFunction(x) {
  13305. return typeof x === 'function';
  13306. }
  13307. function lib$es6$promise$utils$$isMaybeThenable(x) {
  13308. return typeof x === 'object' && x !== null;
  13309. }
  13310. var lib$es6$promise$utils$$_isArray;
  13311. if (!Array.isArray) {
  13312. lib$es6$promise$utils$$_isArray = function (x) {
  13313. return Object.prototype.toString.call(x) === '[object Array]';
  13314. };
  13315. } else {
  13316. lib$es6$promise$utils$$_isArray = Array.isArray;
  13317. }
  13318. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  13319. var lib$es6$promise$asap$$len = 0;
  13320. var lib$es6$promise$asap$$toString = {}.toString;
  13321. var lib$es6$promise$asap$$vertxNext;
  13322. var lib$es6$promise$asap$$customSchedulerFn;
  13323. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  13324. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  13325. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  13326. lib$es6$promise$asap$$len += 2;
  13327. if (lib$es6$promise$asap$$len === 2) {
  13328. // If len is 2, that means that we need to schedule an async flush.
  13329. // If additional callbacks are queued before the queue is flushed, they
  13330. // will be processed by this flush that we are scheduling.
  13331. if (lib$es6$promise$asap$$customSchedulerFn) {
  13332. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  13333. } else {
  13334. lib$es6$promise$asap$$scheduleFlush();
  13335. }
  13336. }
  13337. }
  13338. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  13339. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  13340. }
  13341. function lib$es6$promise$asap$$setAsap(asapFn) {
  13342. lib$es6$promise$asap$$asap = asapFn;
  13343. }
  13344. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  13345. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  13346. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  13347. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  13348. // test for web worker but not in IE10
  13349. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  13350. typeof importScripts !== 'undefined' &&
  13351. typeof MessageChannel !== 'undefined';
  13352. // node
  13353. function lib$es6$promise$asap$$useNextTick() {
  13354. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  13355. // see https://github.com/cujojs/when/issues/410 for details
  13356. return function() {
  13357. process.nextTick(lib$es6$promise$asap$$flush);
  13358. };
  13359. }
  13360. // vertx
  13361. function lib$es6$promise$asap$$useVertxTimer() {
  13362. return function() {
  13363. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  13364. };
  13365. }
  13366. function lib$es6$promise$asap$$useMutationObserver() {
  13367. var iterations = 0;
  13368. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  13369. var node = document.createTextNode('');
  13370. observer.observe(node, { characterData: true });
  13371. return function() {
  13372. node.data = (iterations = ++iterations % 2);
  13373. };
  13374. }
  13375. // web worker
  13376. function lib$es6$promise$asap$$useMessageChannel() {
  13377. var channel = new MessageChannel();
  13378. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  13379. return function () {
  13380. channel.port2.postMessage(0);
  13381. };
  13382. }
  13383. function lib$es6$promise$asap$$useSetTimeout() {
  13384. return function() {
  13385. setTimeout(lib$es6$promise$asap$$flush, 1);
  13386. };
  13387. }
  13388. var lib$es6$promise$asap$$queue = new Array(1000);
  13389. function lib$es6$promise$asap$$flush() {
  13390. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  13391. var callback = lib$es6$promise$asap$$queue[i];
  13392. var arg = lib$es6$promise$asap$$queue[i+1];
  13393. callback(arg);
  13394. lib$es6$promise$asap$$queue[i] = undefined;
  13395. lib$es6$promise$asap$$queue[i+1] = undefined;
  13396. }
  13397. lib$es6$promise$asap$$len = 0;
  13398. }
  13399. function lib$es6$promise$asap$$attemptVertx() {
  13400. try {
  13401. var r = require;
  13402. var vertx = r('vertx');
  13403. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  13404. return lib$es6$promise$asap$$useVertxTimer();
  13405. } catch(e) {
  13406. return lib$es6$promise$asap$$useSetTimeout();
  13407. }
  13408. }
  13409. var lib$es6$promise$asap$$scheduleFlush;
  13410. // Decide what async method to use to triggering processing of queued callbacks:
  13411. if (lib$es6$promise$asap$$isNode) {
  13412. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  13413. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  13414. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  13415. } else if (lib$es6$promise$asap$$isWorker) {
  13416. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  13417. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  13418. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  13419. } else {
  13420. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  13421. }
  13422. function lib$es6$promise$$internal$$noop() {}
  13423. var lib$es6$promise$$internal$$PENDING = void 0;
  13424. var lib$es6$promise$$internal$$FULFILLED = 1;
  13425. var lib$es6$promise$$internal$$REJECTED = 2;
  13426. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13427. function lib$es6$promise$$internal$$selfFulfillment() {
  13428. return new TypeError("You cannot resolve a promise with itself");
  13429. }
  13430. function lib$es6$promise$$internal$$cannotReturnOwn() {
  13431. return new TypeError('A promises callback cannot return that same promise.');
  13432. }
  13433. function lib$es6$promise$$internal$$getThen(promise) {
  13434. try {
  13435. return promise.then;
  13436. } catch(error) {
  13437. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  13438. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  13439. }
  13440. }
  13441. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  13442. try {
  13443. then.call(value, fulfillmentHandler, rejectionHandler);
  13444. } catch(e) {
  13445. return e;
  13446. }
  13447. }
  13448. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  13449. lib$es6$promise$asap$$asap(function(promise) {
  13450. var sealed = false;
  13451. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  13452. if (sealed) { return; }
  13453. sealed = true;
  13454. if (thenable !== value) {
  13455. lib$es6$promise$$internal$$resolve(promise, value);
  13456. } else {
  13457. lib$es6$promise$$internal$$fulfill(promise, value);
  13458. }
  13459. }, function(reason) {
  13460. if (sealed) { return; }
  13461. sealed = true;
  13462. lib$es6$promise$$internal$$reject(promise, reason);
  13463. }, 'Settle: ' + (promise._label || ' unknown promise'));
  13464. if (!sealed && error) {
  13465. sealed = true;
  13466. lib$es6$promise$$internal$$reject(promise, error);
  13467. }
  13468. }, promise);
  13469. }
  13470. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  13471. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  13472. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  13473. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  13474. lib$es6$promise$$internal$$reject(promise, thenable._result);
  13475. } else {
  13476. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  13477. lib$es6$promise$$internal$$resolve(promise, value);
  13478. }, function(reason) {
  13479. lib$es6$promise$$internal$$reject(promise, reason);
  13480. });
  13481. }
  13482. }
  13483. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  13484. if (maybeThenable.constructor === promise.constructor) {
  13485. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  13486. } else {
  13487. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  13488. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  13489. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  13490. } else if (then === undefined) {
  13491. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13492. } else if (lib$es6$promise$utils$$isFunction(then)) {
  13493. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  13494. } else {
  13495. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13496. }
  13497. }
  13498. }
  13499. function lib$es6$promise$$internal$$resolve(promise, value) {
  13500. if (promise === value) {
  13501. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  13502. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  13503. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  13504. } else {
  13505. lib$es6$promise$$internal$$fulfill(promise, value);
  13506. }
  13507. }
  13508. function lib$es6$promise$$internal$$publishRejection(promise) {
  13509. if (promise._onerror) {
  13510. promise._onerror(promise._result);
  13511. }
  13512. lib$es6$promise$$internal$$publish(promise);
  13513. }
  13514. function lib$es6$promise$$internal$$fulfill(promise, value) {
  13515. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13516. promise._result = value;
  13517. promise._state = lib$es6$promise$$internal$$FULFILLED;
  13518. if (promise._subscribers.length !== 0) {
  13519. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  13520. }
  13521. }
  13522. function lib$es6$promise$$internal$$reject(promise, reason) {
  13523. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13524. promise._state = lib$es6$promise$$internal$$REJECTED;
  13525. promise._result = reason;
  13526. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  13527. }
  13528. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  13529. var subscribers = parent._subscribers;
  13530. var length = subscribers.length;
  13531. parent._onerror = null;
  13532. subscribers[length] = child;
  13533. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  13534. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  13535. if (length === 0 && parent._state) {
  13536. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  13537. }
  13538. }
  13539. function lib$es6$promise$$internal$$publish(promise) {
  13540. var subscribers = promise._subscribers;
  13541. var settled = promise._state;
  13542. if (subscribers.length === 0) { return; }
  13543. var child, callback, detail = promise._result;
  13544. for (var i = 0; i < subscribers.length; i += 3) {
  13545. child = subscribers[i];
  13546. callback = subscribers[i + settled];
  13547. if (child) {
  13548. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  13549. } else {
  13550. callback(detail);
  13551. }
  13552. }
  13553. promise._subscribers.length = 0;
  13554. }
  13555. function lib$es6$promise$$internal$$ErrorObject() {
  13556. this.error = null;
  13557. }
  13558. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13559. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  13560. try {
  13561. return callback(detail);
  13562. } catch(e) {
  13563. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  13564. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  13565. }
  13566. }
  13567. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  13568. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  13569. value, error, succeeded, failed;
  13570. if (hasCallback) {
  13571. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  13572. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  13573. failed = true;
  13574. error = value.error;
  13575. value = null;
  13576. } else {
  13577. succeeded = true;
  13578. }
  13579. if (promise === value) {
  13580. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  13581. return;
  13582. }
  13583. } else {
  13584. value = detail;
  13585. succeeded = true;
  13586. }
  13587. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  13588. // noop
  13589. } else if (hasCallback && succeeded) {
  13590. lib$es6$promise$$internal$$resolve(promise, value);
  13591. } else if (failed) {
  13592. lib$es6$promise$$internal$$reject(promise, error);
  13593. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  13594. lib$es6$promise$$internal$$fulfill(promise, value);
  13595. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  13596. lib$es6$promise$$internal$$reject(promise, value);
  13597. }
  13598. }
  13599. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  13600. try {
  13601. resolver(function resolvePromise(value){
  13602. lib$es6$promise$$internal$$resolve(promise, value);
  13603. }, function rejectPromise(reason) {
  13604. lib$es6$promise$$internal$$reject(promise, reason);
  13605. });
  13606. } catch(e) {
  13607. lib$es6$promise$$internal$$reject(promise, e);
  13608. }
  13609. }
  13610. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  13611. var enumerator = this;
  13612. enumerator._instanceConstructor = Constructor;
  13613. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  13614. if (enumerator._validateInput(input)) {
  13615. enumerator._input = input;
  13616. enumerator.length = input.length;
  13617. enumerator._remaining = input.length;
  13618. enumerator._init();
  13619. if (enumerator.length === 0) {
  13620. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13621. } else {
  13622. enumerator.length = enumerator.length || 0;
  13623. enumerator._enumerate();
  13624. if (enumerator._remaining === 0) {
  13625. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13626. }
  13627. }
  13628. } else {
  13629. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  13630. }
  13631. }
  13632. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  13633. return lib$es6$promise$utils$$isArray(input);
  13634. };
  13635. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  13636. return new Error('Array Methods must be provided an Array');
  13637. };
  13638. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  13639. this._result = new Array(this.length);
  13640. };
  13641. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  13642. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  13643. var enumerator = this;
  13644. var length = enumerator.length;
  13645. var promise = enumerator.promise;
  13646. var input = enumerator._input;
  13647. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13648. enumerator._eachEntry(input[i], i);
  13649. }
  13650. };
  13651. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  13652. var enumerator = this;
  13653. var c = enumerator._instanceConstructor;
  13654. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  13655. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  13656. entry._onerror = null;
  13657. enumerator._settledAt(entry._state, i, entry._result);
  13658. } else {
  13659. enumerator._willSettleAt(c.resolve(entry), i);
  13660. }
  13661. } else {
  13662. enumerator._remaining--;
  13663. enumerator._result[i] = entry;
  13664. }
  13665. };
  13666. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  13667. var enumerator = this;
  13668. var promise = enumerator.promise;
  13669. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  13670. enumerator._remaining--;
  13671. if (state === lib$es6$promise$$internal$$REJECTED) {
  13672. lib$es6$promise$$internal$$reject(promise, value);
  13673. } else {
  13674. enumerator._result[i] = value;
  13675. }
  13676. }
  13677. if (enumerator._remaining === 0) {
  13678. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  13679. }
  13680. };
  13681. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  13682. var enumerator = this;
  13683. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  13684. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  13685. }, function(reason) {
  13686. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  13687. });
  13688. };
  13689. function lib$es6$promise$promise$all$$all(entries) {
  13690. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  13691. }
  13692. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  13693. function lib$es6$promise$promise$race$$race(entries) {
  13694. /*jshint validthis:true */
  13695. var Constructor = this;
  13696. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13697. if (!lib$es6$promise$utils$$isArray(entries)) {
  13698. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  13699. return promise;
  13700. }
  13701. var length = entries.length;
  13702. function onFulfillment(value) {
  13703. lib$es6$promise$$internal$$resolve(promise, value);
  13704. }
  13705. function onRejection(reason) {
  13706. lib$es6$promise$$internal$$reject(promise, reason);
  13707. }
  13708. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13709. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  13710. }
  13711. return promise;
  13712. }
  13713. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  13714. function lib$es6$promise$promise$resolve$$resolve(object) {
  13715. /*jshint validthis:true */
  13716. var Constructor = this;
  13717. if (object && typeof object === 'object' && object.constructor === Constructor) {
  13718. return object;
  13719. }
  13720. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13721. lib$es6$promise$$internal$$resolve(promise, object);
  13722. return promise;
  13723. }
  13724. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  13725. function lib$es6$promise$promise$reject$$reject(reason) {
  13726. /*jshint validthis:true */
  13727. var Constructor = this;
  13728. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13729. lib$es6$promise$$internal$$reject(promise, reason);
  13730. return promise;
  13731. }
  13732. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  13733. var lib$es6$promise$promise$$counter = 0;
  13734. function lib$es6$promise$promise$$needsResolver() {
  13735. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  13736. }
  13737. function lib$es6$promise$promise$$needsNew() {
  13738. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  13739. }
  13740. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  13741. /**
  13742. Promise objects represent the eventual result of an asynchronous operation. The
  13743. primary way of interacting with a promise is through its `then` method, which
  13744. registers callbacks to receive either a promise's eventual value or the reason
  13745. why the promise cannot be fulfilled.
  13746. Terminology
  13747. -----------
  13748. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  13749. - `thenable` is an object or function that defines a `then` method.
  13750. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  13751. - `exception` is a value that is thrown using the throw statement.
  13752. - `reason` is a value that indicates why a promise was rejected.
  13753. - `settled` the final resting state of a promise, fulfilled or rejected.
  13754. A promise can be in one of three states: pending, fulfilled, or rejected.
  13755. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  13756. state. Promises that are rejected have a rejection reason and are in the
  13757. rejected state. A fulfillment value is never a thenable.
  13758. Promises can also be said to *resolve* a value. If this value is also a
  13759. promise, then the original promise's settled state will match the value's
  13760. settled state. So a promise that *resolves* a promise that rejects will
  13761. itself reject, and a promise that *resolves* a promise that fulfills will
  13762. itself fulfill.
  13763. Basic Usage:
  13764. ------------
  13765. ```js
  13766. var promise = new Promise(function(resolve, reject) {
  13767. // on success
  13768. resolve(value);
  13769. // on failure
  13770. reject(reason);
  13771. });
  13772. promise.then(function(value) {
  13773. // on fulfillment
  13774. }, function(reason) {
  13775. // on rejection
  13776. });
  13777. ```
  13778. Advanced Usage:
  13779. ---------------
  13780. Promises shine when abstracting away asynchronous interactions such as
  13781. `XMLHttpRequest`s.
  13782. ```js
  13783. function getJSON(url) {
  13784. return new Promise(function(resolve, reject){
  13785. var xhr = new XMLHttpRequest();
  13786. xhr.open('GET', url);
  13787. xhr.onreadystatechange = handler;
  13788. xhr.responseType = 'json';
  13789. xhr.setRequestHeader('Accept', 'application/json');
  13790. xhr.send();
  13791. function handler() {
  13792. if (this.readyState === this.DONE) {
  13793. if (this.status === 200) {
  13794. resolve(this.response);
  13795. } else {
  13796. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  13797. }
  13798. }
  13799. };
  13800. });
  13801. }
  13802. getJSON('/posts.json').then(function(json) {
  13803. // on fulfillment
  13804. }, function(reason) {
  13805. // on rejection
  13806. });
  13807. ```
  13808. Unlike callbacks, promises are great composable primitives.
  13809. ```js
  13810. Promise.all([
  13811. getJSON('/posts'),
  13812. getJSON('/comments')
  13813. ]).then(function(values){
  13814. values[0] // => postsJSON
  13815. values[1] // => commentsJSON
  13816. return values;
  13817. });
  13818. ```
  13819. @class Promise
  13820. @param {function} resolver
  13821. Useful for tooling.
  13822. @constructor
  13823. */
  13824. function lib$es6$promise$promise$$Promise(resolver) {
  13825. this._id = lib$es6$promise$promise$$counter++;
  13826. this._state = undefined;
  13827. this._result = undefined;
  13828. this._subscribers = [];
  13829. if (lib$es6$promise$$internal$$noop !== resolver) {
  13830. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  13831. lib$es6$promise$promise$$needsResolver();
  13832. }
  13833. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  13834. lib$es6$promise$promise$$needsNew();
  13835. }
  13836. lib$es6$promise$$internal$$initializePromise(this, resolver);
  13837. }
  13838. }
  13839. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  13840. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  13841. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  13842. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  13843. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  13844. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  13845. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  13846. lib$es6$promise$promise$$Promise.prototype = {
  13847. constructor: lib$es6$promise$promise$$Promise,
  13848. /**
  13849. The primary way of interacting with a promise is through its `then` method,
  13850. which registers callbacks to receive either a promise's eventual value or the
  13851. reason why the promise cannot be fulfilled.
  13852. ```js
  13853. findUser().then(function(user){
  13854. // user is available
  13855. }, function(reason){
  13856. // user is unavailable, and you are given the reason why
  13857. });
  13858. ```
  13859. Chaining
  13860. --------
  13861. The return value of `then` is itself a promise. This second, 'downstream'
  13862. promise is resolved with the return value of the first promise's fulfillment
  13863. or rejection handler, or rejected if the handler throws an exception.
  13864. ```js
  13865. findUser().then(function (user) {
  13866. return user.name;
  13867. }, function (reason) {
  13868. return 'default name';
  13869. }).then(function (userName) {
  13870. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  13871. // will be `'default name'`
  13872. });
  13873. findUser().then(function (user) {
  13874. throw new Error('Found user, but still unhappy');
  13875. }, function (reason) {
  13876. throw new Error('`findUser` rejected and we're unhappy');
  13877. }).then(function (value) {
  13878. // never reached
  13879. }, function (reason) {
  13880. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  13881. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  13882. });
  13883. ```
  13884. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  13885. ```js
  13886. findUser().then(function (user) {
  13887. throw new PedagogicalException('Upstream error');
  13888. }).then(function (value) {
  13889. // never reached
  13890. }).then(function (value) {
  13891. // never reached
  13892. }, function (reason) {
  13893. // The `PedgagocialException` is propagated all the way down to here
  13894. });
  13895. ```
  13896. Assimilation
  13897. ------------
  13898. Sometimes the value you want to propagate to a downstream promise can only be
  13899. retrieved asynchronously. This can be achieved by returning a promise in the
  13900. fulfillment or rejection handler. The downstream promise will then be pending
  13901. until the returned promise is settled. This is called *assimilation*.
  13902. ```js
  13903. findUser().then(function (user) {
  13904. return findCommentsByAuthor(user);
  13905. }).then(function (comments) {
  13906. // The user's comments are now available
  13907. });
  13908. ```
  13909. If the assimliated promise rejects, then the downstream promise will also reject.
  13910. ```js
  13911. findUser().then(function (user) {
  13912. return findCommentsByAuthor(user);
  13913. }).then(function (comments) {
  13914. // If `findCommentsByAuthor` fulfills, we'll have the value here
  13915. }, function (reason) {
  13916. // If `findCommentsByAuthor` rejects, we'll have the reason here
  13917. });
  13918. ```
  13919. Simple Example
  13920. --------------
  13921. Synchronous Example
  13922. ```javascript
  13923. var result;
  13924. try {
  13925. result = findResult();
  13926. // success
  13927. } catch(reason) {
  13928. // failure
  13929. }
  13930. ```
  13931. Errback Example
  13932. ```js
  13933. findResult(function(result, err){
  13934. if (err) {
  13935. // failure
  13936. } else {
  13937. // success
  13938. }
  13939. });
  13940. ```
  13941. Promise Example;
  13942. ```javascript
  13943. findResult().then(function(result){
  13944. // success
  13945. }, function(reason){
  13946. // failure
  13947. });
  13948. ```
  13949. Advanced Example
  13950. --------------
  13951. Synchronous Example
  13952. ```javascript
  13953. var author, books;
  13954. try {
  13955. author = findAuthor();
  13956. books = findBooksByAuthor(author);
  13957. // success
  13958. } catch(reason) {
  13959. // failure
  13960. }
  13961. ```
  13962. Errback Example
  13963. ```js
  13964. function foundBooks(books) {
  13965. }
  13966. function failure(reason) {
  13967. }
  13968. findAuthor(function(author, err){
  13969. if (err) {
  13970. failure(err);
  13971. // failure
  13972. } else {
  13973. try {
  13974. findBoooksByAuthor(author, function(books, err) {
  13975. if (err) {
  13976. failure(err);
  13977. } else {
  13978. try {
  13979. foundBooks(books);
  13980. } catch(reason) {
  13981. failure(reason);
  13982. }
  13983. }
  13984. });
  13985. } catch(error) {
  13986. failure(err);
  13987. }
  13988. // success
  13989. }
  13990. });
  13991. ```
  13992. Promise Example;
  13993. ```javascript
  13994. findAuthor().
  13995. then(findBooksByAuthor).
  13996. then(function(books){
  13997. // found books
  13998. }).catch(function(reason){
  13999. // something went wrong
  14000. });
  14001. ```
  14002. @method then
  14003. @param {Function} onFulfilled
  14004. @param {Function} onRejected
  14005. Useful for tooling.
  14006. @return {Promise}
  14007. */
  14008. then: function(onFulfillment, onRejection) {
  14009. var parent = this;
  14010. var state = parent._state;
  14011. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  14012. return this;
  14013. }
  14014. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  14015. var result = parent._result;
  14016. if (state) {
  14017. var callback = arguments[state - 1];
  14018. lib$es6$promise$asap$$asap(function(){
  14019. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  14020. });
  14021. } else {
  14022. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  14023. }
  14024. return child;
  14025. },
  14026. /**
  14027. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  14028. as the catch block of a try/catch statement.
  14029. ```js
  14030. function findAuthor(){
  14031. throw new Error('couldn't find that author');
  14032. }
  14033. // synchronous
  14034. try {
  14035. findAuthor();
  14036. } catch(reason) {
  14037. // something went wrong
  14038. }
  14039. // async with promises
  14040. findAuthor().catch(function(reason){
  14041. // something went wrong
  14042. });
  14043. ```
  14044. @method catch
  14045. @param {Function} onRejection
  14046. Useful for tooling.
  14047. @return {Promise}
  14048. */
  14049. 'catch': function(onRejection) {
  14050. return this.then(null, onRejection);
  14051. }
  14052. };
  14053. function lib$es6$promise$polyfill$$polyfill() {
  14054. var local;
  14055. if (typeof global !== 'undefined') {
  14056. local = global;
  14057. } else if (typeof self !== 'undefined') {
  14058. local = self;
  14059. } else {
  14060. try {
  14061. local = Function('return this')();
  14062. } catch (e) {
  14063. throw new Error('polyfill failed because global object is unavailable in this environment');
  14064. }
  14065. }
  14066. var P = local.Promise;
  14067. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  14068. return;
  14069. }
  14070. local.Promise = lib$es6$promise$promise$$default;
  14071. }
  14072. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  14073. var lib$es6$promise$umd$$ES6Promise = {
  14074. 'Promise': lib$es6$promise$promise$$default,
  14075. 'polyfill': lib$es6$promise$polyfill$$default
  14076. };
  14077. /* global define:true module:true window: true */
  14078. if (typeof define === 'function' && define['amd']) {
  14079. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  14080. } else if (typeof module !== 'undefined' && module['exports']) {
  14081. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  14082. } else if (typeof this !== 'undefined') {
  14083. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  14084. }
  14085. lib$es6$promise$polyfill$$default();
  14086. }).call(this);
  14087. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14088. },{"_process":46}],48:[function(require,module,exports){
  14089. /* Copyright @ 2015 Atlassian Pty Ltd
  14090. *
  14091. * Licensed under the Apache License, Version 2.0 (the "License");
  14092. * you may not use this file except in compliance with the License.
  14093. * You may obtain a copy of the License at
  14094. *
  14095. * http://www.apache.org/licenses/LICENSE-2.0
  14096. *
  14097. * Unless required by applicable law or agreed to in writing, software
  14098. * distributed under the License is distributed on an "AS IS" BASIS,
  14099. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14100. * See the License for the specific language governing permissions and
  14101. * limitations under the License.
  14102. */
  14103. /**
  14104. * Ordered log levels.
  14105. */
  14106. var levels = {
  14107. "trace": 0,
  14108. "debug": 1,
  14109. "info": 2,
  14110. "log": 3,
  14111. "warn": 4,
  14112. "error": 5
  14113. };
  14114. /**
  14115. * Parses Error's object stack trace and extracts information about the last
  14116. * caller before the log method was called.
  14117. * @returns JS object with info about the caller - method name, file location,
  14118. * line and column.
  14119. */
  14120. function getCallerInfo() {
  14121. var callerInfo = {
  14122. methodName: "",
  14123. fileLocation: "",
  14124. line: null,
  14125. column: null
  14126. };
  14127. //gets the part of the stack without the logger wrappers
  14128. var error = new Error();
  14129. var stack = error.stack? error.stack.split("\n") : [];
  14130. if(!stack || stack.length < 1) {
  14131. return callerInfo;
  14132. }
  14133. var m = null;
  14134. if(stack[3]) {
  14135. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  14136. }
  14137. if(!m || m.length <= 4) {
  14138. //Firefox && Safari
  14139. if(stack[2].indexOf("log@") === 0){
  14140. //Safari
  14141. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  14142. } else {
  14143. //Firefox
  14144. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  14145. }
  14146. return callerInfo;
  14147. }
  14148. callerInfo.methodName = m[1];
  14149. callerInfo.fileLocation = m[2];
  14150. callerInfo.line = m[3];
  14151. callerInfo.column = m[4];
  14152. return callerInfo;
  14153. }
  14154. /**
  14155. * Logs messages using the transports and level from the logger.
  14156. * @param logger a logger instance.
  14157. * @param level the log level of the message. See the levels variable.
  14158. * @param arguments array with arguments that will be logged.
  14159. */
  14160. function log() {
  14161. var logger = arguments[0], level = arguments[1],
  14162. args = Array.prototype.slice.call(arguments, 2);
  14163. if(levels[level] <= logger.level) {
  14164. return;
  14165. }
  14166. var callerInfo = getCallerInfo();
  14167. for(var i = 0; i < logger.transports.length; i++) {
  14168. var t = logger.transports[i];
  14169. var l = t[level];
  14170. if(l && typeof(l) === "function") {
  14171. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  14172. .apply(t, args);
  14173. }
  14174. }
  14175. }
  14176. /**
  14177. *
  14178. * Constructs new logger object.
  14179. * @param level the logging level for the new logger
  14180. * @param id optional identifier for the logger instance.
  14181. * @param transports optional list of handlers(objects) for the logs.
  14182. * The handlers must support - log, warn, error, debug, info, trace.
  14183. * @param format optional (NOT implemented) string.
  14184. */
  14185. function Logger(level, id, transports, format) {
  14186. this.id = id;
  14187. this.format = format;
  14188. if(!this.transports) {
  14189. this.transports = [];
  14190. this.transports.push(Logger.consoleTransport);
  14191. }
  14192. this.level = levels[level];
  14193. var methods = Object.keys(levels);
  14194. for(var i = 0; i < methods.length; i++){
  14195. this[methods[i]] =
  14196. log.bind(null, this, methods[i]);
  14197. }
  14198. }
  14199. /**
  14200. * Sets the log level for the logger.
  14201. * @param level the new log level.
  14202. */
  14203. Logger.prototype.setLevel = function (level) {
  14204. this.level = levels[level];
  14205. };
  14206. module.exports = Logger;
  14207. /**
  14208. * The default transport - console
  14209. */
  14210. Logger.consoleTransport = console;
  14211. /**
  14212. * Enum for the supported log levels.
  14213. */
  14214. Logger.levels = {
  14215. TRACE: "trace",
  14216. DEBUG: "debug",
  14217. INFO: "info",
  14218. LOG: "log",
  14219. WARN: "warn",
  14220. ERROR: "error"
  14221. };
  14222. },{}],49:[function(require,module,exports){
  14223. /* Copyright @ 2015 Atlassian Pty Ltd
  14224. *
  14225. * Licensed under the Apache License, Version 2.0 (the "License");
  14226. * you may not use this file except in compliance with the License.
  14227. * You may obtain a copy of the License at
  14228. *
  14229. * http://www.apache.org/licenses/LICENSE-2.0
  14230. *
  14231. * Unless required by applicable law or agreed to in writing, software
  14232. * distributed under the License is distributed on an "AS IS" BASIS,
  14233. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14234. * See the License for the specific language governing permissions and
  14235. * limitations under the License.
  14236. */
  14237. var Logger = require("./Logger");
  14238. /**
  14239. * Map with the created loggers with ID.
  14240. */
  14241. var idLoggers = {};
  14242. /**
  14243. * Array with the loggers without id.
  14244. */
  14245. var loggers = [];
  14246. /**
  14247. * Log level for the lbrary.
  14248. */
  14249. var curLevel = Logger.levels.TRACE;
  14250. module.exports = {
  14251. /**
  14252. * Creates new logger.
  14253. * @arguments the same as Logger constructor
  14254. */
  14255. getLogger: function(id, transports, format) {
  14256. var logger = new Logger(curLevel, id, transports, format);
  14257. if(id) {
  14258. idLoggers[id] = idLoggers[id] || [];
  14259. idLoggers[id].push(logger);
  14260. } else {
  14261. loggers.push(logger);
  14262. }
  14263. return logger;
  14264. },
  14265. /**
  14266. * Changes the log level for the existing loggers by id.
  14267. * @param level the new log level.
  14268. * @param id if specified the level will be changed only for loggers with the
  14269. * same id. Otherwise the operation will affect all loggers that don't
  14270. * have id.
  14271. */
  14272. setLogLevelById: function(level, id) {
  14273. var l = id? (idLoggers[id] || []) : loggers;
  14274. for(var i = 0; i < l.length; i++) {
  14275. l[i].setLevel(level);
  14276. }
  14277. },
  14278. /**
  14279. * Changes the log level for all existing loggers.
  14280. * @param level the new log level.
  14281. */
  14282. setLogLevel: function (level) {
  14283. curLevel = level;
  14284. var i = 0;
  14285. for(; i < loggers.length; i++) {
  14286. loggers[i].setLevel(level);
  14287. }
  14288. for(var id in idLoggers) {
  14289. var l = idLoggers[id] || [];
  14290. for(i = 0; i < l.length; i++) {
  14291. l[i].setLevel(level);
  14292. }
  14293. }
  14294. },
  14295. /**
  14296. * The supported log levels.
  14297. */
  14298. levels: Logger.levels
  14299. };
  14300. },{"./Logger":48}],50:[function(require,module,exports){
  14301. /*
  14302. A JavaScript implementation of the SHA family of hashes, as
  14303. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  14304. as defined in FIPS PUB 198a
  14305. Copyright Brian Turek 2008-2013
  14306. Distributed under the BSD License
  14307. See http://caligatio.github.com/jsSHA/ for more information
  14308. Several functions taken from Paul Johnston
  14309. */
  14310. (function(T){function z(a,c,b){var g=0,f=[0],h="",l=null,h=b||"UTF8";if("UTF8"!==h&&"UTF16"!==h)throw"encoding must be UTF8 or UTF16";if("HEX"===c){if(0!==a.length%2)throw"srcString of HEX type must be in byte increments";l=B(a);g=l.binLen;f=l.value}else if("ASCII"===c||"TEXT"===c)l=J(a,h),g=l.binLen,f=l.value;else if("B64"===c)l=K(a),g=l.binLen,f=l.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";this.getHash=function(a,c,b,h){var l=null,d=f.slice(),n=g,p;3===arguments.length?"number"!==
  14311. typeof b&&(h=b,b=1):2===arguments.length&&(b=1);if(b!==parseInt(b,10)||1>b)throw"numRounds must a integer >= 1";switch(c){case "HEX":l=L;break;case "B64":l=M;break;default:throw"format must be HEX or B64";}if("SHA-1"===a)for(p=0;p<b;p++)d=y(d,n),n=160;else if("SHA-224"===a)for(p=0;p<b;p++)d=v(d,n,a),n=224;else if("SHA-256"===a)for(p=0;p<b;p++)d=v(d,n,a),n=256;else if("SHA-384"===a)for(p=0;p<b;p++)d=v(d,n,a),n=384;else if("SHA-512"===a)for(p=0;p<b;p++)d=v(d,n,a),n=512;else throw"Chosen SHA variant is not supported";
  14312. return l(d,N(h))};this.getHMAC=function(a,b,c,l,s){var d,n,p,m,w=[],x=[];d=null;switch(l){case "HEX":l=L;break;case "B64":l=M;break;default:throw"outputFormat must be HEX or B64";}if("SHA-1"===c)n=64,m=160;else if("SHA-224"===c)n=64,m=224;else if("SHA-256"===c)n=64,m=256;else if("SHA-384"===c)n=128,m=384;else if("SHA-512"===c)n=128,m=512;else throw"Chosen SHA variant is not supported";if("HEX"===b)d=B(a),p=d.binLen,d=d.value;else if("ASCII"===b||"TEXT"===b)d=J(a,h),p=d.binLen,d=d.value;else if("B64"===
  14313. b)d=K(a),p=d.binLen,d=d.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";a=8*n;b=n/4-1;n<p/8?(d="SHA-1"===c?y(d,p):v(d,p,c),d[b]&=4294967040):n>p/8&&(d[b]&=4294967040);for(n=0;n<=b;n+=1)w[n]=d[n]^909522486,x[n]=d[n]^1549556828;c="SHA-1"===c?y(x.concat(y(w.concat(f),a+g)),a+m):v(x.concat(v(w.concat(f),a+g,c)),a+m,c);return l(c,N(s))}}function s(a,c){this.a=a;this.b=c}function J(a,c){var b=[],g,f=[],h=0,l;if("UTF8"===c)for(l=0;l<a.length;l+=1)for(g=a.charCodeAt(l),f=[],2048<g?(f[0]=224|
  14314. (g&61440)>>>12,f[1]=128|(g&4032)>>>6,f[2]=128|g&63):128<g?(f[0]=192|(g&1984)>>>6,f[1]=128|g&63):f[0]=g,g=0;g<f.length;g+=1)b[h>>>2]|=f[g]<<24-h%4*8,h+=1;else if("UTF16"===c)for(l=0;l<a.length;l+=1)b[h>>>2]|=a.charCodeAt(l)<<16-h%4*8,h+=2;return{value:b,binLen:8*h}}function B(a){var c=[],b=a.length,g,f;if(0!==b%2)throw"String of HEX type must be in byte increments";for(g=0;g<b;g+=2){f=parseInt(a.substr(g,2),16);if(isNaN(f))throw"String of HEX type contains invalid characters";c[g>>>3]|=f<<24-g%8*4}return{value:c,
  14315. binLen:4*b}}function K(a){var c=[],b=0,g,f,h,l,r;if(-1===a.search(/^[a-zA-Z0-9=+\/]+$/))throw"Invalid character in base-64 string";g=a.indexOf("=");a=a.replace(/\=/g,"");if(-1!==g&&g<a.length)throw"Invalid '=' found in base-64 string";for(f=0;f<a.length;f+=4){r=a.substr(f,4);for(h=l=0;h<r.length;h+=1)g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(r[h]),l|=g<<18-6*h;for(h=0;h<r.length-1;h+=1)c[b>>2]|=(l>>>16-8*h&255)<<24-b%4*8,b+=1}return{value:c,binLen:8*b}}function L(a,
  14316. c){var b="",g=4*a.length,f,h;for(f=0;f<g;f+=1)h=a[f>>>2]>>>8*(3-f%4),b+="0123456789abcdef".charAt(h>>>4&15)+"0123456789abcdef".charAt(h&15);return c.outputUpper?b.toUpperCase():b}function M(a,c){var b="",g=4*a.length,f,h,l;for(f=0;f<g;f+=3)for(l=(a[f>>>2]>>>8*(3-f%4)&255)<<16|(a[f+1>>>2]>>>8*(3-(f+1)%4)&255)<<8|a[f+2>>>2]>>>8*(3-(f+2)%4)&255,h=0;4>h;h+=1)b=8*f+6*h<=32*a.length?b+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(l>>>6*(3-h)&63):b+c.b64Pad;return b}function N(a){var c=
  14317. {outputUpper:!1,b64Pad:"="};try{a.hasOwnProperty("outputUpper")&&(c.outputUpper=a.outputUpper),a.hasOwnProperty("b64Pad")&&(c.b64Pad=a.b64Pad)}catch(b){}if("boolean"!==typeof c.outputUpper)throw"Invalid outputUpper formatting option";if("string"!==typeof c.b64Pad)throw"Invalid b64Pad formatting option";return c}function U(a,c){return a<<c|a>>>32-c}function u(a,c){return a>>>c|a<<32-c}function t(a,c){var b=null,b=new s(a.a,a.b);return b=32>=c?new s(b.a>>>c|b.b<<32-c&4294967295,b.b>>>c|b.a<<32-c&4294967295):
  14318. new s(b.b>>>c-32|b.a<<64-c&4294967295,b.a>>>c-32|b.b<<64-c&4294967295)}function O(a,c){var b=null;return b=32>=c?new s(a.a>>>c,a.b>>>c|a.a<<32-c&4294967295):new s(0,a.a>>>c-32)}function V(a,c,b){return a^c^b}function P(a,c,b){return a&c^~a&b}function W(a,c,b){return new s(a.a&c.a^~a.a&b.a,a.b&c.b^~a.b&b.b)}function Q(a,c,b){return a&c^a&b^c&b}function X(a,c,b){return new s(a.a&c.a^a.a&b.a^c.a&b.a,a.b&c.b^a.b&b.b^c.b&b.b)}function Y(a){return u(a,2)^u(a,13)^u(a,22)}function Z(a){var c=t(a,28),b=t(a,
  14319. 34);a=t(a,39);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function $(a){return u(a,6)^u(a,11)^u(a,25)}function aa(a){var c=t(a,14),b=t(a,18);a=t(a,41);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function ba(a){return u(a,7)^u(a,18)^a>>>3}function ca(a){var c=t(a,1),b=t(a,8);a=O(a,7);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function da(a){return u(a,17)^u(a,19)^a>>>10}function ea(a){var c=t(a,19),b=t(a,61);a=O(a,6);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function R(a,c){var b=(a&65535)+(c&65535);return((a>>>16)+(c>>>
  14320. 16)+(b>>>16)&65535)<<16|b&65535}function fa(a,c,b,g){var f=(a&65535)+(c&65535)+(b&65535)+(g&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)&65535)<<16|f&65535}function S(a,c,b,g,f){var h=(a&65535)+(c&65535)+(b&65535)+(g&65535)+(f&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)+(h>>>16)&65535)<<16|h&65535}function ga(a,c){var b,g,f;b=(a.b&65535)+(c.b&65535);g=(a.b>>>16)+(c.b>>>16)+(b>>>16);f=(g&65535)<<16|b&65535;b=(a.a&65535)+(c.a&65535)+(g>>>16);g=(a.a>>>16)+(c.a>>>16)+(b>>>
  14321. 16);return new s((g&65535)<<16|b&65535,f)}function ha(a,c,b,g){var f,h,l;f=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535);h=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f>>>16);l=(h&65535)<<16|f&65535;f=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(h>>>16);h=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f>>>16);return new s((h&65535)<<16|f&65535,l)}function ia(a,c,b,g,f){var h,l,r;h=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535)+(f.b&65535);l=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f.b>>>
  14322. 16)+(h>>>16);r=(l&65535)<<16|h&65535;h=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(f.a&65535)+(l>>>16);l=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f.a>>>16)+(h>>>16);return new s((l&65535)<<16|h&65535,r)}function y(a,c){var b=[],g,f,h,l,r,s,u=P,t=V,v=Q,d=U,n=R,p,m,w=S,x,q=[1732584193,4023233417,2562383102,271733878,3285377520];a[c>>>5]|=128<<24-c%32;a[(c+65>>>9<<4)+15]=c;x=a.length;for(p=0;p<x;p+=16){g=q[0];f=q[1];h=q[2];l=q[3];r=q[4];for(m=0;80>m;m+=1)b[m]=16>m?a[m+p]:d(b[m-3]^b[m-8]^b[m-
  14323. 14]^b[m-16],1),s=20>m?w(d(g,5),u(f,h,l),r,1518500249,b[m]):40>m?w(d(g,5),t(f,h,l),r,1859775393,b[m]):60>m?w(d(g,5),v(f,h,l),r,2400959708,b[m]):w(d(g,5),t(f,h,l),r,3395469782,b[m]),r=l,l=h,h=d(f,30),f=g,g=s;q[0]=n(g,q[0]);q[1]=n(f,q[1]);q[2]=n(h,q[2]);q[3]=n(l,q[3]);q[4]=n(r,q[4])}return q}function v(a,c,b){var g,f,h,l,r,t,u,v,z,d,n,p,m,w,x,q,y,C,D,E,F,G,H,I,e,A=[],B,k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,
  14324. 1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,
  14325. 2361852424,2428436474,2756734187,3204031479,3329325298];d=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428];f=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];if("SHA-224"===b||"SHA-256"===b)n=64,g=(c+65>>>9<<4)+15,w=16,x=1,e=Number,q=R,y=fa,C=S,D=ba,E=da,F=Y,G=$,I=Q,H=P,d="SHA-224"===b?d:f;else if("SHA-384"===b||"SHA-512"===b)n=80,g=(c+128>>>10<<5)+31,w=32,x=2,e=s,q=ga,y=ha,C=ia,D=ca,E=ea,F=Z,G=aa,I=X,H=W,k=[new e(k[0],
  14326. 3609767458),new e(k[1],602891725),new e(k[2],3964484399),new e(k[3],2173295548),new e(k[4],4081628472),new e(k[5],3053834265),new e(k[6],2937671579),new e(k[7],3664609560),new e(k[8],2734883394),new e(k[9],1164996542),new e(k[10],1323610764),new e(k[11],3590304994),new e(k[12],4068182383),new e(k[13],991336113),new e(k[14],633803317),new e(k[15],3479774868),new e(k[16],2666613458),new e(k[17],944711139),new e(k[18],2341262773),new e(k[19],2007800933),new e(k[20],1495990901),new e(k[21],1856431235),
  14327. new e(k[22],3175218132),new e(k[23],2198950837),new e(k[24],3999719339),new e(k[25],766784016),new e(k[26],2566594879),new e(k[27],3203337956),new e(k[28],1034457026),new e(k[29],2466948901),new e(k[30],3758326383),new e(k[31],168717936),new e(k[32],1188179964),new e(k[33],1546045734),new e(k[34],1522805485),new e(k[35],2643833823),new e(k[36],2343527390),new e(k[37],1014477480),new e(k[38],1206759142),new e(k[39],344077627),new e(k[40],1290863460),new e(k[41],3158454273),new e(k[42],3505952657),
  14328. new e(k[43],106217008),new e(k[44],3606008344),new e(k[45],1432725776),new e(k[46],1467031594),new e(k[47],851169720),new e(k[48],3100823752),new e(k[49],1363258195),new e(k[50],3750685593),new e(k[51],3785050280),new e(k[52],3318307427),new e(k[53],3812723403),new e(k[54],2003034995),new e(k[55],3602036899),new e(k[56],1575990012),new e(k[57],1125592928),new e(k[58],2716904306),new e(k[59],442776044),new e(k[60],593698344),new e(k[61],3733110249),new e(k[62],2999351573),new e(k[63],3815920427),new e(3391569614,
  14329. 3928383900),new e(3515267271,566280711),new e(3940187606,3454069534),new e(4118630271,4000239992),new e(116418474,1914138554),new e(174292421,2731055270),new e(289380356,3203993006),new e(460393269,320620315),new e(685471733,587496836),new e(852142971,1086792851),new e(1017036298,365543100),new e(1126000580,2618297676),new e(1288033470,3409855158),new e(1501505948,4234509866),new e(1607167915,987167468),new e(1816402316,1246189591)],d="SHA-384"===b?[new e(3418070365,d[0]),new e(1654270250,d[1]),new e(2438529370,
  14330. d[2]),new e(355462360,d[3]),new e(1731405415,d[4]),new e(41048885895,d[5]),new e(3675008525,d[6]),new e(1203062813,d[7])]:[new e(f[0],4089235720),new e(f[1],2227873595),new e(f[2],4271175723),new e(f[3],1595750129),new e(f[4],2917565137),new e(f[5],725511199),new e(f[6],4215389547),new e(f[7],327033209)];else throw"Unexpected error in SHA-2 implementation";a[c>>>5]|=128<<24-c%32;a[g]=c;B=a.length;for(p=0;p<B;p+=w){c=d[0];g=d[1];f=d[2];h=d[3];l=d[4];r=d[5];t=d[6];u=d[7];for(m=0;m<n;m+=1)A[m]=16>m?
  14331. new e(a[m*x+p],a[m*x+p+1]):y(E(A[m-2]),A[m-7],D(A[m-15]),A[m-16]),v=C(u,G(l),H(l,r,t),k[m],A[m]),z=q(F(c),I(c,g,f)),u=t,t=r,r=l,l=q(h,v),h=f,f=g,g=c,c=q(v,z);d[0]=q(c,d[0]);d[1]=q(g,d[1]);d[2]=q(f,d[2]);d[3]=q(h,d[3]);d[4]=q(l,d[4]);d[5]=q(r,d[5]);d[6]=q(t,d[6]);d[7]=q(u,d[7])}if("SHA-224"===b)a=[d[0],d[1],d[2],d[3],d[4],d[5],d[6]];else if("SHA-256"===b)a=d;else if("SHA-384"===b)a=[d[0].a,d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b];else if("SHA-512"===b)a=[d[0].a,
  14332. d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b,d[6].a,d[6].b,d[7].a,d[7].b];else throw"Unexpected error in SHA-2 implementation";return a}"function"===typeof define&&typeof define.amd?define(function(){return z}):"undefined"!==typeof exports?"undefined"!==typeof module&&module.exports?module.exports=exports=z:exports=z:T.jsSHA=z})(this);
  14333. },{}],51:[function(require,module,exports){
  14334. // Top level file is just a mixin of submodules & constants
  14335. 'use strict';
  14336. var assign = require('./lib/utils/common').assign;
  14337. var deflate = require('./lib/deflate');
  14338. var inflate = require('./lib/inflate');
  14339. var constants = require('./lib/zlib/constants');
  14340. var pako = {};
  14341. assign(pako, deflate, inflate, constants);
  14342. module.exports = pako;
  14343. },{"./lib/deflate":52,"./lib/inflate":53,"./lib/utils/common":54,"./lib/zlib/constants":57}],52:[function(require,module,exports){
  14344. 'use strict';
  14345. var zlib_deflate = require('./zlib/deflate.js');
  14346. var utils = require('./utils/common');
  14347. var strings = require('./utils/strings');
  14348. var msg = require('./zlib/messages');
  14349. var zstream = require('./zlib/zstream');
  14350. var toString = Object.prototype.toString;
  14351. /* Public constants ==========================================================*/
  14352. /* ===========================================================================*/
  14353. var Z_NO_FLUSH = 0;
  14354. var Z_FINISH = 4;
  14355. var Z_OK = 0;
  14356. var Z_STREAM_END = 1;
  14357. var Z_SYNC_FLUSH = 2;
  14358. var Z_DEFAULT_COMPRESSION = -1;
  14359. var Z_DEFAULT_STRATEGY = 0;
  14360. var Z_DEFLATED = 8;
  14361. /* ===========================================================================*/
  14362. /**
  14363. * class Deflate
  14364. *
  14365. * Generic JS-style wrapper for zlib calls. If you don't need
  14366. * streaming behaviour - use more simple functions: [[deflate]],
  14367. * [[deflateRaw]] and [[gzip]].
  14368. **/
  14369. /* internal
  14370. * Deflate.chunks -> Array
  14371. *
  14372. * Chunks of output data, if [[Deflate#onData]] not overriden.
  14373. **/
  14374. /**
  14375. * Deflate.result -> Uint8Array|Array
  14376. *
  14377. * Compressed result, generated by default [[Deflate#onData]]
  14378. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  14379. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  14380. * push a chunk with explicit flush (call [[Deflate#push]] with
  14381. * `Z_SYNC_FLUSH` param).
  14382. **/
  14383. /**
  14384. * Deflate.err -> Number
  14385. *
  14386. * Error code after deflate finished. 0 (Z_OK) on success.
  14387. * You will not need it in real life, because deflate errors
  14388. * are possible only on wrong options or bad `onData` / `onEnd`
  14389. * custom handlers.
  14390. **/
  14391. /**
  14392. * Deflate.msg -> String
  14393. *
  14394. * Error message, if [[Deflate.err]] != 0
  14395. **/
  14396. /**
  14397. * new Deflate(options)
  14398. * - options (Object): zlib deflate options.
  14399. *
  14400. * Creates new deflator instance with specified params. Throws exception
  14401. * on bad params. Supported options:
  14402. *
  14403. * - `level`
  14404. * - `windowBits`
  14405. * - `memLevel`
  14406. * - `strategy`
  14407. *
  14408. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14409. * for more information on these.
  14410. *
  14411. * Additional options, for internal needs:
  14412. *
  14413. * - `chunkSize` - size of generated data chunks (16K by default)
  14414. * - `raw` (Boolean) - do raw deflate
  14415. * - `gzip` (Boolean) - create gzip wrapper
  14416. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14417. * (each char code [0..255])
  14418. * - `header` (Object) - custom header for gzip
  14419. * - `text` (Boolean) - true if compressed data believed to be text
  14420. * - `time` (Number) - modification time, unix timestamp
  14421. * - `os` (Number) - operation system code
  14422. * - `extra` (Array) - array of bytes with extra data (max 65536)
  14423. * - `name` (String) - file name (binary string)
  14424. * - `comment` (String) - comment (binary string)
  14425. * - `hcrc` (Boolean) - true if header crc should be added
  14426. *
  14427. * ##### Example:
  14428. *
  14429. * ```javascript
  14430. * var pako = require('pako')
  14431. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14432. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14433. *
  14434. * var deflate = new pako.Deflate({ level: 3});
  14435. *
  14436. * deflate.push(chunk1, false);
  14437. * deflate.push(chunk2, true); // true -> last chunk
  14438. *
  14439. * if (deflate.err) { throw new Error(deflate.err); }
  14440. *
  14441. * console.log(deflate.result);
  14442. * ```
  14443. **/
  14444. var Deflate = function(options) {
  14445. this.options = utils.assign({
  14446. level: Z_DEFAULT_COMPRESSION,
  14447. method: Z_DEFLATED,
  14448. chunkSize: 16384,
  14449. windowBits: 15,
  14450. memLevel: 8,
  14451. strategy: Z_DEFAULT_STRATEGY,
  14452. to: ''
  14453. }, options || {});
  14454. var opt = this.options;
  14455. if (opt.raw && (opt.windowBits > 0)) {
  14456. opt.windowBits = -opt.windowBits;
  14457. }
  14458. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  14459. opt.windowBits += 16;
  14460. }
  14461. this.err = 0; // error code, if happens (0 = Z_OK)
  14462. this.msg = ''; // error message
  14463. this.ended = false; // used to avoid multiple onEnd() calls
  14464. this.chunks = []; // chunks of compressed data
  14465. this.strm = new zstream();
  14466. this.strm.avail_out = 0;
  14467. var status = zlib_deflate.deflateInit2(
  14468. this.strm,
  14469. opt.level,
  14470. opt.method,
  14471. opt.windowBits,
  14472. opt.memLevel,
  14473. opt.strategy
  14474. );
  14475. if (status !== Z_OK) {
  14476. throw new Error(msg[status]);
  14477. }
  14478. if (opt.header) {
  14479. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  14480. }
  14481. };
  14482. /**
  14483. * Deflate#push(data[, mode]) -> Boolean
  14484. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  14485. * converted to utf8 byte sequence.
  14486. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14487. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14488. *
  14489. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  14490. * new compressed chunks. Returns `true` on success. The last data block must have
  14491. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  14492. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  14493. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  14494. *
  14495. * On fail call [[Deflate#onEnd]] with error code and return false.
  14496. *
  14497. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14498. * array format is detected automatically). Also, don't skip last param and always
  14499. * use the same type in your code (boolean or number). That will improve JS speed.
  14500. *
  14501. * For regular `Array`-s make sure all elements are [0..255].
  14502. *
  14503. * ##### Example
  14504. *
  14505. * ```javascript
  14506. * push(chunk, false); // push one of data chunks
  14507. * ...
  14508. * push(chunk, true); // push last chunk
  14509. * ```
  14510. **/
  14511. Deflate.prototype.push = function(data, mode) {
  14512. var strm = this.strm;
  14513. var chunkSize = this.options.chunkSize;
  14514. var status, _mode;
  14515. if (this.ended) { return false; }
  14516. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  14517. // Convert data if needed
  14518. if (typeof data === 'string') {
  14519. // If we need to compress text, change encoding to utf8.
  14520. strm.input = strings.string2buf(data);
  14521. } else if (toString.call(data) === '[object ArrayBuffer]') {
  14522. strm.input = new Uint8Array(data);
  14523. } else {
  14524. strm.input = data;
  14525. }
  14526. strm.next_in = 0;
  14527. strm.avail_in = strm.input.length;
  14528. do {
  14529. if (strm.avail_out === 0) {
  14530. strm.output = new utils.Buf8(chunkSize);
  14531. strm.next_out = 0;
  14532. strm.avail_out = chunkSize;
  14533. }
  14534. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  14535. if (status !== Z_STREAM_END && status !== Z_OK) {
  14536. this.onEnd(status);
  14537. this.ended = true;
  14538. return false;
  14539. }
  14540. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  14541. if (this.options.to === 'string') {
  14542. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  14543. } else {
  14544. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14545. }
  14546. }
  14547. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  14548. // Finalize on the last chunk.
  14549. if (_mode === Z_FINISH) {
  14550. status = zlib_deflate.deflateEnd(this.strm);
  14551. this.onEnd(status);
  14552. this.ended = true;
  14553. return status === Z_OK;
  14554. }
  14555. // callback interim results if Z_SYNC_FLUSH.
  14556. if (_mode === Z_SYNC_FLUSH) {
  14557. this.onEnd(Z_OK);
  14558. strm.avail_out = 0;
  14559. return true;
  14560. }
  14561. return true;
  14562. };
  14563. /**
  14564. * Deflate#onData(chunk) -> Void
  14565. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14566. * on js engine support. When string output requested, each chunk
  14567. * will be string.
  14568. *
  14569. * By default, stores data blocks in `chunks[]` property and glue
  14570. * those in `onEnd`. Override this handler, if you need another behaviour.
  14571. **/
  14572. Deflate.prototype.onData = function(chunk) {
  14573. this.chunks.push(chunk);
  14574. };
  14575. /**
  14576. * Deflate#onEnd(status) -> Void
  14577. * - status (Number): deflate status. 0 (Z_OK) on success,
  14578. * other if not.
  14579. *
  14580. * Called once after you tell deflate that the input stream is
  14581. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14582. * or if an error happened. By default - join collected chunks,
  14583. * free memory and fill `results` / `err` properties.
  14584. **/
  14585. Deflate.prototype.onEnd = function(status) {
  14586. // On success - join
  14587. if (status === Z_OK) {
  14588. if (this.options.to === 'string') {
  14589. this.result = this.chunks.join('');
  14590. } else {
  14591. this.result = utils.flattenChunks(this.chunks);
  14592. }
  14593. }
  14594. this.chunks = [];
  14595. this.err = status;
  14596. this.msg = this.strm.msg;
  14597. };
  14598. /**
  14599. * deflate(data[, options]) -> Uint8Array|Array|String
  14600. * - data (Uint8Array|Array|String): input data to compress.
  14601. * - options (Object): zlib deflate options.
  14602. *
  14603. * Compress `data` with deflate alrorythm and `options`.
  14604. *
  14605. * Supported options are:
  14606. *
  14607. * - level
  14608. * - windowBits
  14609. * - memLevel
  14610. * - strategy
  14611. *
  14612. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14613. * for more information on these.
  14614. *
  14615. * Sugar (options):
  14616. *
  14617. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14618. * negative windowBits implicitly.
  14619. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14620. * (each char code [0..255])
  14621. *
  14622. * ##### Example:
  14623. *
  14624. * ```javascript
  14625. * var pako = require('pako')
  14626. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  14627. *
  14628. * console.log(pako.deflate(data));
  14629. * ```
  14630. **/
  14631. function deflate(input, options) {
  14632. var deflator = new Deflate(options);
  14633. deflator.push(input, true);
  14634. // That will never happens, if you don't cheat with options :)
  14635. if (deflator.err) { throw deflator.msg; }
  14636. return deflator.result;
  14637. }
  14638. /**
  14639. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  14640. * - data (Uint8Array|Array|String): input data to compress.
  14641. * - options (Object): zlib deflate options.
  14642. *
  14643. * The same as [[deflate]], but creates raw data, without wrapper
  14644. * (header and adler32 crc).
  14645. **/
  14646. function deflateRaw(input, options) {
  14647. options = options || {};
  14648. options.raw = true;
  14649. return deflate(input, options);
  14650. }
  14651. /**
  14652. * gzip(data[, options]) -> Uint8Array|Array|String
  14653. * - data (Uint8Array|Array|String): input data to compress.
  14654. * - options (Object): zlib deflate options.
  14655. *
  14656. * The same as [[deflate]], but create gzip wrapper instead of
  14657. * deflate one.
  14658. **/
  14659. function gzip(input, options) {
  14660. options = options || {};
  14661. options.gzip = true;
  14662. return deflate(input, options);
  14663. }
  14664. exports.Deflate = Deflate;
  14665. exports.deflate = deflate;
  14666. exports.deflateRaw = deflateRaw;
  14667. exports.gzip = gzip;
  14668. },{"./utils/common":54,"./utils/strings":55,"./zlib/deflate.js":59,"./zlib/messages":64,"./zlib/zstream":66}],53:[function(require,module,exports){
  14669. 'use strict';
  14670. var zlib_inflate = require('./zlib/inflate.js');
  14671. var utils = require('./utils/common');
  14672. var strings = require('./utils/strings');
  14673. var c = require('./zlib/constants');
  14674. var msg = require('./zlib/messages');
  14675. var zstream = require('./zlib/zstream');
  14676. var gzheader = require('./zlib/gzheader');
  14677. var toString = Object.prototype.toString;
  14678. /**
  14679. * class Inflate
  14680. *
  14681. * Generic JS-style wrapper for zlib calls. If you don't need
  14682. * streaming behaviour - use more simple functions: [[inflate]]
  14683. * and [[inflateRaw]].
  14684. **/
  14685. /* internal
  14686. * inflate.chunks -> Array
  14687. *
  14688. * Chunks of output data, if [[Inflate#onData]] not overriden.
  14689. **/
  14690. /**
  14691. * Inflate.result -> Uint8Array|Array|String
  14692. *
  14693. * Uncompressed result, generated by default [[Inflate#onData]]
  14694. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  14695. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  14696. * push a chunk with explicit flush (call [[Inflate#push]] with
  14697. * `Z_SYNC_FLUSH` param).
  14698. **/
  14699. /**
  14700. * Inflate.err -> Number
  14701. *
  14702. * Error code after inflate finished. 0 (Z_OK) on success.
  14703. * Should be checked if broken data possible.
  14704. **/
  14705. /**
  14706. * Inflate.msg -> String
  14707. *
  14708. * Error message, if [[Inflate.err]] != 0
  14709. **/
  14710. /**
  14711. * new Inflate(options)
  14712. * - options (Object): zlib inflate options.
  14713. *
  14714. * Creates new inflator instance with specified params. Throws exception
  14715. * on bad params. Supported options:
  14716. *
  14717. * - `windowBits`
  14718. *
  14719. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14720. * for more information on these.
  14721. *
  14722. * Additional options, for internal needs:
  14723. *
  14724. * - `chunkSize` - size of generated data chunks (16K by default)
  14725. * - `raw` (Boolean) - do raw inflate
  14726. * - `to` (String) - if equal to 'string', then result will be converted
  14727. * from utf8 to utf16 (javascript) string. When string output requested,
  14728. * chunk length can differ from `chunkSize`, depending on content.
  14729. *
  14730. * By default, when no options set, autodetect deflate/gzip data format via
  14731. * wrapper header.
  14732. *
  14733. * ##### Example:
  14734. *
  14735. * ```javascript
  14736. * var pako = require('pako')
  14737. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14738. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14739. *
  14740. * var inflate = new pako.Inflate({ level: 3});
  14741. *
  14742. * inflate.push(chunk1, false);
  14743. * inflate.push(chunk2, true); // true -> last chunk
  14744. *
  14745. * if (inflate.err) { throw new Error(inflate.err); }
  14746. *
  14747. * console.log(inflate.result);
  14748. * ```
  14749. **/
  14750. var Inflate = function(options) {
  14751. this.options = utils.assign({
  14752. chunkSize: 16384,
  14753. windowBits: 0,
  14754. to: ''
  14755. }, options || {});
  14756. var opt = this.options;
  14757. // Force window size for `raw` data, if not set directly,
  14758. // because we have no header for autodetect.
  14759. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  14760. opt.windowBits = -opt.windowBits;
  14761. if (opt.windowBits === 0) { opt.windowBits = -15; }
  14762. }
  14763. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  14764. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  14765. !(options && options.windowBits)) {
  14766. opt.windowBits += 32;
  14767. }
  14768. // Gzip header has no info about windows size, we can do autodetect only
  14769. // for deflate. So, if window size not set, force it to max when gzip possible
  14770. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  14771. // bit 3 (16) -> gzipped data
  14772. // bit 4 (32) -> autodetect gzip/deflate
  14773. if ((opt.windowBits & 15) === 0) {
  14774. opt.windowBits |= 15;
  14775. }
  14776. }
  14777. this.err = 0; // error code, if happens (0 = Z_OK)
  14778. this.msg = ''; // error message
  14779. this.ended = false; // used to avoid multiple onEnd() calls
  14780. this.chunks = []; // chunks of compressed data
  14781. this.strm = new zstream();
  14782. this.strm.avail_out = 0;
  14783. var status = zlib_inflate.inflateInit2(
  14784. this.strm,
  14785. opt.windowBits
  14786. );
  14787. if (status !== c.Z_OK) {
  14788. throw new Error(msg[status]);
  14789. }
  14790. this.header = new gzheader();
  14791. zlib_inflate.inflateGetHeader(this.strm, this.header);
  14792. };
  14793. /**
  14794. * Inflate#push(data[, mode]) -> Boolean
  14795. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  14796. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14797. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14798. *
  14799. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  14800. * new output chunks. Returns `true` on success. The last data block must have
  14801. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  14802. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  14803. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  14804. *
  14805. * On fail call [[Inflate#onEnd]] with error code and return false.
  14806. *
  14807. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14808. * format is detected automatically). Also, don't skip last param and always
  14809. * use the same type in your code (boolean or number). That will improve JS speed.
  14810. *
  14811. * For regular `Array`-s make sure all elements are [0..255].
  14812. *
  14813. * ##### Example
  14814. *
  14815. * ```javascript
  14816. * push(chunk, false); // push one of data chunks
  14817. * ...
  14818. * push(chunk, true); // push last chunk
  14819. * ```
  14820. **/
  14821. Inflate.prototype.push = function(data, mode) {
  14822. var strm = this.strm;
  14823. var chunkSize = this.options.chunkSize;
  14824. var status, _mode;
  14825. var next_out_utf8, tail, utf8str;
  14826. // Flag to properly process Z_BUF_ERROR on testing inflate call
  14827. // when we check that all output data was flushed.
  14828. var allowBufError = false;
  14829. if (this.ended) { return false; }
  14830. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  14831. // Convert data if needed
  14832. if (typeof data === 'string') {
  14833. // Only binary strings can be decompressed on practice
  14834. strm.input = strings.binstring2buf(data);
  14835. } else if (toString.call(data) === '[object ArrayBuffer]') {
  14836. strm.input = new Uint8Array(data);
  14837. } else {
  14838. strm.input = data;
  14839. }
  14840. strm.next_in = 0;
  14841. strm.avail_in = strm.input.length;
  14842. do {
  14843. if (strm.avail_out === 0) {
  14844. strm.output = new utils.Buf8(chunkSize);
  14845. strm.next_out = 0;
  14846. strm.avail_out = chunkSize;
  14847. }
  14848. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  14849. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  14850. status = c.Z_OK;
  14851. allowBufError = false;
  14852. }
  14853. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  14854. this.onEnd(status);
  14855. this.ended = true;
  14856. return false;
  14857. }
  14858. if (strm.next_out) {
  14859. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  14860. if (this.options.to === 'string') {
  14861. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  14862. tail = strm.next_out - next_out_utf8;
  14863. utf8str = strings.buf2string(strm.output, next_out_utf8);
  14864. // move tail
  14865. strm.next_out = tail;
  14866. strm.avail_out = chunkSize - tail;
  14867. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  14868. this.onData(utf8str);
  14869. } else {
  14870. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14871. }
  14872. }
  14873. }
  14874. // When no more input data, we should check that internal inflate buffers
  14875. // are flushed. The only way to do it when avail_out = 0 - run one more
  14876. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  14877. // Here we set flag to process this error properly.
  14878. //
  14879. // NOTE. Deflate does not return error in this case and does not needs such
  14880. // logic.
  14881. if (strm.avail_in === 0 && strm.avail_out === 0) {
  14882. allowBufError = true;
  14883. }
  14884. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  14885. if (status === c.Z_STREAM_END) {
  14886. _mode = c.Z_FINISH;
  14887. }
  14888. // Finalize on the last chunk.
  14889. if (_mode === c.Z_FINISH) {
  14890. status = zlib_inflate.inflateEnd(this.strm);
  14891. this.onEnd(status);
  14892. this.ended = true;
  14893. return status === c.Z_OK;
  14894. }
  14895. // callback interim results if Z_SYNC_FLUSH.
  14896. if (_mode === c.Z_SYNC_FLUSH) {
  14897. this.onEnd(c.Z_OK);
  14898. strm.avail_out = 0;
  14899. return true;
  14900. }
  14901. return true;
  14902. };
  14903. /**
  14904. * Inflate#onData(chunk) -> Void
  14905. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14906. * on js engine support. When string output requested, each chunk
  14907. * will be string.
  14908. *
  14909. * By default, stores data blocks in `chunks[]` property and glue
  14910. * those in `onEnd`. Override this handler, if you need another behaviour.
  14911. **/
  14912. Inflate.prototype.onData = function(chunk) {
  14913. this.chunks.push(chunk);
  14914. };
  14915. /**
  14916. * Inflate#onEnd(status) -> Void
  14917. * - status (Number): inflate status. 0 (Z_OK) on success,
  14918. * other if not.
  14919. *
  14920. * Called either after you tell inflate that the input stream is
  14921. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14922. * or if an error happened. By default - join collected chunks,
  14923. * free memory and fill `results` / `err` properties.
  14924. **/
  14925. Inflate.prototype.onEnd = function(status) {
  14926. // On success - join
  14927. if (status === c.Z_OK) {
  14928. if (this.options.to === 'string') {
  14929. // Glue & convert here, until we teach pako to send
  14930. // utf8 alligned strings to onData
  14931. this.result = this.chunks.join('');
  14932. } else {
  14933. this.result = utils.flattenChunks(this.chunks);
  14934. }
  14935. }
  14936. this.chunks = [];
  14937. this.err = status;
  14938. this.msg = this.strm.msg;
  14939. };
  14940. /**
  14941. * inflate(data[, options]) -> Uint8Array|Array|String
  14942. * - data (Uint8Array|Array|String): input data to decompress.
  14943. * - options (Object): zlib inflate options.
  14944. *
  14945. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  14946. * format via wrapper header by default. That's why we don't provide
  14947. * separate `ungzip` method.
  14948. *
  14949. * Supported options are:
  14950. *
  14951. * - windowBits
  14952. *
  14953. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14954. * for more information.
  14955. *
  14956. * Sugar (options):
  14957. *
  14958. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14959. * negative windowBits implicitly.
  14960. * - `to` (String) - if equal to 'string', then result will be converted
  14961. * from utf8 to utf16 (javascript) string. When string output requested,
  14962. * chunk length can differ from `chunkSize`, depending on content.
  14963. *
  14964. *
  14965. * ##### Example:
  14966. *
  14967. * ```javascript
  14968. * var pako = require('pako')
  14969. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  14970. * , output;
  14971. *
  14972. * try {
  14973. * output = pako.inflate(input);
  14974. * } catch (err)
  14975. * console.log(err);
  14976. * }
  14977. * ```
  14978. **/
  14979. function inflate(input, options) {
  14980. var inflator = new Inflate(options);
  14981. inflator.push(input, true);
  14982. // That will never happens, if you don't cheat with options :)
  14983. if (inflator.err) { throw inflator.msg; }
  14984. return inflator.result;
  14985. }
  14986. /**
  14987. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  14988. * - data (Uint8Array|Array|String): input data to decompress.
  14989. * - options (Object): zlib inflate options.
  14990. *
  14991. * The same as [[inflate]], but creates raw data, without wrapper
  14992. * (header and adler32 crc).
  14993. **/
  14994. function inflateRaw(input, options) {
  14995. options = options || {};
  14996. options.raw = true;
  14997. return inflate(input, options);
  14998. }
  14999. /**
  15000. * ungzip(data[, options]) -> Uint8Array|Array|String
  15001. * - data (Uint8Array|Array|String): input data to decompress.
  15002. * - options (Object): zlib inflate options.
  15003. *
  15004. * Just shortcut to [[inflate]], because it autodetects format
  15005. * by header.content. Done for convenience.
  15006. **/
  15007. exports.Inflate = Inflate;
  15008. exports.inflate = inflate;
  15009. exports.inflateRaw = inflateRaw;
  15010. exports.ungzip = inflate;
  15011. },{"./utils/common":54,"./utils/strings":55,"./zlib/constants":57,"./zlib/gzheader":60,"./zlib/inflate.js":62,"./zlib/messages":64,"./zlib/zstream":66}],54:[function(require,module,exports){
  15012. 'use strict';
  15013. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  15014. (typeof Uint16Array !== 'undefined') &&
  15015. (typeof Int32Array !== 'undefined');
  15016. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  15017. var sources = Array.prototype.slice.call(arguments, 1);
  15018. while (sources.length) {
  15019. var source = sources.shift();
  15020. if (!source) { continue; }
  15021. if (typeof source !== 'object') {
  15022. throw new TypeError(source + 'must be non-object');
  15023. }
  15024. for (var p in source) {
  15025. if (source.hasOwnProperty(p)) {
  15026. obj[p] = source[p];
  15027. }
  15028. }
  15029. }
  15030. return obj;
  15031. };
  15032. // reduce buffer size, avoiding mem copy
  15033. exports.shrinkBuf = function (buf, size) {
  15034. if (buf.length === size) { return buf; }
  15035. if (buf.subarray) { return buf.subarray(0, size); }
  15036. buf.length = size;
  15037. return buf;
  15038. };
  15039. var fnTyped = {
  15040. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15041. if (src.subarray && dest.subarray) {
  15042. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  15043. return;
  15044. }
  15045. // Fallback to ordinary array
  15046. for (var i=0; i<len; i++) {
  15047. dest[dest_offs + i] = src[src_offs + i];
  15048. }
  15049. },
  15050. // Join array of chunks to single array.
  15051. flattenChunks: function(chunks) {
  15052. var i, l, len, pos, chunk, result;
  15053. // calculate data length
  15054. len = 0;
  15055. for (i=0, l=chunks.length; i<l; i++) {
  15056. len += chunks[i].length;
  15057. }
  15058. // join chunks
  15059. result = new Uint8Array(len);
  15060. pos = 0;
  15061. for (i=0, l=chunks.length; i<l; i++) {
  15062. chunk = chunks[i];
  15063. result.set(chunk, pos);
  15064. pos += chunk.length;
  15065. }
  15066. return result;
  15067. }
  15068. };
  15069. var fnUntyped = {
  15070. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15071. for (var i=0; i<len; i++) {
  15072. dest[dest_offs + i] = src[src_offs + i];
  15073. }
  15074. },
  15075. // Join array of chunks to single array.
  15076. flattenChunks: function(chunks) {
  15077. return [].concat.apply([], chunks);
  15078. }
  15079. };
  15080. // Enable/Disable typed arrays use, for testing
  15081. //
  15082. exports.setTyped = function (on) {
  15083. if (on) {
  15084. exports.Buf8 = Uint8Array;
  15085. exports.Buf16 = Uint16Array;
  15086. exports.Buf32 = Int32Array;
  15087. exports.assign(exports, fnTyped);
  15088. } else {
  15089. exports.Buf8 = Array;
  15090. exports.Buf16 = Array;
  15091. exports.Buf32 = Array;
  15092. exports.assign(exports, fnUntyped);
  15093. }
  15094. };
  15095. exports.setTyped(TYPED_OK);
  15096. },{}],55:[function(require,module,exports){
  15097. // String encode/decode helpers
  15098. 'use strict';
  15099. var utils = require('./common');
  15100. // Quick check if we can use fast array to bin string conversion
  15101. //
  15102. // - apply(Array) can fail on Android 2.2
  15103. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  15104. //
  15105. var STR_APPLY_OK = true;
  15106. var STR_APPLY_UIA_OK = true;
  15107. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  15108. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  15109. // Table with utf8 lengths (calculated by first byte of sequence)
  15110. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  15111. // because max possible codepoint is 0x10ffff
  15112. var _utf8len = new utils.Buf8(256);
  15113. for (var q=0; q<256; q++) {
  15114. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  15115. }
  15116. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  15117. // convert string to array (typed, when possible)
  15118. exports.string2buf = function (str) {
  15119. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  15120. // count binary size
  15121. for (m_pos = 0; m_pos < str_len; m_pos++) {
  15122. c = str.charCodeAt(m_pos);
  15123. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15124. c2 = str.charCodeAt(m_pos+1);
  15125. if ((c2 & 0xfc00) === 0xdc00) {
  15126. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15127. m_pos++;
  15128. }
  15129. }
  15130. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  15131. }
  15132. // allocate buffer
  15133. buf = new utils.Buf8(buf_len);
  15134. // convert
  15135. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  15136. c = str.charCodeAt(m_pos);
  15137. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15138. c2 = str.charCodeAt(m_pos+1);
  15139. if ((c2 & 0xfc00) === 0xdc00) {
  15140. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15141. m_pos++;
  15142. }
  15143. }
  15144. if (c < 0x80) {
  15145. /* one byte */
  15146. buf[i++] = c;
  15147. } else if (c < 0x800) {
  15148. /* two bytes */
  15149. buf[i++] = 0xC0 | (c >>> 6);
  15150. buf[i++] = 0x80 | (c & 0x3f);
  15151. } else if (c < 0x10000) {
  15152. /* three bytes */
  15153. buf[i++] = 0xE0 | (c >>> 12);
  15154. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15155. buf[i++] = 0x80 | (c & 0x3f);
  15156. } else {
  15157. /* four bytes */
  15158. buf[i++] = 0xf0 | (c >>> 18);
  15159. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  15160. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15161. buf[i++] = 0x80 | (c & 0x3f);
  15162. }
  15163. }
  15164. return buf;
  15165. };
  15166. // Helper (used in 2 places)
  15167. function buf2binstring(buf, len) {
  15168. // use fallback for big arrays to avoid stack overflow
  15169. if (len < 65537) {
  15170. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  15171. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  15172. }
  15173. }
  15174. var result = '';
  15175. for (var i=0; i < len; i++) {
  15176. result += String.fromCharCode(buf[i]);
  15177. }
  15178. return result;
  15179. }
  15180. // Convert byte array to binary string
  15181. exports.buf2binstring = function(buf) {
  15182. return buf2binstring(buf, buf.length);
  15183. };
  15184. // Convert binary string (typed, when possible)
  15185. exports.binstring2buf = function(str) {
  15186. var buf = new utils.Buf8(str.length);
  15187. for (var i=0, len=buf.length; i < len; i++) {
  15188. buf[i] = str.charCodeAt(i);
  15189. }
  15190. return buf;
  15191. };
  15192. // convert array to string
  15193. exports.buf2string = function (buf, max) {
  15194. var i, out, c, c_len;
  15195. var len = max || buf.length;
  15196. // Reserve max possible length (2 words per char)
  15197. // NB: by unknown reasons, Array is significantly faster for
  15198. // String.fromCharCode.apply than Uint16Array.
  15199. var utf16buf = new Array(len*2);
  15200. for (out=0, i=0; i<len;) {
  15201. c = buf[i++];
  15202. // quick process ascii
  15203. if (c < 0x80) { utf16buf[out++] = c; continue; }
  15204. c_len = _utf8len[c];
  15205. // skip 5 & 6 byte codes
  15206. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  15207. // apply mask on first byte
  15208. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  15209. // join the rest
  15210. while (c_len > 1 && i < len) {
  15211. c = (c << 6) | (buf[i++] & 0x3f);
  15212. c_len--;
  15213. }
  15214. // terminated by end of string?
  15215. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  15216. if (c < 0x10000) {
  15217. utf16buf[out++] = c;
  15218. } else {
  15219. c -= 0x10000;
  15220. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  15221. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  15222. }
  15223. }
  15224. return buf2binstring(utf16buf, out);
  15225. };
  15226. // Calculate max possible position in utf8 buffer,
  15227. // that will not break sequence. If that's not possible
  15228. // - (very small limits) return max size as is.
  15229. //
  15230. // buf[] - utf8 bytes array
  15231. // max - length limit (mandatory);
  15232. exports.utf8border = function(buf, max) {
  15233. var pos;
  15234. max = max || buf.length;
  15235. if (max > buf.length) { max = buf.length; }
  15236. // go back from last position, until start of sequence found
  15237. pos = max-1;
  15238. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  15239. // Fuckup - very small and broken sequence,
  15240. // return max, because we should return something anyway.
  15241. if (pos < 0) { return max; }
  15242. // If we came to start of buffer - that means vuffer is too small,
  15243. // return max too.
  15244. if (pos === 0) { return max; }
  15245. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  15246. };
  15247. },{"./common":54}],56:[function(require,module,exports){
  15248. 'use strict';
  15249. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  15250. // It doesn't worth to make additional optimizationa as in original.
  15251. // Small size is preferable.
  15252. function adler32(adler, buf, len, pos) {
  15253. var s1 = (adler & 0xffff) |0,
  15254. s2 = ((adler >>> 16) & 0xffff) |0,
  15255. n = 0;
  15256. while (len !== 0) {
  15257. // Set limit ~ twice less than 5552, to keep
  15258. // s2 in 31-bits, because we force signed ints.
  15259. // in other case %= will fail.
  15260. n = len > 2000 ? 2000 : len;
  15261. len -= n;
  15262. do {
  15263. s1 = (s1 + buf[pos++]) |0;
  15264. s2 = (s2 + s1) |0;
  15265. } while (--n);
  15266. s1 %= 65521;
  15267. s2 %= 65521;
  15268. }
  15269. return (s1 | (s2 << 16)) |0;
  15270. }
  15271. module.exports = adler32;
  15272. },{}],57:[function(require,module,exports){
  15273. module.exports = {
  15274. /* Allowed flush values; see deflate() and inflate() below for details */
  15275. Z_NO_FLUSH: 0,
  15276. Z_PARTIAL_FLUSH: 1,
  15277. Z_SYNC_FLUSH: 2,
  15278. Z_FULL_FLUSH: 3,
  15279. Z_FINISH: 4,
  15280. Z_BLOCK: 5,
  15281. Z_TREES: 6,
  15282. /* Return codes for the compression/decompression functions. Negative values
  15283. * are errors, positive values are used for special but normal events.
  15284. */
  15285. Z_OK: 0,
  15286. Z_STREAM_END: 1,
  15287. Z_NEED_DICT: 2,
  15288. Z_ERRNO: -1,
  15289. Z_STREAM_ERROR: -2,
  15290. Z_DATA_ERROR: -3,
  15291. //Z_MEM_ERROR: -4,
  15292. Z_BUF_ERROR: -5,
  15293. //Z_VERSION_ERROR: -6,
  15294. /* compression levels */
  15295. Z_NO_COMPRESSION: 0,
  15296. Z_BEST_SPEED: 1,
  15297. Z_BEST_COMPRESSION: 9,
  15298. Z_DEFAULT_COMPRESSION: -1,
  15299. Z_FILTERED: 1,
  15300. Z_HUFFMAN_ONLY: 2,
  15301. Z_RLE: 3,
  15302. Z_FIXED: 4,
  15303. Z_DEFAULT_STRATEGY: 0,
  15304. /* Possible values of the data_type field (though see inflate()) */
  15305. Z_BINARY: 0,
  15306. Z_TEXT: 1,
  15307. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  15308. Z_UNKNOWN: 2,
  15309. /* The deflate compression method */
  15310. Z_DEFLATED: 8
  15311. //Z_NULL: null // Use -1 or null inline, depending on var type
  15312. };
  15313. },{}],58:[function(require,module,exports){
  15314. 'use strict';
  15315. // Note: we can't get significant speed boost here.
  15316. // So write code to minimize size - no pregenerated tables
  15317. // and array tools dependencies.
  15318. // Use ordinary array, since untyped makes no boost here
  15319. function makeTable() {
  15320. var c, table = [];
  15321. for (var n =0; n < 256; n++) {
  15322. c = n;
  15323. for (var k =0; k < 8; k++) {
  15324. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  15325. }
  15326. table[n] = c;
  15327. }
  15328. return table;
  15329. }
  15330. // Create table on load. Just 255 signed longs. Not a problem.
  15331. var crcTable = makeTable();
  15332. function crc32(crc, buf, len, pos) {
  15333. var t = crcTable,
  15334. end = pos + len;
  15335. crc = crc ^ (-1);
  15336. for (var i = pos; i < end; i++) {
  15337. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  15338. }
  15339. return (crc ^ (-1)); // >>> 0;
  15340. }
  15341. module.exports = crc32;
  15342. },{}],59:[function(require,module,exports){
  15343. 'use strict';
  15344. var utils = require('../utils/common');
  15345. var trees = require('./trees');
  15346. var adler32 = require('./adler32');
  15347. var crc32 = require('./crc32');
  15348. var msg = require('./messages');
  15349. /* Public constants ==========================================================*/
  15350. /* ===========================================================================*/
  15351. /* Allowed flush values; see deflate() and inflate() below for details */
  15352. var Z_NO_FLUSH = 0;
  15353. var Z_PARTIAL_FLUSH = 1;
  15354. //var Z_SYNC_FLUSH = 2;
  15355. var Z_FULL_FLUSH = 3;
  15356. var Z_FINISH = 4;
  15357. var Z_BLOCK = 5;
  15358. //var Z_TREES = 6;
  15359. /* Return codes for the compression/decompression functions. Negative values
  15360. * are errors, positive values are used for special but normal events.
  15361. */
  15362. var Z_OK = 0;
  15363. var Z_STREAM_END = 1;
  15364. //var Z_NEED_DICT = 2;
  15365. //var Z_ERRNO = -1;
  15366. var Z_STREAM_ERROR = -2;
  15367. var Z_DATA_ERROR = -3;
  15368. //var Z_MEM_ERROR = -4;
  15369. var Z_BUF_ERROR = -5;
  15370. //var Z_VERSION_ERROR = -6;
  15371. /* compression levels */
  15372. //var Z_NO_COMPRESSION = 0;
  15373. //var Z_BEST_SPEED = 1;
  15374. //var Z_BEST_COMPRESSION = 9;
  15375. var Z_DEFAULT_COMPRESSION = -1;
  15376. var Z_FILTERED = 1;
  15377. var Z_HUFFMAN_ONLY = 2;
  15378. var Z_RLE = 3;
  15379. var Z_FIXED = 4;
  15380. var Z_DEFAULT_STRATEGY = 0;
  15381. /* Possible values of the data_type field (though see inflate()) */
  15382. //var Z_BINARY = 0;
  15383. //var Z_TEXT = 1;
  15384. //var Z_ASCII = 1; // = Z_TEXT
  15385. var Z_UNKNOWN = 2;
  15386. /* The deflate compression method */
  15387. var Z_DEFLATED = 8;
  15388. /*============================================================================*/
  15389. var MAX_MEM_LEVEL = 9;
  15390. /* Maximum value for memLevel in deflateInit2 */
  15391. var MAX_WBITS = 15;
  15392. /* 32K LZ77 window */
  15393. var DEF_MEM_LEVEL = 8;
  15394. var LENGTH_CODES = 29;
  15395. /* number of length codes, not counting the special END_BLOCK code */
  15396. var LITERALS = 256;
  15397. /* number of literal bytes 0..255 */
  15398. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  15399. /* number of Literal or Length codes, including the END_BLOCK code */
  15400. var D_CODES = 30;
  15401. /* number of distance codes */
  15402. var BL_CODES = 19;
  15403. /* number of codes used to transfer the bit lengths */
  15404. var HEAP_SIZE = 2*L_CODES + 1;
  15405. /* maximum heap size */
  15406. var MAX_BITS = 15;
  15407. /* All codes must not exceed MAX_BITS bits */
  15408. var MIN_MATCH = 3;
  15409. var MAX_MATCH = 258;
  15410. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  15411. var PRESET_DICT = 0x20;
  15412. var INIT_STATE = 42;
  15413. var EXTRA_STATE = 69;
  15414. var NAME_STATE = 73;
  15415. var COMMENT_STATE = 91;
  15416. var HCRC_STATE = 103;
  15417. var BUSY_STATE = 113;
  15418. var FINISH_STATE = 666;
  15419. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  15420. var BS_BLOCK_DONE = 2; /* block flush performed */
  15421. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  15422. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  15423. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  15424. function err(strm, errorCode) {
  15425. strm.msg = msg[errorCode];
  15426. return errorCode;
  15427. }
  15428. function rank(f) {
  15429. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  15430. }
  15431. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  15432. /* =========================================================================
  15433. * Flush as much pending output as possible. All deflate() output goes
  15434. * through this function so some applications may wish to modify it
  15435. * to avoid allocating a large strm->output buffer and copying into it.
  15436. * (See also read_buf()).
  15437. */
  15438. function flush_pending(strm) {
  15439. var s = strm.state;
  15440. //_tr_flush_bits(s);
  15441. var len = s.pending;
  15442. if (len > strm.avail_out) {
  15443. len = strm.avail_out;
  15444. }
  15445. if (len === 0) { return; }
  15446. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  15447. strm.next_out += len;
  15448. s.pending_out += len;
  15449. strm.total_out += len;
  15450. strm.avail_out -= len;
  15451. s.pending -= len;
  15452. if (s.pending === 0) {
  15453. s.pending_out = 0;
  15454. }
  15455. }
  15456. function flush_block_only (s, last) {
  15457. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  15458. s.block_start = s.strstart;
  15459. flush_pending(s.strm);
  15460. }
  15461. function put_byte(s, b) {
  15462. s.pending_buf[s.pending++] = b;
  15463. }
  15464. /* =========================================================================
  15465. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  15466. * IN assertion: the stream state is correct and there is enough room in
  15467. * pending_buf.
  15468. */
  15469. function putShortMSB(s, b) {
  15470. // put_byte(s, (Byte)(b >> 8));
  15471. // put_byte(s, (Byte)(b & 0xff));
  15472. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  15473. s.pending_buf[s.pending++] = b & 0xff;
  15474. }
  15475. /* ===========================================================================
  15476. * Read a new buffer from the current input stream, update the adler32
  15477. * and total number of bytes read. All deflate() input goes through
  15478. * this function so some applications may wish to modify it to avoid
  15479. * allocating a large strm->input buffer and copying from it.
  15480. * (See also flush_pending()).
  15481. */
  15482. function read_buf(strm, buf, start, size) {
  15483. var len = strm.avail_in;
  15484. if (len > size) { len = size; }
  15485. if (len === 0) { return 0; }
  15486. strm.avail_in -= len;
  15487. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  15488. if (strm.state.wrap === 1) {
  15489. strm.adler = adler32(strm.adler, buf, len, start);
  15490. }
  15491. else if (strm.state.wrap === 2) {
  15492. strm.adler = crc32(strm.adler, buf, len, start);
  15493. }
  15494. strm.next_in += len;
  15495. strm.total_in += len;
  15496. return len;
  15497. }
  15498. /* ===========================================================================
  15499. * Set match_start to the longest match starting at the given string and
  15500. * return its length. Matches shorter or equal to prev_length are discarded,
  15501. * in which case the result is equal to prev_length and match_start is
  15502. * garbage.
  15503. * IN assertions: cur_match is the head of the hash chain for the current
  15504. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  15505. * OUT assertion: the match length is not greater than s->lookahead.
  15506. */
  15507. function longest_match(s, cur_match) {
  15508. var chain_length = s.max_chain_length; /* max hash chain length */
  15509. var scan = s.strstart; /* current string */
  15510. var match; /* matched string */
  15511. var len; /* length of current match */
  15512. var best_len = s.prev_length; /* best match length so far */
  15513. var nice_match = s.nice_match; /* stop if match long enough */
  15514. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  15515. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  15516. var _win = s.window; // shortcut
  15517. var wmask = s.w_mask;
  15518. var prev = s.prev;
  15519. /* Stop when cur_match becomes <= limit. To simplify the code,
  15520. * we prevent matches with the string of window index 0.
  15521. */
  15522. var strend = s.strstart + MAX_MATCH;
  15523. var scan_end1 = _win[scan + best_len - 1];
  15524. var scan_end = _win[scan + best_len];
  15525. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  15526. * It is easy to get rid of this optimization if necessary.
  15527. */
  15528. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  15529. /* Do not waste too much time if we already have a good match: */
  15530. if (s.prev_length >= s.good_match) {
  15531. chain_length >>= 2;
  15532. }
  15533. /* Do not look for matches beyond the end of the input. This is necessary
  15534. * to make deflate deterministic.
  15535. */
  15536. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  15537. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  15538. do {
  15539. // Assert(cur_match < s->strstart, "no future");
  15540. match = cur_match;
  15541. /* Skip to next match if the match length cannot increase
  15542. * or if the match length is less than 2. Note that the checks below
  15543. * for insufficient lookahead only occur occasionally for performance
  15544. * reasons. Therefore uninitialized memory will be accessed, and
  15545. * conditional jumps will be made that depend on those values.
  15546. * However the length of the match is limited to the lookahead, so
  15547. * the output of deflate is not affected by the uninitialized values.
  15548. */
  15549. if (_win[match + best_len] !== scan_end ||
  15550. _win[match + best_len - 1] !== scan_end1 ||
  15551. _win[match] !== _win[scan] ||
  15552. _win[++match] !== _win[scan + 1]) {
  15553. continue;
  15554. }
  15555. /* The check at best_len-1 can be removed because it will be made
  15556. * again later. (This heuristic is not always a win.)
  15557. * It is not necessary to compare scan[2] and match[2] since they
  15558. * are always equal when the other bytes match, given that
  15559. * the hash keys are equal and that HASH_BITS >= 8.
  15560. */
  15561. scan += 2;
  15562. match++;
  15563. // Assert(*scan == *match, "match[2]?");
  15564. /* We check for insufficient lookahead only every 8th comparison;
  15565. * the 256th check will be made at strstart+258.
  15566. */
  15567. do {
  15568. /*jshint noempty:false*/
  15569. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15570. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15571. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15572. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15573. scan < strend);
  15574. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  15575. len = MAX_MATCH - (strend - scan);
  15576. scan = strend - MAX_MATCH;
  15577. if (len > best_len) {
  15578. s.match_start = cur_match;
  15579. best_len = len;
  15580. if (len >= nice_match) {
  15581. break;
  15582. }
  15583. scan_end1 = _win[scan + best_len - 1];
  15584. scan_end = _win[scan + best_len];
  15585. }
  15586. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  15587. if (best_len <= s.lookahead) {
  15588. return best_len;
  15589. }
  15590. return s.lookahead;
  15591. }
  15592. /* ===========================================================================
  15593. * Fill the window when the lookahead becomes insufficient.
  15594. * Updates strstart and lookahead.
  15595. *
  15596. * IN assertion: lookahead < MIN_LOOKAHEAD
  15597. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  15598. * At least one byte has been read, or avail_in == 0; reads are
  15599. * performed for at least two bytes (required for the zip translate_eol
  15600. * option -- not supported here).
  15601. */
  15602. function fill_window(s) {
  15603. var _w_size = s.w_size;
  15604. var p, n, m, more, str;
  15605. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  15606. do {
  15607. more = s.window_size - s.lookahead - s.strstart;
  15608. // JS ints have 32 bit, block below not needed
  15609. /* Deal with !@#$% 64K limit: */
  15610. //if (sizeof(int) <= 2) {
  15611. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  15612. // more = wsize;
  15613. //
  15614. // } else if (more == (unsigned)(-1)) {
  15615. // /* Very unlikely, but possible on 16 bit machine if
  15616. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  15617. // */
  15618. // more--;
  15619. // }
  15620. //}
  15621. /* If the window is almost full and there is insufficient lookahead,
  15622. * move the upper half to the lower one to make room in the upper half.
  15623. */
  15624. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  15625. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  15626. s.match_start -= _w_size;
  15627. s.strstart -= _w_size;
  15628. /* we now have strstart >= MAX_DIST */
  15629. s.block_start -= _w_size;
  15630. /* Slide the hash table (could be avoided with 32 bit values
  15631. at the expense of memory usage). We slide even when level == 0
  15632. to keep the hash table consistent if we switch back to level > 0
  15633. later. (Using level 0 permanently is not an optimal usage of
  15634. zlib, so we don't care about this pathological case.)
  15635. */
  15636. n = s.hash_size;
  15637. p = n;
  15638. do {
  15639. m = s.head[--p];
  15640. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  15641. } while (--n);
  15642. n = _w_size;
  15643. p = n;
  15644. do {
  15645. m = s.prev[--p];
  15646. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  15647. /* If n is not on any hash chain, prev[n] is garbage but
  15648. * its value will never be used.
  15649. */
  15650. } while (--n);
  15651. more += _w_size;
  15652. }
  15653. if (s.strm.avail_in === 0) {
  15654. break;
  15655. }
  15656. /* If there was no sliding:
  15657. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  15658. * more == window_size - lookahead - strstart
  15659. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  15660. * => more >= window_size - 2*WSIZE + 2
  15661. * In the BIG_MEM or MMAP case (not yet supported),
  15662. * window_size == input_size + MIN_LOOKAHEAD &&
  15663. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  15664. * Otherwise, window_size == 2*WSIZE so more >= 2.
  15665. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  15666. */
  15667. //Assert(more >= 2, "more < 2");
  15668. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  15669. s.lookahead += n;
  15670. /* Initialize the hash value now that we have some input: */
  15671. if (s.lookahead + s.insert >= MIN_MATCH) {
  15672. str = s.strstart - s.insert;
  15673. s.ins_h = s.window[str];
  15674. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  15675. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  15676. //#if MIN_MATCH != 3
  15677. // Call update_hash() MIN_MATCH-3 more times
  15678. //#endif
  15679. while (s.insert) {
  15680. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  15681. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  15682. s.prev[str & s.w_mask] = s.head[s.ins_h];
  15683. s.head[s.ins_h] = str;
  15684. str++;
  15685. s.insert--;
  15686. if (s.lookahead + s.insert < MIN_MATCH) {
  15687. break;
  15688. }
  15689. }
  15690. }
  15691. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  15692. * but this is not important since only literal bytes will be emitted.
  15693. */
  15694. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  15695. /* If the WIN_INIT bytes after the end of the current data have never been
  15696. * written, then zero those bytes in order to avoid memory check reports of
  15697. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  15698. * the longest match routines. Update the high water mark for the next
  15699. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  15700. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  15701. */
  15702. // if (s.high_water < s.window_size) {
  15703. // var curr = s.strstart + s.lookahead;
  15704. // var init = 0;
  15705. //
  15706. // if (s.high_water < curr) {
  15707. // /* Previous high water mark below current data -- zero WIN_INIT
  15708. // * bytes or up to end of window, whichever is less.
  15709. // */
  15710. // init = s.window_size - curr;
  15711. // if (init > WIN_INIT)
  15712. // init = WIN_INIT;
  15713. // zmemzero(s->window + curr, (unsigned)init);
  15714. // s->high_water = curr + init;
  15715. // }
  15716. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  15717. // /* High water mark at or above current data, but below current data
  15718. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  15719. // * to end of window, whichever is less.
  15720. // */
  15721. // init = (ulg)curr + WIN_INIT - s->high_water;
  15722. // if (init > s->window_size - s->high_water)
  15723. // init = s->window_size - s->high_water;
  15724. // zmemzero(s->window + s->high_water, (unsigned)init);
  15725. // s->high_water += init;
  15726. // }
  15727. // }
  15728. //
  15729. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  15730. // "not enough room for search");
  15731. }
  15732. /* ===========================================================================
  15733. * Copy without compression as much as possible from the input stream, return
  15734. * the current block state.
  15735. * This function does not insert new strings in the dictionary since
  15736. * uncompressible data is probably not useful. This function is used
  15737. * only for the level=0 compression option.
  15738. * NOTE: this function should be optimized to avoid extra copying from
  15739. * window to pending_buf.
  15740. */
  15741. function deflate_stored(s, flush) {
  15742. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  15743. * to pending_buf_size, and each stored block has a 5 byte header:
  15744. */
  15745. var max_block_size = 0xffff;
  15746. if (max_block_size > s.pending_buf_size - 5) {
  15747. max_block_size = s.pending_buf_size - 5;
  15748. }
  15749. /* Copy as much as possible from input to output: */
  15750. for (;;) {
  15751. /* Fill the window as much as possible: */
  15752. if (s.lookahead <= 1) {
  15753. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  15754. // s->block_start >= (long)s->w_size, "slide too late");
  15755. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  15756. // s.block_start >= s.w_size)) {
  15757. // throw new Error("slide too late");
  15758. // }
  15759. fill_window(s);
  15760. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  15761. return BS_NEED_MORE;
  15762. }
  15763. if (s.lookahead === 0) {
  15764. break;
  15765. }
  15766. /* flush the current block */
  15767. }
  15768. //Assert(s->block_start >= 0L, "block gone");
  15769. // if (s.block_start < 0) throw new Error("block gone");
  15770. s.strstart += s.lookahead;
  15771. s.lookahead = 0;
  15772. /* Emit a stored block if pending_buf will be full: */
  15773. var max_start = s.block_start + max_block_size;
  15774. if (s.strstart === 0 || s.strstart >= max_start) {
  15775. /* strstart == 0 is possible when wraparound on 16-bit machine */
  15776. s.lookahead = s.strstart - max_start;
  15777. s.strstart = max_start;
  15778. /*** FLUSH_BLOCK(s, 0); ***/
  15779. flush_block_only(s, false);
  15780. if (s.strm.avail_out === 0) {
  15781. return BS_NEED_MORE;
  15782. }
  15783. /***/
  15784. }
  15785. /* Flush if we may have to slide, otherwise block_start may become
  15786. * negative and the data will be gone:
  15787. */
  15788. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  15789. /*** FLUSH_BLOCK(s, 0); ***/
  15790. flush_block_only(s, false);
  15791. if (s.strm.avail_out === 0) {
  15792. return BS_NEED_MORE;
  15793. }
  15794. /***/
  15795. }
  15796. }
  15797. s.insert = 0;
  15798. if (flush === Z_FINISH) {
  15799. /*** FLUSH_BLOCK(s, 1); ***/
  15800. flush_block_only(s, true);
  15801. if (s.strm.avail_out === 0) {
  15802. return BS_FINISH_STARTED;
  15803. }
  15804. /***/
  15805. return BS_FINISH_DONE;
  15806. }
  15807. if (s.strstart > s.block_start) {
  15808. /*** FLUSH_BLOCK(s, 0); ***/
  15809. flush_block_only(s, false);
  15810. if (s.strm.avail_out === 0) {
  15811. return BS_NEED_MORE;
  15812. }
  15813. /***/
  15814. }
  15815. return BS_NEED_MORE;
  15816. }
  15817. /* ===========================================================================
  15818. * Compress as much as possible from the input stream, return the current
  15819. * block state.
  15820. * This function does not perform lazy evaluation of matches and inserts
  15821. * new strings in the dictionary only for unmatched strings or for short
  15822. * matches. It is used only for the fast compression options.
  15823. */
  15824. function deflate_fast(s, flush) {
  15825. var hash_head; /* head of the hash chain */
  15826. var bflush; /* set if current block must be flushed */
  15827. for (;;) {
  15828. /* Make sure that we always have enough lookahead, except
  15829. * at the end of the input file. We need MAX_MATCH bytes
  15830. * for the next match, plus MIN_MATCH bytes to insert the
  15831. * string following the next match.
  15832. */
  15833. if (s.lookahead < MIN_LOOKAHEAD) {
  15834. fill_window(s);
  15835. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15836. return BS_NEED_MORE;
  15837. }
  15838. if (s.lookahead === 0) {
  15839. break; /* flush the current block */
  15840. }
  15841. }
  15842. /* Insert the string window[strstart .. strstart+2] in the
  15843. * dictionary, and set hash_head to the head of the hash chain:
  15844. */
  15845. hash_head = 0/*NIL*/;
  15846. if (s.lookahead >= MIN_MATCH) {
  15847. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15848. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15849. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15850. s.head[s.ins_h] = s.strstart;
  15851. /***/
  15852. }
  15853. /* Find the longest match, discarding those <= prev_length.
  15854. * At this point we have always match_length < MIN_MATCH
  15855. */
  15856. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  15857. /* To simplify the code, we prevent matches with the string
  15858. * of window index 0 (in particular we have to avoid a match
  15859. * of the string with itself at the start of the input file).
  15860. */
  15861. s.match_length = longest_match(s, hash_head);
  15862. /* longest_match() sets match_start */
  15863. }
  15864. if (s.match_length >= MIN_MATCH) {
  15865. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  15866. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  15867. s.match_length - MIN_MATCH, bflush); ***/
  15868. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  15869. s.lookahead -= s.match_length;
  15870. /* Insert new strings in the hash table only if the match length
  15871. * is not too large. This saves time but degrades compression.
  15872. */
  15873. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  15874. s.match_length--; /* string at strstart already in table */
  15875. do {
  15876. s.strstart++;
  15877. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15878. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15879. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15880. s.head[s.ins_h] = s.strstart;
  15881. /***/
  15882. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  15883. * always MIN_MATCH bytes ahead.
  15884. */
  15885. } while (--s.match_length !== 0);
  15886. s.strstart++;
  15887. } else
  15888. {
  15889. s.strstart += s.match_length;
  15890. s.match_length = 0;
  15891. s.ins_h = s.window[s.strstart];
  15892. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  15893. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  15894. //#if MIN_MATCH != 3
  15895. // Call UPDATE_HASH() MIN_MATCH-3 more times
  15896. //#endif
  15897. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  15898. * matter since it will be recomputed at next deflate call.
  15899. */
  15900. }
  15901. } else {
  15902. /* No match, output a literal byte */
  15903. //Tracevv((stderr,"%c", s.window[s.strstart]));
  15904. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15905. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15906. s.lookahead--;
  15907. s.strstart++;
  15908. }
  15909. if (bflush) {
  15910. /*** FLUSH_BLOCK(s, 0); ***/
  15911. flush_block_only(s, false);
  15912. if (s.strm.avail_out === 0) {
  15913. return BS_NEED_MORE;
  15914. }
  15915. /***/
  15916. }
  15917. }
  15918. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  15919. if (flush === Z_FINISH) {
  15920. /*** FLUSH_BLOCK(s, 1); ***/
  15921. flush_block_only(s, true);
  15922. if (s.strm.avail_out === 0) {
  15923. return BS_FINISH_STARTED;
  15924. }
  15925. /***/
  15926. return BS_FINISH_DONE;
  15927. }
  15928. if (s.last_lit) {
  15929. /*** FLUSH_BLOCK(s, 0); ***/
  15930. flush_block_only(s, false);
  15931. if (s.strm.avail_out === 0) {
  15932. return BS_NEED_MORE;
  15933. }
  15934. /***/
  15935. }
  15936. return BS_BLOCK_DONE;
  15937. }
  15938. /* ===========================================================================
  15939. * Same as above, but achieves better compression. We use a lazy
  15940. * evaluation for matches: a match is finally adopted only if there is
  15941. * no better match at the next window position.
  15942. */
  15943. function deflate_slow(s, flush) {
  15944. var hash_head; /* head of hash chain */
  15945. var bflush; /* set if current block must be flushed */
  15946. var max_insert;
  15947. /* Process the input block. */
  15948. for (;;) {
  15949. /* Make sure that we always have enough lookahead, except
  15950. * at the end of the input file. We need MAX_MATCH bytes
  15951. * for the next match, plus MIN_MATCH bytes to insert the
  15952. * string following the next match.
  15953. */
  15954. if (s.lookahead < MIN_LOOKAHEAD) {
  15955. fill_window(s);
  15956. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15957. return BS_NEED_MORE;
  15958. }
  15959. if (s.lookahead === 0) { break; } /* flush the current block */
  15960. }
  15961. /* Insert the string window[strstart .. strstart+2] in the
  15962. * dictionary, and set hash_head to the head of the hash chain:
  15963. */
  15964. hash_head = 0/*NIL*/;
  15965. if (s.lookahead >= MIN_MATCH) {
  15966. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15967. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15968. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15969. s.head[s.ins_h] = s.strstart;
  15970. /***/
  15971. }
  15972. /* Find the longest match, discarding those <= prev_length.
  15973. */
  15974. s.prev_length = s.match_length;
  15975. s.prev_match = s.match_start;
  15976. s.match_length = MIN_MATCH-1;
  15977. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  15978. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  15979. /* To simplify the code, we prevent matches with the string
  15980. * of window index 0 (in particular we have to avoid a match
  15981. * of the string with itself at the start of the input file).
  15982. */
  15983. s.match_length = longest_match(s, hash_head);
  15984. /* longest_match() sets match_start */
  15985. if (s.match_length <= 5 &&
  15986. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  15987. /* If prev_match is also MIN_MATCH, match_start is garbage
  15988. * but we will ignore the current match anyway.
  15989. */
  15990. s.match_length = MIN_MATCH-1;
  15991. }
  15992. }
  15993. /* If there was a match at the previous step and the current
  15994. * match is not better, output the previous match:
  15995. */
  15996. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  15997. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  15998. /* Do not insert strings in hash table beyond this. */
  15999. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  16000. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  16001. s.prev_length - MIN_MATCH, bflush);***/
  16002. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  16003. /* Insert in hash table all strings up to the end of the match.
  16004. * strstart-1 and strstart are already inserted. If there is not
  16005. * enough lookahead, the last two strings are not inserted in
  16006. * the hash table.
  16007. */
  16008. s.lookahead -= s.prev_length-1;
  16009. s.prev_length -= 2;
  16010. do {
  16011. if (++s.strstart <= max_insert) {
  16012. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16013. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16014. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16015. s.head[s.ins_h] = s.strstart;
  16016. /***/
  16017. }
  16018. } while (--s.prev_length !== 0);
  16019. s.match_available = 0;
  16020. s.match_length = MIN_MATCH-1;
  16021. s.strstart++;
  16022. if (bflush) {
  16023. /*** FLUSH_BLOCK(s, 0); ***/
  16024. flush_block_only(s, false);
  16025. if (s.strm.avail_out === 0) {
  16026. return BS_NEED_MORE;
  16027. }
  16028. /***/
  16029. }
  16030. } else if (s.match_available) {
  16031. /* If there was no match at the previous position, output a
  16032. * single literal. If there was a match but the current match
  16033. * is longer, truncate the previous match to a single literal.
  16034. */
  16035. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16036. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16037. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16038. if (bflush) {
  16039. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  16040. flush_block_only(s, false);
  16041. /***/
  16042. }
  16043. s.strstart++;
  16044. s.lookahead--;
  16045. if (s.strm.avail_out === 0) {
  16046. return BS_NEED_MORE;
  16047. }
  16048. } else {
  16049. /* There is no previous match to compare with, wait for
  16050. * the next step to decide.
  16051. */
  16052. s.match_available = 1;
  16053. s.strstart++;
  16054. s.lookahead--;
  16055. }
  16056. }
  16057. //Assert (flush != Z_NO_FLUSH, "no flush?");
  16058. if (s.match_available) {
  16059. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16060. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16061. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16062. s.match_available = 0;
  16063. }
  16064. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  16065. if (flush === Z_FINISH) {
  16066. /*** FLUSH_BLOCK(s, 1); ***/
  16067. flush_block_only(s, true);
  16068. if (s.strm.avail_out === 0) {
  16069. return BS_FINISH_STARTED;
  16070. }
  16071. /***/
  16072. return BS_FINISH_DONE;
  16073. }
  16074. if (s.last_lit) {
  16075. /*** FLUSH_BLOCK(s, 0); ***/
  16076. flush_block_only(s, false);
  16077. if (s.strm.avail_out === 0) {
  16078. return BS_NEED_MORE;
  16079. }
  16080. /***/
  16081. }
  16082. return BS_BLOCK_DONE;
  16083. }
  16084. /* ===========================================================================
  16085. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  16086. * one. Do not maintain a hash table. (It will be regenerated if this run of
  16087. * deflate switches away from Z_RLE.)
  16088. */
  16089. function deflate_rle(s, flush) {
  16090. var bflush; /* set if current block must be flushed */
  16091. var prev; /* byte at distance one to match */
  16092. var scan, strend; /* scan goes up to strend for length of run */
  16093. var _win = s.window;
  16094. for (;;) {
  16095. /* Make sure that we always have enough lookahead, except
  16096. * at the end of the input file. We need MAX_MATCH bytes
  16097. * for the longest run, plus one for the unrolled loop.
  16098. */
  16099. if (s.lookahead <= MAX_MATCH) {
  16100. fill_window(s);
  16101. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  16102. return BS_NEED_MORE;
  16103. }
  16104. if (s.lookahead === 0) { break; } /* flush the current block */
  16105. }
  16106. /* See how many times the previous byte repeats */
  16107. s.match_length = 0;
  16108. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  16109. scan = s.strstart - 1;
  16110. prev = _win[scan];
  16111. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  16112. strend = s.strstart + MAX_MATCH;
  16113. do {
  16114. /*jshint noempty:false*/
  16115. } while (prev === _win[++scan] && prev === _win[++scan] &&
  16116. prev === _win[++scan] && prev === _win[++scan] &&
  16117. prev === _win[++scan] && prev === _win[++scan] &&
  16118. prev === _win[++scan] && prev === _win[++scan] &&
  16119. scan < strend);
  16120. s.match_length = MAX_MATCH - (strend - scan);
  16121. if (s.match_length > s.lookahead) {
  16122. s.match_length = s.lookahead;
  16123. }
  16124. }
  16125. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  16126. }
  16127. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  16128. if (s.match_length >= MIN_MATCH) {
  16129. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  16130. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  16131. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  16132. s.lookahead -= s.match_length;
  16133. s.strstart += s.match_length;
  16134. s.match_length = 0;
  16135. } else {
  16136. /* No match, output a literal byte */
  16137. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16138. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16139. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16140. s.lookahead--;
  16141. s.strstart++;
  16142. }
  16143. if (bflush) {
  16144. /*** FLUSH_BLOCK(s, 0); ***/
  16145. flush_block_only(s, false);
  16146. if (s.strm.avail_out === 0) {
  16147. return BS_NEED_MORE;
  16148. }
  16149. /***/
  16150. }
  16151. }
  16152. s.insert = 0;
  16153. if (flush === Z_FINISH) {
  16154. /*** FLUSH_BLOCK(s, 1); ***/
  16155. flush_block_only(s, true);
  16156. if (s.strm.avail_out === 0) {
  16157. return BS_FINISH_STARTED;
  16158. }
  16159. /***/
  16160. return BS_FINISH_DONE;
  16161. }
  16162. if (s.last_lit) {
  16163. /*** FLUSH_BLOCK(s, 0); ***/
  16164. flush_block_only(s, false);
  16165. if (s.strm.avail_out === 0) {
  16166. return BS_NEED_MORE;
  16167. }
  16168. /***/
  16169. }
  16170. return BS_BLOCK_DONE;
  16171. }
  16172. /* ===========================================================================
  16173. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  16174. * (It will be regenerated if this run of deflate switches away from Huffman.)
  16175. */
  16176. function deflate_huff(s, flush) {
  16177. var bflush; /* set if current block must be flushed */
  16178. for (;;) {
  16179. /* Make sure that we have a literal to write. */
  16180. if (s.lookahead === 0) {
  16181. fill_window(s);
  16182. if (s.lookahead === 0) {
  16183. if (flush === Z_NO_FLUSH) {
  16184. return BS_NEED_MORE;
  16185. }
  16186. break; /* flush the current block */
  16187. }
  16188. }
  16189. /* Output a literal byte */
  16190. s.match_length = 0;
  16191. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16192. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16193. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16194. s.lookahead--;
  16195. s.strstart++;
  16196. if (bflush) {
  16197. /*** FLUSH_BLOCK(s, 0); ***/
  16198. flush_block_only(s, false);
  16199. if (s.strm.avail_out === 0) {
  16200. return BS_NEED_MORE;
  16201. }
  16202. /***/
  16203. }
  16204. }
  16205. s.insert = 0;
  16206. if (flush === Z_FINISH) {
  16207. /*** FLUSH_BLOCK(s, 1); ***/
  16208. flush_block_only(s, true);
  16209. if (s.strm.avail_out === 0) {
  16210. return BS_FINISH_STARTED;
  16211. }
  16212. /***/
  16213. return BS_FINISH_DONE;
  16214. }
  16215. if (s.last_lit) {
  16216. /*** FLUSH_BLOCK(s, 0); ***/
  16217. flush_block_only(s, false);
  16218. if (s.strm.avail_out === 0) {
  16219. return BS_NEED_MORE;
  16220. }
  16221. /***/
  16222. }
  16223. return BS_BLOCK_DONE;
  16224. }
  16225. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  16226. * the desired pack level (0..9). The values given below have been tuned to
  16227. * exclude worst case performance for pathological files. Better values may be
  16228. * found for specific files.
  16229. */
  16230. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  16231. this.good_length = good_length;
  16232. this.max_lazy = max_lazy;
  16233. this.nice_length = nice_length;
  16234. this.max_chain = max_chain;
  16235. this.func = func;
  16236. };
  16237. var configuration_table;
  16238. configuration_table = [
  16239. /* good lazy nice chain */
  16240. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  16241. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  16242. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  16243. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  16244. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  16245. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  16246. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  16247. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  16248. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  16249. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  16250. ];
  16251. /* ===========================================================================
  16252. * Initialize the "longest match" routines for a new zlib stream
  16253. */
  16254. function lm_init(s) {
  16255. s.window_size = 2 * s.w_size;
  16256. /*** CLEAR_HASH(s); ***/
  16257. zero(s.head); // Fill with NIL (= 0);
  16258. /* Set the default configuration parameters:
  16259. */
  16260. s.max_lazy_match = configuration_table[s.level].max_lazy;
  16261. s.good_match = configuration_table[s.level].good_length;
  16262. s.nice_match = configuration_table[s.level].nice_length;
  16263. s.max_chain_length = configuration_table[s.level].max_chain;
  16264. s.strstart = 0;
  16265. s.block_start = 0;
  16266. s.lookahead = 0;
  16267. s.insert = 0;
  16268. s.match_length = s.prev_length = MIN_MATCH - 1;
  16269. s.match_available = 0;
  16270. s.ins_h = 0;
  16271. }
  16272. function DeflateState() {
  16273. this.strm = null; /* pointer back to this zlib stream */
  16274. this.status = 0; /* as the name implies */
  16275. this.pending_buf = null; /* output still pending */
  16276. this.pending_buf_size = 0; /* size of pending_buf */
  16277. this.pending_out = 0; /* next pending byte to output to the stream */
  16278. this.pending = 0; /* nb of bytes in the pending buffer */
  16279. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16280. this.gzhead = null; /* gzip header information to write */
  16281. this.gzindex = 0; /* where in extra, name, or comment */
  16282. this.method = Z_DEFLATED; /* can only be DEFLATED */
  16283. this.last_flush = -1; /* value of flush param for previous deflate call */
  16284. this.w_size = 0; /* LZ77 window size (32K by default) */
  16285. this.w_bits = 0; /* log2(w_size) (8..16) */
  16286. this.w_mask = 0; /* w_size - 1 */
  16287. this.window = null;
  16288. /* Sliding window. Input bytes are read into the second half of the window,
  16289. * and move to the first half later to keep a dictionary of at least wSize
  16290. * bytes. With this organization, matches are limited to a distance of
  16291. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  16292. * performed with a length multiple of the block size.
  16293. */
  16294. this.window_size = 0;
  16295. /* Actual size of window: 2*wSize, except when the user input buffer
  16296. * is directly used as sliding window.
  16297. */
  16298. this.prev = null;
  16299. /* Link to older string with same hash index. To limit the size of this
  16300. * array to 64K, this link is maintained only for the last 32K strings.
  16301. * An index in this array is thus a window index modulo 32K.
  16302. */
  16303. this.head = null; /* Heads of the hash chains or NIL. */
  16304. this.ins_h = 0; /* hash index of string to be inserted */
  16305. this.hash_size = 0; /* number of elements in hash table */
  16306. this.hash_bits = 0; /* log2(hash_size) */
  16307. this.hash_mask = 0; /* hash_size-1 */
  16308. this.hash_shift = 0;
  16309. /* Number of bits by which ins_h must be shifted at each input
  16310. * step. It must be such that after MIN_MATCH steps, the oldest
  16311. * byte no longer takes part in the hash key, that is:
  16312. * hash_shift * MIN_MATCH >= hash_bits
  16313. */
  16314. this.block_start = 0;
  16315. /* Window position at the beginning of the current output block. Gets
  16316. * negative when the window is moved backwards.
  16317. */
  16318. this.match_length = 0; /* length of best match */
  16319. this.prev_match = 0; /* previous match */
  16320. this.match_available = 0; /* set if previous match exists */
  16321. this.strstart = 0; /* start of string to insert */
  16322. this.match_start = 0; /* start of matching string */
  16323. this.lookahead = 0; /* number of valid bytes ahead in window */
  16324. this.prev_length = 0;
  16325. /* Length of the best match at previous step. Matches not greater than this
  16326. * are discarded. This is used in the lazy match evaluation.
  16327. */
  16328. this.max_chain_length = 0;
  16329. /* To speed up deflation, hash chains are never searched beyond this
  16330. * length. A higher limit improves compression ratio but degrades the
  16331. * speed.
  16332. */
  16333. this.max_lazy_match = 0;
  16334. /* Attempt to find a better match only when the current match is strictly
  16335. * smaller than this value. This mechanism is used only for compression
  16336. * levels >= 4.
  16337. */
  16338. // That's alias to max_lazy_match, don't use directly
  16339. //this.max_insert_length = 0;
  16340. /* Insert new strings in the hash table only if the match length is not
  16341. * greater than this length. This saves time but degrades compression.
  16342. * max_insert_length is used only for compression levels <= 3.
  16343. */
  16344. this.level = 0; /* compression level (1..9) */
  16345. this.strategy = 0; /* favor or force Huffman coding*/
  16346. this.good_match = 0;
  16347. /* Use a faster search when the previous match is longer than this */
  16348. this.nice_match = 0; /* Stop searching when current match exceeds this */
  16349. /* used by trees.c: */
  16350. /* Didn't use ct_data typedef below to suppress compiler warning */
  16351. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  16352. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  16353. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  16354. // Use flat array of DOUBLE size, with interleaved fata,
  16355. // because JS does not support effective
  16356. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  16357. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  16358. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  16359. zero(this.dyn_ltree);
  16360. zero(this.dyn_dtree);
  16361. zero(this.bl_tree);
  16362. this.l_desc = null; /* desc. for literal tree */
  16363. this.d_desc = null; /* desc. for distance tree */
  16364. this.bl_desc = null; /* desc. for bit length tree */
  16365. //ush bl_count[MAX_BITS+1];
  16366. this.bl_count = new utils.Buf16(MAX_BITS+1);
  16367. /* number of codes at each bit length for an optimal tree */
  16368. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  16369. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  16370. zero(this.heap);
  16371. this.heap_len = 0; /* number of elements in the heap */
  16372. this.heap_max = 0; /* element of largest frequency */
  16373. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  16374. * The same heap array is used to build all trees.
  16375. */
  16376. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  16377. zero(this.depth);
  16378. /* Depth of each subtree used as tie breaker for trees of equal frequency
  16379. */
  16380. this.l_buf = 0; /* buffer index for literals or lengths */
  16381. this.lit_bufsize = 0;
  16382. /* Size of match buffer for literals/lengths. There are 4 reasons for
  16383. * limiting lit_bufsize to 64K:
  16384. * - frequencies can be kept in 16 bit counters
  16385. * - if compression is not successful for the first block, all input
  16386. * data is still in the window so we can still emit a stored block even
  16387. * when input comes from standard input. (This can also be done for
  16388. * all blocks if lit_bufsize is not greater than 32K.)
  16389. * - if compression is not successful for a file smaller than 64K, we can
  16390. * even emit a stored file instead of a stored block (saving 5 bytes).
  16391. * This is applicable only for zip (not gzip or zlib).
  16392. * - creating new Huffman trees less frequently may not provide fast
  16393. * adaptation to changes in the input data statistics. (Take for
  16394. * example a binary file with poorly compressible code followed by
  16395. * a highly compressible string table.) Smaller buffer sizes give
  16396. * fast adaptation but have of course the overhead of transmitting
  16397. * trees more frequently.
  16398. * - I can't count above 4
  16399. */
  16400. this.last_lit = 0; /* running index in l_buf */
  16401. this.d_buf = 0;
  16402. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  16403. * the same number of elements. To use different lengths, an extra flag
  16404. * array would be necessary.
  16405. */
  16406. this.opt_len = 0; /* bit length of current block with optimal trees */
  16407. this.static_len = 0; /* bit length of current block with static trees */
  16408. this.matches = 0; /* number of string matches in current block */
  16409. this.insert = 0; /* bytes at end of window left to insert */
  16410. this.bi_buf = 0;
  16411. /* Output buffer. bits are inserted starting at the bottom (least
  16412. * significant bits).
  16413. */
  16414. this.bi_valid = 0;
  16415. /* Number of valid bits in bi_buf. All bits above the last valid bit
  16416. * are always zero.
  16417. */
  16418. // Used for window memory init. We safely ignore it for JS. That makes
  16419. // sense only for pointers and memory check tools.
  16420. //this.high_water = 0;
  16421. /* High water mark offset in window for initialized bytes -- bytes above
  16422. * this are set to zero in order to avoid memory check warnings when
  16423. * longest match routines access bytes past the input. This is then
  16424. * updated to the new high water mark.
  16425. */
  16426. }
  16427. function deflateResetKeep(strm) {
  16428. var s;
  16429. if (!strm || !strm.state) {
  16430. return err(strm, Z_STREAM_ERROR);
  16431. }
  16432. strm.total_in = strm.total_out = 0;
  16433. strm.data_type = Z_UNKNOWN;
  16434. s = strm.state;
  16435. s.pending = 0;
  16436. s.pending_out = 0;
  16437. if (s.wrap < 0) {
  16438. s.wrap = -s.wrap;
  16439. /* was made negative by deflate(..., Z_FINISH); */
  16440. }
  16441. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  16442. strm.adler = (s.wrap === 2) ?
  16443. 0 // crc32(0, Z_NULL, 0)
  16444. :
  16445. 1; // adler32(0, Z_NULL, 0)
  16446. s.last_flush = Z_NO_FLUSH;
  16447. trees._tr_init(s);
  16448. return Z_OK;
  16449. }
  16450. function deflateReset(strm) {
  16451. var ret = deflateResetKeep(strm);
  16452. if (ret === Z_OK) {
  16453. lm_init(strm.state);
  16454. }
  16455. return ret;
  16456. }
  16457. function deflateSetHeader(strm, head) {
  16458. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16459. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  16460. strm.state.gzhead = head;
  16461. return Z_OK;
  16462. }
  16463. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  16464. if (!strm) { // === Z_NULL
  16465. return Z_STREAM_ERROR;
  16466. }
  16467. var wrap = 1;
  16468. if (level === Z_DEFAULT_COMPRESSION) {
  16469. level = 6;
  16470. }
  16471. if (windowBits < 0) { /* suppress zlib wrapper */
  16472. wrap = 0;
  16473. windowBits = -windowBits;
  16474. }
  16475. else if (windowBits > 15) {
  16476. wrap = 2; /* write gzip wrapper instead */
  16477. windowBits -= 16;
  16478. }
  16479. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  16480. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  16481. strategy < 0 || strategy > Z_FIXED) {
  16482. return err(strm, Z_STREAM_ERROR);
  16483. }
  16484. if (windowBits === 8) {
  16485. windowBits = 9;
  16486. }
  16487. /* until 256-byte window bug fixed */
  16488. var s = new DeflateState();
  16489. strm.state = s;
  16490. s.strm = strm;
  16491. s.wrap = wrap;
  16492. s.gzhead = null;
  16493. s.w_bits = windowBits;
  16494. s.w_size = 1 << s.w_bits;
  16495. s.w_mask = s.w_size - 1;
  16496. s.hash_bits = memLevel + 7;
  16497. s.hash_size = 1 << s.hash_bits;
  16498. s.hash_mask = s.hash_size - 1;
  16499. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  16500. s.window = new utils.Buf8(s.w_size * 2);
  16501. s.head = new utils.Buf16(s.hash_size);
  16502. s.prev = new utils.Buf16(s.w_size);
  16503. // Don't need mem init magic for JS.
  16504. //s.high_water = 0; /* nothing written to s->window yet */
  16505. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  16506. s.pending_buf_size = s.lit_bufsize * 4;
  16507. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  16508. s.d_buf = s.lit_bufsize >> 1;
  16509. s.l_buf = (1 + 2) * s.lit_bufsize;
  16510. s.level = level;
  16511. s.strategy = strategy;
  16512. s.method = method;
  16513. return deflateReset(strm);
  16514. }
  16515. function deflateInit(strm, level) {
  16516. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  16517. }
  16518. function deflate(strm, flush) {
  16519. var old_flush, s;
  16520. var beg, val; // for gzip header write only
  16521. if (!strm || !strm.state ||
  16522. flush > Z_BLOCK || flush < 0) {
  16523. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  16524. }
  16525. s = strm.state;
  16526. if (!strm.output ||
  16527. (!strm.input && strm.avail_in !== 0) ||
  16528. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  16529. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  16530. }
  16531. s.strm = strm; /* just in case */
  16532. old_flush = s.last_flush;
  16533. s.last_flush = flush;
  16534. /* Write the header */
  16535. if (s.status === INIT_STATE) {
  16536. if (s.wrap === 2) { // GZIP header
  16537. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16538. put_byte(s, 31);
  16539. put_byte(s, 139);
  16540. put_byte(s, 8);
  16541. if (!s.gzhead) { // s->gzhead == Z_NULL
  16542. put_byte(s, 0);
  16543. put_byte(s, 0);
  16544. put_byte(s, 0);
  16545. put_byte(s, 0);
  16546. put_byte(s, 0);
  16547. put_byte(s, s.level === 9 ? 2 :
  16548. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16549. 4 : 0));
  16550. put_byte(s, OS_CODE);
  16551. s.status = BUSY_STATE;
  16552. }
  16553. else {
  16554. put_byte(s, (s.gzhead.text ? 1 : 0) +
  16555. (s.gzhead.hcrc ? 2 : 0) +
  16556. (!s.gzhead.extra ? 0 : 4) +
  16557. (!s.gzhead.name ? 0 : 8) +
  16558. (!s.gzhead.comment ? 0 : 16)
  16559. );
  16560. put_byte(s, s.gzhead.time & 0xff);
  16561. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  16562. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  16563. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  16564. put_byte(s, s.level === 9 ? 2 :
  16565. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16566. 4 : 0));
  16567. put_byte(s, s.gzhead.os & 0xff);
  16568. if (s.gzhead.extra && s.gzhead.extra.length) {
  16569. put_byte(s, s.gzhead.extra.length & 0xff);
  16570. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  16571. }
  16572. if (s.gzhead.hcrc) {
  16573. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  16574. }
  16575. s.gzindex = 0;
  16576. s.status = EXTRA_STATE;
  16577. }
  16578. }
  16579. else // DEFLATE header
  16580. {
  16581. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  16582. var level_flags = -1;
  16583. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  16584. level_flags = 0;
  16585. } else if (s.level < 6) {
  16586. level_flags = 1;
  16587. } else if (s.level === 6) {
  16588. level_flags = 2;
  16589. } else {
  16590. level_flags = 3;
  16591. }
  16592. header |= (level_flags << 6);
  16593. if (s.strstart !== 0) { header |= PRESET_DICT; }
  16594. header += 31 - (header % 31);
  16595. s.status = BUSY_STATE;
  16596. putShortMSB(s, header);
  16597. /* Save the adler32 of the preset dictionary: */
  16598. if (s.strstart !== 0) {
  16599. putShortMSB(s, strm.adler >>> 16);
  16600. putShortMSB(s, strm.adler & 0xffff);
  16601. }
  16602. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  16603. }
  16604. }
  16605. //#ifdef GZIP
  16606. if (s.status === EXTRA_STATE) {
  16607. if (s.gzhead.extra/* != Z_NULL*/) {
  16608. beg = s.pending; /* start of bytes to update crc */
  16609. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  16610. if (s.pending === s.pending_buf_size) {
  16611. if (s.gzhead.hcrc && s.pending > beg) {
  16612. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16613. }
  16614. flush_pending(strm);
  16615. beg = s.pending;
  16616. if (s.pending === s.pending_buf_size) {
  16617. break;
  16618. }
  16619. }
  16620. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  16621. s.gzindex++;
  16622. }
  16623. if (s.gzhead.hcrc && s.pending > beg) {
  16624. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16625. }
  16626. if (s.gzindex === s.gzhead.extra.length) {
  16627. s.gzindex = 0;
  16628. s.status = NAME_STATE;
  16629. }
  16630. }
  16631. else {
  16632. s.status = NAME_STATE;
  16633. }
  16634. }
  16635. if (s.status === NAME_STATE) {
  16636. if (s.gzhead.name/* != Z_NULL*/) {
  16637. beg = s.pending; /* start of bytes to update crc */
  16638. //int val;
  16639. do {
  16640. if (s.pending === s.pending_buf_size) {
  16641. if (s.gzhead.hcrc && s.pending > beg) {
  16642. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16643. }
  16644. flush_pending(strm);
  16645. beg = s.pending;
  16646. if (s.pending === s.pending_buf_size) {
  16647. val = 1;
  16648. break;
  16649. }
  16650. }
  16651. // JS specific: little magic to add zero terminator to end of string
  16652. if (s.gzindex < s.gzhead.name.length) {
  16653. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  16654. } else {
  16655. val = 0;
  16656. }
  16657. put_byte(s, val);
  16658. } while (val !== 0);
  16659. if (s.gzhead.hcrc && s.pending > beg) {
  16660. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16661. }
  16662. if (val === 0) {
  16663. s.gzindex = 0;
  16664. s.status = COMMENT_STATE;
  16665. }
  16666. }
  16667. else {
  16668. s.status = COMMENT_STATE;
  16669. }
  16670. }
  16671. if (s.status === COMMENT_STATE) {
  16672. if (s.gzhead.comment/* != Z_NULL*/) {
  16673. beg = s.pending; /* start of bytes to update crc */
  16674. //int val;
  16675. do {
  16676. if (s.pending === s.pending_buf_size) {
  16677. if (s.gzhead.hcrc && s.pending > beg) {
  16678. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16679. }
  16680. flush_pending(strm);
  16681. beg = s.pending;
  16682. if (s.pending === s.pending_buf_size) {
  16683. val = 1;
  16684. break;
  16685. }
  16686. }
  16687. // JS specific: little magic to add zero terminator to end of string
  16688. if (s.gzindex < s.gzhead.comment.length) {
  16689. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  16690. } else {
  16691. val = 0;
  16692. }
  16693. put_byte(s, val);
  16694. } while (val !== 0);
  16695. if (s.gzhead.hcrc && s.pending > beg) {
  16696. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16697. }
  16698. if (val === 0) {
  16699. s.status = HCRC_STATE;
  16700. }
  16701. }
  16702. else {
  16703. s.status = HCRC_STATE;
  16704. }
  16705. }
  16706. if (s.status === HCRC_STATE) {
  16707. if (s.gzhead.hcrc) {
  16708. if (s.pending + 2 > s.pending_buf_size) {
  16709. flush_pending(strm);
  16710. }
  16711. if (s.pending + 2 <= s.pending_buf_size) {
  16712. put_byte(s, strm.adler & 0xff);
  16713. put_byte(s, (strm.adler >> 8) & 0xff);
  16714. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16715. s.status = BUSY_STATE;
  16716. }
  16717. }
  16718. else {
  16719. s.status = BUSY_STATE;
  16720. }
  16721. }
  16722. //#endif
  16723. /* Flush as much pending output as possible */
  16724. if (s.pending !== 0) {
  16725. flush_pending(strm);
  16726. if (strm.avail_out === 0) {
  16727. /* Since avail_out is 0, deflate will be called again with
  16728. * more output space, but possibly with both pending and
  16729. * avail_in equal to zero. There won't be anything to do,
  16730. * but this is not an error situation so make sure we
  16731. * return OK instead of BUF_ERROR at next call of deflate:
  16732. */
  16733. s.last_flush = -1;
  16734. return Z_OK;
  16735. }
  16736. /* Make sure there is something to do and avoid duplicate consecutive
  16737. * flushes. For repeated and useless calls with Z_FINISH, we keep
  16738. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  16739. */
  16740. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  16741. flush !== Z_FINISH) {
  16742. return err(strm, Z_BUF_ERROR);
  16743. }
  16744. /* User must not provide more input after the first FINISH: */
  16745. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  16746. return err(strm, Z_BUF_ERROR);
  16747. }
  16748. /* Start a new block or continue the current one.
  16749. */
  16750. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  16751. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  16752. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  16753. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  16754. configuration_table[s.level].func(s, flush));
  16755. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  16756. s.status = FINISH_STATE;
  16757. }
  16758. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  16759. if (strm.avail_out === 0) {
  16760. s.last_flush = -1;
  16761. /* avoid BUF_ERROR next call, see above */
  16762. }
  16763. return Z_OK;
  16764. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  16765. * of deflate should use the same flush parameter to make sure
  16766. * that the flush is complete. So we don't have to output an
  16767. * empty block here, this will be done at next call. This also
  16768. * ensures that for a very small output buffer, we emit at most
  16769. * one empty block.
  16770. */
  16771. }
  16772. if (bstate === BS_BLOCK_DONE) {
  16773. if (flush === Z_PARTIAL_FLUSH) {
  16774. trees._tr_align(s);
  16775. }
  16776. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  16777. trees._tr_stored_block(s, 0, 0, false);
  16778. /* For a full flush, this empty block will be recognized
  16779. * as a special marker by inflate_sync().
  16780. */
  16781. if (flush === Z_FULL_FLUSH) {
  16782. /*** CLEAR_HASH(s); ***/ /* forget history */
  16783. zero(s.head); // Fill with NIL (= 0);
  16784. if (s.lookahead === 0) {
  16785. s.strstart = 0;
  16786. s.block_start = 0;
  16787. s.insert = 0;
  16788. }
  16789. }
  16790. }
  16791. flush_pending(strm);
  16792. if (strm.avail_out === 0) {
  16793. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  16794. return Z_OK;
  16795. }
  16796. }
  16797. }
  16798. //Assert(strm->avail_out > 0, "bug2");
  16799. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  16800. if (flush !== Z_FINISH) { return Z_OK; }
  16801. if (s.wrap <= 0) { return Z_STREAM_END; }
  16802. /* Write the trailer */
  16803. if (s.wrap === 2) {
  16804. put_byte(s, strm.adler & 0xff);
  16805. put_byte(s, (strm.adler >> 8) & 0xff);
  16806. put_byte(s, (strm.adler >> 16) & 0xff);
  16807. put_byte(s, (strm.adler >> 24) & 0xff);
  16808. put_byte(s, strm.total_in & 0xff);
  16809. put_byte(s, (strm.total_in >> 8) & 0xff);
  16810. put_byte(s, (strm.total_in >> 16) & 0xff);
  16811. put_byte(s, (strm.total_in >> 24) & 0xff);
  16812. }
  16813. else
  16814. {
  16815. putShortMSB(s, strm.adler >>> 16);
  16816. putShortMSB(s, strm.adler & 0xffff);
  16817. }
  16818. flush_pending(strm);
  16819. /* If avail_out is zero, the application will call deflate again
  16820. * to flush the rest.
  16821. */
  16822. if (s.wrap > 0) { s.wrap = -s.wrap; }
  16823. /* write the trailer only once! */
  16824. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  16825. }
  16826. function deflateEnd(strm) {
  16827. var status;
  16828. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  16829. return Z_STREAM_ERROR;
  16830. }
  16831. status = strm.state.status;
  16832. if (status !== INIT_STATE &&
  16833. status !== EXTRA_STATE &&
  16834. status !== NAME_STATE &&
  16835. status !== COMMENT_STATE &&
  16836. status !== HCRC_STATE &&
  16837. status !== BUSY_STATE &&
  16838. status !== FINISH_STATE
  16839. ) {
  16840. return err(strm, Z_STREAM_ERROR);
  16841. }
  16842. strm.state = null;
  16843. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  16844. }
  16845. /* =========================================================================
  16846. * Copy the source state to the destination state
  16847. */
  16848. //function deflateCopy(dest, source) {
  16849. //
  16850. //}
  16851. exports.deflateInit = deflateInit;
  16852. exports.deflateInit2 = deflateInit2;
  16853. exports.deflateReset = deflateReset;
  16854. exports.deflateResetKeep = deflateResetKeep;
  16855. exports.deflateSetHeader = deflateSetHeader;
  16856. exports.deflate = deflate;
  16857. exports.deflateEnd = deflateEnd;
  16858. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  16859. /* Not implemented
  16860. exports.deflateBound = deflateBound;
  16861. exports.deflateCopy = deflateCopy;
  16862. exports.deflateSetDictionary = deflateSetDictionary;
  16863. exports.deflateParams = deflateParams;
  16864. exports.deflatePending = deflatePending;
  16865. exports.deflatePrime = deflatePrime;
  16866. exports.deflateTune = deflateTune;
  16867. */
  16868. },{"../utils/common":54,"./adler32":56,"./crc32":58,"./messages":64,"./trees":65}],60:[function(require,module,exports){
  16869. 'use strict';
  16870. function GZheader() {
  16871. /* true if compressed data believed to be text */
  16872. this.text = 0;
  16873. /* modification time */
  16874. this.time = 0;
  16875. /* extra flags (not used when writing a gzip file) */
  16876. this.xflags = 0;
  16877. /* operating system */
  16878. this.os = 0;
  16879. /* pointer to extra field or Z_NULL if none */
  16880. this.extra = null;
  16881. /* extra field length (valid if extra != Z_NULL) */
  16882. this.extra_len = 0; // Actually, we don't need it in JS,
  16883. // but leave for few code modifications
  16884. //
  16885. // Setup limits is not necessary because in js we should not preallocate memory
  16886. // for inflate use constant limit in 65536 bytes
  16887. //
  16888. /* space at extra (only when reading header) */
  16889. // this.extra_max = 0;
  16890. /* pointer to zero-terminated file name or Z_NULL */
  16891. this.name = '';
  16892. /* space at name (only when reading header) */
  16893. // this.name_max = 0;
  16894. /* pointer to zero-terminated comment or Z_NULL */
  16895. this.comment = '';
  16896. /* space at comment (only when reading header) */
  16897. // this.comm_max = 0;
  16898. /* true if there was or will be a header crc */
  16899. this.hcrc = 0;
  16900. /* true when done reading gzip header (not used when writing a gzip file) */
  16901. this.done = false;
  16902. }
  16903. module.exports = GZheader;
  16904. },{}],61:[function(require,module,exports){
  16905. 'use strict';
  16906. // See state defs from inflate.js
  16907. var BAD = 30; /* got a data error -- remain here until reset */
  16908. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16909. /*
  16910. Decode literal, length, and distance codes and write out the resulting
  16911. literal and match bytes until either not enough input or output is
  16912. available, an end-of-block is encountered, or a data error is encountered.
  16913. When large enough input and output buffers are supplied to inflate(), for
  16914. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  16915. inflate execution time is spent in this routine.
  16916. Entry assumptions:
  16917. state.mode === LEN
  16918. strm.avail_in >= 6
  16919. strm.avail_out >= 258
  16920. start >= strm.avail_out
  16921. state.bits < 8
  16922. On return, state.mode is one of:
  16923. LEN -- ran out of enough output space or enough available input
  16924. TYPE -- reached end of block code, inflate() to interpret next block
  16925. BAD -- error in block data
  16926. Notes:
  16927. - The maximum input bits used by a length/distance pair is 15 bits for the
  16928. length code, 5 bits for the length extra, 15 bits for the distance code,
  16929. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  16930. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  16931. checking for available input while decoding.
  16932. - The maximum bytes that a single length/distance pair can output is 258
  16933. bytes, which is the maximum length that can be coded. inflate_fast()
  16934. requires strm.avail_out >= 258 for each loop to avoid checking for
  16935. output space.
  16936. */
  16937. module.exports = function inflate_fast(strm, start) {
  16938. var state;
  16939. var _in; /* local strm.input */
  16940. var last; /* have enough input while in < last */
  16941. var _out; /* local strm.output */
  16942. var beg; /* inflate()'s initial strm.output */
  16943. var end; /* while out < end, enough space available */
  16944. //#ifdef INFLATE_STRICT
  16945. var dmax; /* maximum distance from zlib header */
  16946. //#endif
  16947. var wsize; /* window size or zero if not using window */
  16948. var whave; /* valid bytes in the window */
  16949. var wnext; /* window write index */
  16950. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  16951. var s_window; /* allocated sliding window, if wsize != 0 */
  16952. var hold; /* local strm.hold */
  16953. var bits; /* local strm.bits */
  16954. var lcode; /* local strm.lencode */
  16955. var dcode; /* local strm.distcode */
  16956. var lmask; /* mask for first level of length codes */
  16957. var dmask; /* mask for first level of distance codes */
  16958. var here; /* retrieved table entry */
  16959. var op; /* code bits, operation, extra bits, or */
  16960. /* window position, window bytes to copy */
  16961. var len; /* match length, unused bytes */
  16962. var dist; /* match distance */
  16963. var from; /* where to copy match from */
  16964. var from_source;
  16965. var input, output; // JS specific, because we have no pointers
  16966. /* copy state to local variables */
  16967. state = strm.state;
  16968. //here = state.here;
  16969. _in = strm.next_in;
  16970. input = strm.input;
  16971. last = _in + (strm.avail_in - 5);
  16972. _out = strm.next_out;
  16973. output = strm.output;
  16974. beg = _out - (start - strm.avail_out);
  16975. end = _out + (strm.avail_out - 257);
  16976. //#ifdef INFLATE_STRICT
  16977. dmax = state.dmax;
  16978. //#endif
  16979. wsize = state.wsize;
  16980. whave = state.whave;
  16981. wnext = state.wnext;
  16982. s_window = state.window;
  16983. hold = state.hold;
  16984. bits = state.bits;
  16985. lcode = state.lencode;
  16986. dcode = state.distcode;
  16987. lmask = (1 << state.lenbits) - 1;
  16988. dmask = (1 << state.distbits) - 1;
  16989. /* decode literals and length/distances until end-of-block or not enough
  16990. input data or output space */
  16991. top:
  16992. do {
  16993. if (bits < 15) {
  16994. hold += input[_in++] << bits;
  16995. bits += 8;
  16996. hold += input[_in++] << bits;
  16997. bits += 8;
  16998. }
  16999. here = lcode[hold & lmask];
  17000. dolen:
  17001. for (;;) { // Goto emulation
  17002. op = here >>> 24/*here.bits*/;
  17003. hold >>>= op;
  17004. bits -= op;
  17005. op = (here >>> 16) & 0xff/*here.op*/;
  17006. if (op === 0) { /* literal */
  17007. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17008. // "inflate: literal '%c'\n" :
  17009. // "inflate: literal 0x%02x\n", here.val));
  17010. output[_out++] = here & 0xffff/*here.val*/;
  17011. }
  17012. else if (op & 16) { /* length base */
  17013. len = here & 0xffff/*here.val*/;
  17014. op &= 15; /* number of extra bits */
  17015. if (op) {
  17016. if (bits < op) {
  17017. hold += input[_in++] << bits;
  17018. bits += 8;
  17019. }
  17020. len += hold & ((1 << op) - 1);
  17021. hold >>>= op;
  17022. bits -= op;
  17023. }
  17024. //Tracevv((stderr, "inflate: length %u\n", len));
  17025. if (bits < 15) {
  17026. hold += input[_in++] << bits;
  17027. bits += 8;
  17028. hold += input[_in++] << bits;
  17029. bits += 8;
  17030. }
  17031. here = dcode[hold & dmask];
  17032. dodist:
  17033. for (;;) { // goto emulation
  17034. op = here >>> 24/*here.bits*/;
  17035. hold >>>= op;
  17036. bits -= op;
  17037. op = (here >>> 16) & 0xff/*here.op*/;
  17038. if (op & 16) { /* distance base */
  17039. dist = here & 0xffff/*here.val*/;
  17040. op &= 15; /* number of extra bits */
  17041. if (bits < op) {
  17042. hold += input[_in++] << bits;
  17043. bits += 8;
  17044. if (bits < op) {
  17045. hold += input[_in++] << bits;
  17046. bits += 8;
  17047. }
  17048. }
  17049. dist += hold & ((1 << op) - 1);
  17050. //#ifdef INFLATE_STRICT
  17051. if (dist > dmax) {
  17052. strm.msg = 'invalid distance too far back';
  17053. state.mode = BAD;
  17054. break top;
  17055. }
  17056. //#endif
  17057. hold >>>= op;
  17058. bits -= op;
  17059. //Tracevv((stderr, "inflate: distance %u\n", dist));
  17060. op = _out - beg; /* max distance in output */
  17061. if (dist > op) { /* see if copy from window */
  17062. op = dist - op; /* distance back in window */
  17063. if (op > whave) {
  17064. if (state.sane) {
  17065. strm.msg = 'invalid distance too far back';
  17066. state.mode = BAD;
  17067. break top;
  17068. }
  17069. // (!) This block is disabled in zlib defailts,
  17070. // don't enable it for binary compatibility
  17071. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17072. // if (len <= op - whave) {
  17073. // do {
  17074. // output[_out++] = 0;
  17075. // } while (--len);
  17076. // continue top;
  17077. // }
  17078. // len -= op - whave;
  17079. // do {
  17080. // output[_out++] = 0;
  17081. // } while (--op > whave);
  17082. // if (op === 0) {
  17083. // from = _out - dist;
  17084. // do {
  17085. // output[_out++] = output[from++];
  17086. // } while (--len);
  17087. // continue top;
  17088. // }
  17089. //#endif
  17090. }
  17091. from = 0; // window index
  17092. from_source = s_window;
  17093. if (wnext === 0) { /* very common case */
  17094. from += wsize - op;
  17095. if (op < len) { /* some from window */
  17096. len -= op;
  17097. do {
  17098. output[_out++] = s_window[from++];
  17099. } while (--op);
  17100. from = _out - dist; /* rest from output */
  17101. from_source = output;
  17102. }
  17103. }
  17104. else if (wnext < op) { /* wrap around window */
  17105. from += wsize + wnext - op;
  17106. op -= wnext;
  17107. if (op < len) { /* some from end of window */
  17108. len -= op;
  17109. do {
  17110. output[_out++] = s_window[from++];
  17111. } while (--op);
  17112. from = 0;
  17113. if (wnext < len) { /* some from start of window */
  17114. op = wnext;
  17115. len -= op;
  17116. do {
  17117. output[_out++] = s_window[from++];
  17118. } while (--op);
  17119. from = _out - dist; /* rest from output */
  17120. from_source = output;
  17121. }
  17122. }
  17123. }
  17124. else { /* contiguous in window */
  17125. from += wnext - op;
  17126. if (op < len) { /* some from window */
  17127. len -= op;
  17128. do {
  17129. output[_out++] = s_window[from++];
  17130. } while (--op);
  17131. from = _out - dist; /* rest from output */
  17132. from_source = output;
  17133. }
  17134. }
  17135. while (len > 2) {
  17136. output[_out++] = from_source[from++];
  17137. output[_out++] = from_source[from++];
  17138. output[_out++] = from_source[from++];
  17139. len -= 3;
  17140. }
  17141. if (len) {
  17142. output[_out++] = from_source[from++];
  17143. if (len > 1) {
  17144. output[_out++] = from_source[from++];
  17145. }
  17146. }
  17147. }
  17148. else {
  17149. from = _out - dist; /* copy direct from output */
  17150. do { /* minimum length is three */
  17151. output[_out++] = output[from++];
  17152. output[_out++] = output[from++];
  17153. output[_out++] = output[from++];
  17154. len -= 3;
  17155. } while (len > 2);
  17156. if (len) {
  17157. output[_out++] = output[from++];
  17158. if (len > 1) {
  17159. output[_out++] = output[from++];
  17160. }
  17161. }
  17162. }
  17163. }
  17164. else if ((op & 64) === 0) { /* 2nd level distance code */
  17165. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17166. continue dodist;
  17167. }
  17168. else {
  17169. strm.msg = 'invalid distance code';
  17170. state.mode = BAD;
  17171. break top;
  17172. }
  17173. break; // need to emulate goto via "continue"
  17174. }
  17175. }
  17176. else if ((op & 64) === 0) { /* 2nd level length code */
  17177. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17178. continue dolen;
  17179. }
  17180. else if (op & 32) { /* end-of-block */
  17181. //Tracevv((stderr, "inflate: end of block\n"));
  17182. state.mode = TYPE;
  17183. break top;
  17184. }
  17185. else {
  17186. strm.msg = 'invalid literal/length code';
  17187. state.mode = BAD;
  17188. break top;
  17189. }
  17190. break; // need to emulate goto via "continue"
  17191. }
  17192. } while (_in < last && _out < end);
  17193. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  17194. len = bits >> 3;
  17195. _in -= len;
  17196. bits -= len << 3;
  17197. hold &= (1 << bits) - 1;
  17198. /* update state and return */
  17199. strm.next_in = _in;
  17200. strm.next_out = _out;
  17201. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  17202. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  17203. state.hold = hold;
  17204. state.bits = bits;
  17205. return;
  17206. };
  17207. },{}],62:[function(require,module,exports){
  17208. 'use strict';
  17209. var utils = require('../utils/common');
  17210. var adler32 = require('./adler32');
  17211. var crc32 = require('./crc32');
  17212. var inflate_fast = require('./inffast');
  17213. var inflate_table = require('./inftrees');
  17214. var CODES = 0;
  17215. var LENS = 1;
  17216. var DISTS = 2;
  17217. /* Public constants ==========================================================*/
  17218. /* ===========================================================================*/
  17219. /* Allowed flush values; see deflate() and inflate() below for details */
  17220. //var Z_NO_FLUSH = 0;
  17221. //var Z_PARTIAL_FLUSH = 1;
  17222. //var Z_SYNC_FLUSH = 2;
  17223. //var Z_FULL_FLUSH = 3;
  17224. var Z_FINISH = 4;
  17225. var Z_BLOCK = 5;
  17226. var Z_TREES = 6;
  17227. /* Return codes for the compression/decompression functions. Negative values
  17228. * are errors, positive values are used for special but normal events.
  17229. */
  17230. var Z_OK = 0;
  17231. var Z_STREAM_END = 1;
  17232. var Z_NEED_DICT = 2;
  17233. //var Z_ERRNO = -1;
  17234. var Z_STREAM_ERROR = -2;
  17235. var Z_DATA_ERROR = -3;
  17236. var Z_MEM_ERROR = -4;
  17237. var Z_BUF_ERROR = -5;
  17238. //var Z_VERSION_ERROR = -6;
  17239. /* The deflate compression method */
  17240. var Z_DEFLATED = 8;
  17241. /* STATES ====================================================================*/
  17242. /* ===========================================================================*/
  17243. var HEAD = 1; /* i: waiting for magic header */
  17244. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  17245. var TIME = 3; /* i: waiting for modification time (gzip) */
  17246. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  17247. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  17248. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  17249. var NAME = 7; /* i: waiting for end of file name (gzip) */
  17250. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  17251. var HCRC = 9; /* i: waiting for header crc (gzip) */
  17252. var DICTID = 10; /* i: waiting for dictionary check value */
  17253. var DICT = 11; /* waiting for inflateSetDictionary() call */
  17254. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17255. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  17256. var STORED = 14; /* i: waiting for stored size (length and complement) */
  17257. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  17258. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  17259. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  17260. var LENLENS = 18; /* i: waiting for code length code lengths */
  17261. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  17262. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  17263. var LEN = 21; /* i: waiting for length/lit/eob code */
  17264. var LENEXT = 22; /* i: waiting for length extra bits */
  17265. var DIST = 23; /* i: waiting for distance code */
  17266. var DISTEXT = 24; /* i: waiting for distance extra bits */
  17267. var MATCH = 25; /* o: waiting for output space to copy string */
  17268. var LIT = 26; /* o: waiting for output space to write literal */
  17269. var CHECK = 27; /* i: waiting for 32-bit check value */
  17270. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  17271. var DONE = 29; /* finished check, done -- remain here until reset */
  17272. var BAD = 30; /* got a data error -- remain here until reset */
  17273. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  17274. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  17275. /* ===========================================================================*/
  17276. var ENOUGH_LENS = 852;
  17277. var ENOUGH_DISTS = 592;
  17278. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17279. var MAX_WBITS = 15;
  17280. /* 32K LZ77 window */
  17281. var DEF_WBITS = MAX_WBITS;
  17282. function ZSWAP32(q) {
  17283. return (((q >>> 24) & 0xff) +
  17284. ((q >>> 8) & 0xff00) +
  17285. ((q & 0xff00) << 8) +
  17286. ((q & 0xff) << 24));
  17287. }
  17288. function InflateState() {
  17289. this.mode = 0; /* current inflate mode */
  17290. this.last = false; /* true if processing last block */
  17291. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  17292. this.havedict = false; /* true if dictionary provided */
  17293. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  17294. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  17295. this.check = 0; /* protected copy of check value */
  17296. this.total = 0; /* protected copy of output count */
  17297. // TODO: may be {}
  17298. this.head = null; /* where to save gzip header information */
  17299. /* sliding window */
  17300. this.wbits = 0; /* log base 2 of requested window size */
  17301. this.wsize = 0; /* window size or zero if not using window */
  17302. this.whave = 0; /* valid bytes in the window */
  17303. this.wnext = 0; /* window write index */
  17304. this.window = null; /* allocated sliding window, if needed */
  17305. /* bit accumulator */
  17306. this.hold = 0; /* input bit accumulator */
  17307. this.bits = 0; /* number of bits in "in" */
  17308. /* for string and stored block copying */
  17309. this.length = 0; /* literal or length of data to copy */
  17310. this.offset = 0; /* distance back to copy string from */
  17311. /* for table and code decoding */
  17312. this.extra = 0; /* extra bits needed */
  17313. /* fixed and dynamic code tables */
  17314. this.lencode = null; /* starting table for length/literal codes */
  17315. this.distcode = null; /* starting table for distance codes */
  17316. this.lenbits = 0; /* index bits for lencode */
  17317. this.distbits = 0; /* index bits for distcode */
  17318. /* dynamic table building */
  17319. this.ncode = 0; /* number of code length code lengths */
  17320. this.nlen = 0; /* number of length code lengths */
  17321. this.ndist = 0; /* number of distance code lengths */
  17322. this.have = 0; /* number of code lengths in lens[] */
  17323. this.next = null; /* next available space in codes[] */
  17324. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  17325. this.work = new utils.Buf16(288); /* work area for code table building */
  17326. /*
  17327. because we don't have pointers in js, we use lencode and distcode directly
  17328. as buffers so we don't need codes
  17329. */
  17330. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  17331. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  17332. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  17333. this.sane = 0; /* if false, allow invalid distance too far */
  17334. this.back = 0; /* bits back of last unprocessed length/lit */
  17335. this.was = 0; /* initial length of match */
  17336. }
  17337. function inflateResetKeep(strm) {
  17338. var state;
  17339. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17340. state = strm.state;
  17341. strm.total_in = strm.total_out = state.total = 0;
  17342. strm.msg = ''; /*Z_NULL*/
  17343. if (state.wrap) { /* to support ill-conceived Java test suite */
  17344. strm.adler = state.wrap & 1;
  17345. }
  17346. state.mode = HEAD;
  17347. state.last = 0;
  17348. state.havedict = 0;
  17349. state.dmax = 32768;
  17350. state.head = null/*Z_NULL*/;
  17351. state.hold = 0;
  17352. state.bits = 0;
  17353. //state.lencode = state.distcode = state.next = state.codes;
  17354. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  17355. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  17356. state.sane = 1;
  17357. state.back = -1;
  17358. //Tracev((stderr, "inflate: reset\n"));
  17359. return Z_OK;
  17360. }
  17361. function inflateReset(strm) {
  17362. var state;
  17363. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17364. state = strm.state;
  17365. state.wsize = 0;
  17366. state.whave = 0;
  17367. state.wnext = 0;
  17368. return inflateResetKeep(strm);
  17369. }
  17370. function inflateReset2(strm, windowBits) {
  17371. var wrap;
  17372. var state;
  17373. /* get the state */
  17374. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17375. state = strm.state;
  17376. /* extract wrap request from windowBits parameter */
  17377. if (windowBits < 0) {
  17378. wrap = 0;
  17379. windowBits = -windowBits;
  17380. }
  17381. else {
  17382. wrap = (windowBits >> 4) + 1;
  17383. if (windowBits < 48) {
  17384. windowBits &= 15;
  17385. }
  17386. }
  17387. /* set number of window bits, free window if different */
  17388. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  17389. return Z_STREAM_ERROR;
  17390. }
  17391. if (state.window !== null && state.wbits !== windowBits) {
  17392. state.window = null;
  17393. }
  17394. /* update state and reset the rest of it */
  17395. state.wrap = wrap;
  17396. state.wbits = windowBits;
  17397. return inflateReset(strm);
  17398. }
  17399. function inflateInit2(strm, windowBits) {
  17400. var ret;
  17401. var state;
  17402. if (!strm) { return Z_STREAM_ERROR; }
  17403. //strm.msg = Z_NULL; /* in case we return an error */
  17404. state = new InflateState();
  17405. //if (state === Z_NULL) return Z_MEM_ERROR;
  17406. //Tracev((stderr, "inflate: allocated\n"));
  17407. strm.state = state;
  17408. state.window = null/*Z_NULL*/;
  17409. ret = inflateReset2(strm, windowBits);
  17410. if (ret !== Z_OK) {
  17411. strm.state = null/*Z_NULL*/;
  17412. }
  17413. return ret;
  17414. }
  17415. function inflateInit(strm) {
  17416. return inflateInit2(strm, DEF_WBITS);
  17417. }
  17418. /*
  17419. Return state with length and distance decoding tables and index sizes set to
  17420. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  17421. If BUILDFIXED is defined, then instead this routine builds the tables the
  17422. first time it's called, and returns those tables the first time and
  17423. thereafter. This reduces the size of the code by about 2K bytes, in
  17424. exchange for a little execution time. However, BUILDFIXED should not be
  17425. used for threaded applications, since the rewriting of the tables and virgin
  17426. may not be thread-safe.
  17427. */
  17428. var virgin = true;
  17429. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  17430. function fixedtables(state) {
  17431. /* build fixed huffman tables if first call (may not be thread safe) */
  17432. if (virgin) {
  17433. var sym;
  17434. lenfix = new utils.Buf32(512);
  17435. distfix = new utils.Buf32(32);
  17436. /* literal/length table */
  17437. sym = 0;
  17438. while (sym < 144) { state.lens[sym++] = 8; }
  17439. while (sym < 256) { state.lens[sym++] = 9; }
  17440. while (sym < 280) { state.lens[sym++] = 7; }
  17441. while (sym < 288) { state.lens[sym++] = 8; }
  17442. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  17443. /* distance table */
  17444. sym = 0;
  17445. while (sym < 32) { state.lens[sym++] = 5; }
  17446. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  17447. /* do this just once */
  17448. virgin = false;
  17449. }
  17450. state.lencode = lenfix;
  17451. state.lenbits = 9;
  17452. state.distcode = distfix;
  17453. state.distbits = 5;
  17454. }
  17455. /*
  17456. Update the window with the last wsize (normally 32K) bytes written before
  17457. returning. If window does not exist yet, create it. This is only called
  17458. when a window is already in use, or when output has been written during this
  17459. inflate call, but the end of the deflate stream has not been reached yet.
  17460. It is also called to create a window for dictionary data when a dictionary
  17461. is loaded.
  17462. Providing output buffers larger than 32K to inflate() should provide a speed
  17463. advantage, since only the last 32K of output is copied to the sliding window
  17464. upon return from inflate(), and since all distances after the first 32K of
  17465. output will fall in the output data, making match copies simpler and faster.
  17466. The advantage may be dependent on the size of the processor's data caches.
  17467. */
  17468. function updatewindow(strm, src, end, copy) {
  17469. var dist;
  17470. var state = strm.state;
  17471. /* if it hasn't been done already, allocate space for the window */
  17472. if (state.window === null) {
  17473. state.wsize = 1 << state.wbits;
  17474. state.wnext = 0;
  17475. state.whave = 0;
  17476. state.window = new utils.Buf8(state.wsize);
  17477. }
  17478. /* copy state->wsize or less output bytes into the circular window */
  17479. if (copy >= state.wsize) {
  17480. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  17481. state.wnext = 0;
  17482. state.whave = state.wsize;
  17483. }
  17484. else {
  17485. dist = state.wsize - state.wnext;
  17486. if (dist > copy) {
  17487. dist = copy;
  17488. }
  17489. //zmemcpy(state->window + state->wnext, end - copy, dist);
  17490. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  17491. copy -= dist;
  17492. if (copy) {
  17493. //zmemcpy(state->window, end - copy, copy);
  17494. utils.arraySet(state.window,src, end - copy, copy, 0);
  17495. state.wnext = copy;
  17496. state.whave = state.wsize;
  17497. }
  17498. else {
  17499. state.wnext += dist;
  17500. if (state.wnext === state.wsize) { state.wnext = 0; }
  17501. if (state.whave < state.wsize) { state.whave += dist; }
  17502. }
  17503. }
  17504. return 0;
  17505. }
  17506. function inflate(strm, flush) {
  17507. var state;
  17508. var input, output; // input/output buffers
  17509. var next; /* next input INDEX */
  17510. var put; /* next output INDEX */
  17511. var have, left; /* available input and output */
  17512. var hold; /* bit buffer */
  17513. var bits; /* bits in bit buffer */
  17514. var _in, _out; /* save starting available input and output */
  17515. var copy; /* number of stored or match bytes to copy */
  17516. var from; /* where to copy match bytes from */
  17517. var from_source;
  17518. var here = 0; /* current decoding table entry */
  17519. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  17520. //var last; /* parent table entry */
  17521. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  17522. var len; /* length to copy for repeats, bits to drop */
  17523. var ret; /* return code */
  17524. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  17525. var opts;
  17526. var n; // temporary var for NEED_BITS
  17527. var order = /* permutation of code lengths */
  17528. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  17529. if (!strm || !strm.state || !strm.output ||
  17530. (!strm.input && strm.avail_in !== 0)) {
  17531. return Z_STREAM_ERROR;
  17532. }
  17533. state = strm.state;
  17534. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  17535. //--- LOAD() ---
  17536. put = strm.next_out;
  17537. output = strm.output;
  17538. left = strm.avail_out;
  17539. next = strm.next_in;
  17540. input = strm.input;
  17541. have = strm.avail_in;
  17542. hold = state.hold;
  17543. bits = state.bits;
  17544. //---
  17545. _in = have;
  17546. _out = left;
  17547. ret = Z_OK;
  17548. inf_leave: // goto emulation
  17549. for (;;) {
  17550. switch (state.mode) {
  17551. case HEAD:
  17552. if (state.wrap === 0) {
  17553. state.mode = TYPEDO;
  17554. break;
  17555. }
  17556. //=== NEEDBITS(16);
  17557. while (bits < 16) {
  17558. if (have === 0) { break inf_leave; }
  17559. have--;
  17560. hold += input[next++] << bits;
  17561. bits += 8;
  17562. }
  17563. //===//
  17564. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  17565. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  17566. //=== CRC2(state.check, hold);
  17567. hbuf[0] = hold & 0xff;
  17568. hbuf[1] = (hold >>> 8) & 0xff;
  17569. state.check = crc32(state.check, hbuf, 2, 0);
  17570. //===//
  17571. //=== INITBITS();
  17572. hold = 0;
  17573. bits = 0;
  17574. //===//
  17575. state.mode = FLAGS;
  17576. break;
  17577. }
  17578. state.flags = 0; /* expect zlib header */
  17579. if (state.head) {
  17580. state.head.done = false;
  17581. }
  17582. if (!(state.wrap & 1) || /* check if zlib header allowed */
  17583. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  17584. strm.msg = 'incorrect header check';
  17585. state.mode = BAD;
  17586. break;
  17587. }
  17588. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  17589. strm.msg = 'unknown compression method';
  17590. state.mode = BAD;
  17591. break;
  17592. }
  17593. //--- DROPBITS(4) ---//
  17594. hold >>>= 4;
  17595. bits -= 4;
  17596. //---//
  17597. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  17598. if (state.wbits === 0) {
  17599. state.wbits = len;
  17600. }
  17601. else if (len > state.wbits) {
  17602. strm.msg = 'invalid window size';
  17603. state.mode = BAD;
  17604. break;
  17605. }
  17606. state.dmax = 1 << len;
  17607. //Tracev((stderr, "inflate: zlib header ok\n"));
  17608. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17609. state.mode = hold & 0x200 ? DICTID : TYPE;
  17610. //=== INITBITS();
  17611. hold = 0;
  17612. bits = 0;
  17613. //===//
  17614. break;
  17615. case FLAGS:
  17616. //=== NEEDBITS(16); */
  17617. while (bits < 16) {
  17618. if (have === 0) { break inf_leave; }
  17619. have--;
  17620. hold += input[next++] << bits;
  17621. bits += 8;
  17622. }
  17623. //===//
  17624. state.flags = hold;
  17625. if ((state.flags & 0xff) !== Z_DEFLATED) {
  17626. strm.msg = 'unknown compression method';
  17627. state.mode = BAD;
  17628. break;
  17629. }
  17630. if (state.flags & 0xe000) {
  17631. strm.msg = 'unknown header flags set';
  17632. state.mode = BAD;
  17633. break;
  17634. }
  17635. if (state.head) {
  17636. state.head.text = ((hold >> 8) & 1);
  17637. }
  17638. if (state.flags & 0x0200) {
  17639. //=== CRC2(state.check, hold);
  17640. hbuf[0] = hold & 0xff;
  17641. hbuf[1] = (hold >>> 8) & 0xff;
  17642. state.check = crc32(state.check, hbuf, 2, 0);
  17643. //===//
  17644. }
  17645. //=== INITBITS();
  17646. hold = 0;
  17647. bits = 0;
  17648. //===//
  17649. state.mode = TIME;
  17650. /* falls through */
  17651. case TIME:
  17652. //=== NEEDBITS(32); */
  17653. while (bits < 32) {
  17654. if (have === 0) { break inf_leave; }
  17655. have--;
  17656. hold += input[next++] << bits;
  17657. bits += 8;
  17658. }
  17659. //===//
  17660. if (state.head) {
  17661. state.head.time = hold;
  17662. }
  17663. if (state.flags & 0x0200) {
  17664. //=== CRC4(state.check, hold)
  17665. hbuf[0] = hold & 0xff;
  17666. hbuf[1] = (hold >>> 8) & 0xff;
  17667. hbuf[2] = (hold >>> 16) & 0xff;
  17668. hbuf[3] = (hold >>> 24) & 0xff;
  17669. state.check = crc32(state.check, hbuf, 4, 0);
  17670. //===
  17671. }
  17672. //=== INITBITS();
  17673. hold = 0;
  17674. bits = 0;
  17675. //===//
  17676. state.mode = OS;
  17677. /* falls through */
  17678. case OS:
  17679. //=== NEEDBITS(16); */
  17680. while (bits < 16) {
  17681. if (have === 0) { break inf_leave; }
  17682. have--;
  17683. hold += input[next++] << bits;
  17684. bits += 8;
  17685. }
  17686. //===//
  17687. if (state.head) {
  17688. state.head.xflags = (hold & 0xff);
  17689. state.head.os = (hold >> 8);
  17690. }
  17691. if (state.flags & 0x0200) {
  17692. //=== CRC2(state.check, hold);
  17693. hbuf[0] = hold & 0xff;
  17694. hbuf[1] = (hold >>> 8) & 0xff;
  17695. state.check = crc32(state.check, hbuf, 2, 0);
  17696. //===//
  17697. }
  17698. //=== INITBITS();
  17699. hold = 0;
  17700. bits = 0;
  17701. //===//
  17702. state.mode = EXLEN;
  17703. /* falls through */
  17704. case EXLEN:
  17705. if (state.flags & 0x0400) {
  17706. //=== NEEDBITS(16); */
  17707. while (bits < 16) {
  17708. if (have === 0) { break inf_leave; }
  17709. have--;
  17710. hold += input[next++] << bits;
  17711. bits += 8;
  17712. }
  17713. //===//
  17714. state.length = hold;
  17715. if (state.head) {
  17716. state.head.extra_len = hold;
  17717. }
  17718. if (state.flags & 0x0200) {
  17719. //=== CRC2(state.check, hold);
  17720. hbuf[0] = hold & 0xff;
  17721. hbuf[1] = (hold >>> 8) & 0xff;
  17722. state.check = crc32(state.check, hbuf, 2, 0);
  17723. //===//
  17724. }
  17725. //=== INITBITS();
  17726. hold = 0;
  17727. bits = 0;
  17728. //===//
  17729. }
  17730. else if (state.head) {
  17731. state.head.extra = null/*Z_NULL*/;
  17732. }
  17733. state.mode = EXTRA;
  17734. /* falls through */
  17735. case EXTRA:
  17736. if (state.flags & 0x0400) {
  17737. copy = state.length;
  17738. if (copy > have) { copy = have; }
  17739. if (copy) {
  17740. if (state.head) {
  17741. len = state.head.extra_len - state.length;
  17742. if (!state.head.extra) {
  17743. // Use untyped array for more conveniend processing later
  17744. state.head.extra = new Array(state.head.extra_len);
  17745. }
  17746. utils.arraySet(
  17747. state.head.extra,
  17748. input,
  17749. next,
  17750. // extra field is limited to 65536 bytes
  17751. // - no need for additional size check
  17752. copy,
  17753. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  17754. len
  17755. );
  17756. //zmemcpy(state.head.extra + len, next,
  17757. // len + copy > state.head.extra_max ?
  17758. // state.head.extra_max - len : copy);
  17759. }
  17760. if (state.flags & 0x0200) {
  17761. state.check = crc32(state.check, input, copy, next);
  17762. }
  17763. have -= copy;
  17764. next += copy;
  17765. state.length -= copy;
  17766. }
  17767. if (state.length) { break inf_leave; }
  17768. }
  17769. state.length = 0;
  17770. state.mode = NAME;
  17771. /* falls through */
  17772. case NAME:
  17773. if (state.flags & 0x0800) {
  17774. if (have === 0) { break inf_leave; }
  17775. copy = 0;
  17776. do {
  17777. // TODO: 2 or 1 bytes?
  17778. len = input[next + copy++];
  17779. /* use constant limit because in js we should not preallocate memory */
  17780. if (state.head && len &&
  17781. (state.length < 65536 /*state.head.name_max*/)) {
  17782. state.head.name += String.fromCharCode(len);
  17783. }
  17784. } while (len && copy < have);
  17785. if (state.flags & 0x0200) {
  17786. state.check = crc32(state.check, input, copy, next);
  17787. }
  17788. have -= copy;
  17789. next += copy;
  17790. if (len) { break inf_leave; }
  17791. }
  17792. else if (state.head) {
  17793. state.head.name = null;
  17794. }
  17795. state.length = 0;
  17796. state.mode = COMMENT;
  17797. /* falls through */
  17798. case COMMENT:
  17799. if (state.flags & 0x1000) {
  17800. if (have === 0) { break inf_leave; }
  17801. copy = 0;
  17802. do {
  17803. len = input[next + copy++];
  17804. /* use constant limit because in js we should not preallocate memory */
  17805. if (state.head && len &&
  17806. (state.length < 65536 /*state.head.comm_max*/)) {
  17807. state.head.comment += String.fromCharCode(len);
  17808. }
  17809. } while (len && copy < have);
  17810. if (state.flags & 0x0200) {
  17811. state.check = crc32(state.check, input, copy, next);
  17812. }
  17813. have -= copy;
  17814. next += copy;
  17815. if (len) { break inf_leave; }
  17816. }
  17817. else if (state.head) {
  17818. state.head.comment = null;
  17819. }
  17820. state.mode = HCRC;
  17821. /* falls through */
  17822. case HCRC:
  17823. if (state.flags & 0x0200) {
  17824. //=== NEEDBITS(16); */
  17825. while (bits < 16) {
  17826. if (have === 0) { break inf_leave; }
  17827. have--;
  17828. hold += input[next++] << bits;
  17829. bits += 8;
  17830. }
  17831. //===//
  17832. if (hold !== (state.check & 0xffff)) {
  17833. strm.msg = 'header crc mismatch';
  17834. state.mode = BAD;
  17835. break;
  17836. }
  17837. //=== INITBITS();
  17838. hold = 0;
  17839. bits = 0;
  17840. //===//
  17841. }
  17842. if (state.head) {
  17843. state.head.hcrc = ((state.flags >> 9) & 1);
  17844. state.head.done = true;
  17845. }
  17846. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  17847. state.mode = TYPE;
  17848. break;
  17849. case DICTID:
  17850. //=== NEEDBITS(32); */
  17851. while (bits < 32) {
  17852. if (have === 0) { break inf_leave; }
  17853. have--;
  17854. hold += input[next++] << bits;
  17855. bits += 8;
  17856. }
  17857. //===//
  17858. strm.adler = state.check = ZSWAP32(hold);
  17859. //=== INITBITS();
  17860. hold = 0;
  17861. bits = 0;
  17862. //===//
  17863. state.mode = DICT;
  17864. /* falls through */
  17865. case DICT:
  17866. if (state.havedict === 0) {
  17867. //--- RESTORE() ---
  17868. strm.next_out = put;
  17869. strm.avail_out = left;
  17870. strm.next_in = next;
  17871. strm.avail_in = have;
  17872. state.hold = hold;
  17873. state.bits = bits;
  17874. //---
  17875. return Z_NEED_DICT;
  17876. }
  17877. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17878. state.mode = TYPE;
  17879. /* falls through */
  17880. case TYPE:
  17881. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  17882. /* falls through */
  17883. case TYPEDO:
  17884. if (state.last) {
  17885. //--- BYTEBITS() ---//
  17886. hold >>>= bits & 7;
  17887. bits -= bits & 7;
  17888. //---//
  17889. state.mode = CHECK;
  17890. break;
  17891. }
  17892. //=== NEEDBITS(3); */
  17893. while (bits < 3) {
  17894. if (have === 0) { break inf_leave; }
  17895. have--;
  17896. hold += input[next++] << bits;
  17897. bits += 8;
  17898. }
  17899. //===//
  17900. state.last = (hold & 0x01)/*BITS(1)*/;
  17901. //--- DROPBITS(1) ---//
  17902. hold >>>= 1;
  17903. bits -= 1;
  17904. //---//
  17905. switch ((hold & 0x03)/*BITS(2)*/) {
  17906. case 0: /* stored block */
  17907. //Tracev((stderr, "inflate: stored block%s\n",
  17908. // state.last ? " (last)" : ""));
  17909. state.mode = STORED;
  17910. break;
  17911. case 1: /* fixed block */
  17912. fixedtables(state);
  17913. //Tracev((stderr, "inflate: fixed codes block%s\n",
  17914. // state.last ? " (last)" : ""));
  17915. state.mode = LEN_; /* decode codes */
  17916. if (flush === Z_TREES) {
  17917. //--- DROPBITS(2) ---//
  17918. hold >>>= 2;
  17919. bits -= 2;
  17920. //---//
  17921. break inf_leave;
  17922. }
  17923. break;
  17924. case 2: /* dynamic block */
  17925. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  17926. // state.last ? " (last)" : ""));
  17927. state.mode = TABLE;
  17928. break;
  17929. case 3:
  17930. strm.msg = 'invalid block type';
  17931. state.mode = BAD;
  17932. }
  17933. //--- DROPBITS(2) ---//
  17934. hold >>>= 2;
  17935. bits -= 2;
  17936. //---//
  17937. break;
  17938. case STORED:
  17939. //--- BYTEBITS() ---// /* go to byte boundary */
  17940. hold >>>= bits & 7;
  17941. bits -= bits & 7;
  17942. //---//
  17943. //=== NEEDBITS(32); */
  17944. while (bits < 32) {
  17945. if (have === 0) { break inf_leave; }
  17946. have--;
  17947. hold += input[next++] << bits;
  17948. bits += 8;
  17949. }
  17950. //===//
  17951. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  17952. strm.msg = 'invalid stored block lengths';
  17953. state.mode = BAD;
  17954. break;
  17955. }
  17956. state.length = hold & 0xffff;
  17957. //Tracev((stderr, "inflate: stored length %u\n",
  17958. // state.length));
  17959. //=== INITBITS();
  17960. hold = 0;
  17961. bits = 0;
  17962. //===//
  17963. state.mode = COPY_;
  17964. if (flush === Z_TREES) { break inf_leave; }
  17965. /* falls through */
  17966. case COPY_:
  17967. state.mode = COPY;
  17968. /* falls through */
  17969. case COPY:
  17970. copy = state.length;
  17971. if (copy) {
  17972. if (copy > have) { copy = have; }
  17973. if (copy > left) { copy = left; }
  17974. if (copy === 0) { break inf_leave; }
  17975. //--- zmemcpy(put, next, copy); ---
  17976. utils.arraySet(output, input, next, copy, put);
  17977. //---//
  17978. have -= copy;
  17979. next += copy;
  17980. left -= copy;
  17981. put += copy;
  17982. state.length -= copy;
  17983. break;
  17984. }
  17985. //Tracev((stderr, "inflate: stored end\n"));
  17986. state.mode = TYPE;
  17987. break;
  17988. case TABLE:
  17989. //=== NEEDBITS(14); */
  17990. while (bits < 14) {
  17991. if (have === 0) { break inf_leave; }
  17992. have--;
  17993. hold += input[next++] << bits;
  17994. bits += 8;
  17995. }
  17996. //===//
  17997. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  17998. //--- DROPBITS(5) ---//
  17999. hold >>>= 5;
  18000. bits -= 5;
  18001. //---//
  18002. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  18003. //--- DROPBITS(5) ---//
  18004. hold >>>= 5;
  18005. bits -= 5;
  18006. //---//
  18007. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  18008. //--- DROPBITS(4) ---//
  18009. hold >>>= 4;
  18010. bits -= 4;
  18011. //---//
  18012. //#ifndef PKZIP_BUG_WORKAROUND
  18013. if (state.nlen > 286 || state.ndist > 30) {
  18014. strm.msg = 'too many length or distance symbols';
  18015. state.mode = BAD;
  18016. break;
  18017. }
  18018. //#endif
  18019. //Tracev((stderr, "inflate: table sizes ok\n"));
  18020. state.have = 0;
  18021. state.mode = LENLENS;
  18022. /* falls through */
  18023. case LENLENS:
  18024. while (state.have < state.ncode) {
  18025. //=== NEEDBITS(3);
  18026. while (bits < 3) {
  18027. if (have === 0) { break inf_leave; }
  18028. have--;
  18029. hold += input[next++] << bits;
  18030. bits += 8;
  18031. }
  18032. //===//
  18033. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  18034. //--- DROPBITS(3) ---//
  18035. hold >>>= 3;
  18036. bits -= 3;
  18037. //---//
  18038. }
  18039. while (state.have < 19) {
  18040. state.lens[order[state.have++]] = 0;
  18041. }
  18042. // We have separate tables & no pointers. 2 commented lines below not needed.
  18043. //state.next = state.codes;
  18044. //state.lencode = state.next;
  18045. // Switch to use dynamic table
  18046. state.lencode = state.lendyn;
  18047. state.lenbits = 7;
  18048. opts = {bits: state.lenbits};
  18049. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  18050. state.lenbits = opts.bits;
  18051. if (ret) {
  18052. strm.msg = 'invalid code lengths set';
  18053. state.mode = BAD;
  18054. break;
  18055. }
  18056. //Tracev((stderr, "inflate: code lengths ok\n"));
  18057. state.have = 0;
  18058. state.mode = CODELENS;
  18059. /* falls through */
  18060. case CODELENS:
  18061. while (state.have < state.nlen + state.ndist) {
  18062. for (;;) {
  18063. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  18064. here_bits = here >>> 24;
  18065. here_op = (here >>> 16) & 0xff;
  18066. here_val = here & 0xffff;
  18067. if ((here_bits) <= bits) { break; }
  18068. //--- PULLBYTE() ---//
  18069. if (have === 0) { break inf_leave; }
  18070. have--;
  18071. hold += input[next++] << bits;
  18072. bits += 8;
  18073. //---//
  18074. }
  18075. if (here_val < 16) {
  18076. //--- DROPBITS(here.bits) ---//
  18077. hold >>>= here_bits;
  18078. bits -= here_bits;
  18079. //---//
  18080. state.lens[state.have++] = here_val;
  18081. }
  18082. else {
  18083. if (here_val === 16) {
  18084. //=== NEEDBITS(here.bits + 2);
  18085. n = here_bits + 2;
  18086. while (bits < n) {
  18087. if (have === 0) { break inf_leave; }
  18088. have--;
  18089. hold += input[next++] << bits;
  18090. bits += 8;
  18091. }
  18092. //===//
  18093. //--- DROPBITS(here.bits) ---//
  18094. hold >>>= here_bits;
  18095. bits -= here_bits;
  18096. //---//
  18097. if (state.have === 0) {
  18098. strm.msg = 'invalid bit length repeat';
  18099. state.mode = BAD;
  18100. break;
  18101. }
  18102. len = state.lens[state.have - 1];
  18103. copy = 3 + (hold & 0x03);//BITS(2);
  18104. //--- DROPBITS(2) ---//
  18105. hold >>>= 2;
  18106. bits -= 2;
  18107. //---//
  18108. }
  18109. else if (here_val === 17) {
  18110. //=== NEEDBITS(here.bits + 3);
  18111. n = here_bits + 3;
  18112. while (bits < n) {
  18113. if (have === 0) { break inf_leave; }
  18114. have--;
  18115. hold += input[next++] << bits;
  18116. bits += 8;
  18117. }
  18118. //===//
  18119. //--- DROPBITS(here.bits) ---//
  18120. hold >>>= here_bits;
  18121. bits -= here_bits;
  18122. //---//
  18123. len = 0;
  18124. copy = 3 + (hold & 0x07);//BITS(3);
  18125. //--- DROPBITS(3) ---//
  18126. hold >>>= 3;
  18127. bits -= 3;
  18128. //---//
  18129. }
  18130. else {
  18131. //=== NEEDBITS(here.bits + 7);
  18132. n = here_bits + 7;
  18133. while (bits < n) {
  18134. if (have === 0) { break inf_leave; }
  18135. have--;
  18136. hold += input[next++] << bits;
  18137. bits += 8;
  18138. }
  18139. //===//
  18140. //--- DROPBITS(here.bits) ---//
  18141. hold >>>= here_bits;
  18142. bits -= here_bits;
  18143. //---//
  18144. len = 0;
  18145. copy = 11 + (hold & 0x7f);//BITS(7);
  18146. //--- DROPBITS(7) ---//
  18147. hold >>>= 7;
  18148. bits -= 7;
  18149. //---//
  18150. }
  18151. if (state.have + copy > state.nlen + state.ndist) {
  18152. strm.msg = 'invalid bit length repeat';
  18153. state.mode = BAD;
  18154. break;
  18155. }
  18156. while (copy--) {
  18157. state.lens[state.have++] = len;
  18158. }
  18159. }
  18160. }
  18161. /* handle error breaks in while */
  18162. if (state.mode === BAD) { break; }
  18163. /* check for end-of-block code (better have one) */
  18164. if (state.lens[256] === 0) {
  18165. strm.msg = 'invalid code -- missing end-of-block';
  18166. state.mode = BAD;
  18167. break;
  18168. }
  18169. /* build code tables -- note: do not change the lenbits or distbits
  18170. values here (9 and 6) without reading the comments in inftrees.h
  18171. concerning the ENOUGH constants, which depend on those values */
  18172. state.lenbits = 9;
  18173. opts = {bits: state.lenbits};
  18174. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  18175. // We have separate tables & no pointers. 2 commented lines below not needed.
  18176. // state.next_index = opts.table_index;
  18177. state.lenbits = opts.bits;
  18178. // state.lencode = state.next;
  18179. if (ret) {
  18180. strm.msg = 'invalid literal/lengths set';
  18181. state.mode = BAD;
  18182. break;
  18183. }
  18184. state.distbits = 6;
  18185. //state.distcode.copy(state.codes);
  18186. // Switch to use dynamic table
  18187. state.distcode = state.distdyn;
  18188. opts = {bits: state.distbits};
  18189. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  18190. // We have separate tables & no pointers. 2 commented lines below not needed.
  18191. // state.next_index = opts.table_index;
  18192. state.distbits = opts.bits;
  18193. // state.distcode = state.next;
  18194. if (ret) {
  18195. strm.msg = 'invalid distances set';
  18196. state.mode = BAD;
  18197. break;
  18198. }
  18199. //Tracev((stderr, 'inflate: codes ok\n'));
  18200. state.mode = LEN_;
  18201. if (flush === Z_TREES) { break inf_leave; }
  18202. /* falls through */
  18203. case LEN_:
  18204. state.mode = LEN;
  18205. /* falls through */
  18206. case LEN:
  18207. if (have >= 6 && left >= 258) {
  18208. //--- RESTORE() ---
  18209. strm.next_out = put;
  18210. strm.avail_out = left;
  18211. strm.next_in = next;
  18212. strm.avail_in = have;
  18213. state.hold = hold;
  18214. state.bits = bits;
  18215. //---
  18216. inflate_fast(strm, _out);
  18217. //--- LOAD() ---
  18218. put = strm.next_out;
  18219. output = strm.output;
  18220. left = strm.avail_out;
  18221. next = strm.next_in;
  18222. input = strm.input;
  18223. have = strm.avail_in;
  18224. hold = state.hold;
  18225. bits = state.bits;
  18226. //---
  18227. if (state.mode === TYPE) {
  18228. state.back = -1;
  18229. }
  18230. break;
  18231. }
  18232. state.back = 0;
  18233. for (;;) {
  18234. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  18235. here_bits = here >>> 24;
  18236. here_op = (here >>> 16) & 0xff;
  18237. here_val = here & 0xffff;
  18238. if (here_bits <= bits) { break; }
  18239. //--- PULLBYTE() ---//
  18240. if (have === 0) { break inf_leave; }
  18241. have--;
  18242. hold += input[next++] << bits;
  18243. bits += 8;
  18244. //---//
  18245. }
  18246. if (here_op && (here_op & 0xf0) === 0) {
  18247. last_bits = here_bits;
  18248. last_op = here_op;
  18249. last_val = here_val;
  18250. for (;;) {
  18251. here = state.lencode[last_val +
  18252. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18253. here_bits = here >>> 24;
  18254. here_op = (here >>> 16) & 0xff;
  18255. here_val = here & 0xffff;
  18256. if ((last_bits + here_bits) <= bits) { break; }
  18257. //--- PULLBYTE() ---//
  18258. if (have === 0) { break inf_leave; }
  18259. have--;
  18260. hold += input[next++] << bits;
  18261. bits += 8;
  18262. //---//
  18263. }
  18264. //--- DROPBITS(last.bits) ---//
  18265. hold >>>= last_bits;
  18266. bits -= last_bits;
  18267. //---//
  18268. state.back += last_bits;
  18269. }
  18270. //--- DROPBITS(here.bits) ---//
  18271. hold >>>= here_bits;
  18272. bits -= here_bits;
  18273. //---//
  18274. state.back += here_bits;
  18275. state.length = here_val;
  18276. if (here_op === 0) {
  18277. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  18278. // "inflate: literal '%c'\n" :
  18279. // "inflate: literal 0x%02x\n", here.val));
  18280. state.mode = LIT;
  18281. break;
  18282. }
  18283. if (here_op & 32) {
  18284. //Tracevv((stderr, "inflate: end of block\n"));
  18285. state.back = -1;
  18286. state.mode = TYPE;
  18287. break;
  18288. }
  18289. if (here_op & 64) {
  18290. strm.msg = 'invalid literal/length code';
  18291. state.mode = BAD;
  18292. break;
  18293. }
  18294. state.extra = here_op & 15;
  18295. state.mode = LENEXT;
  18296. /* falls through */
  18297. case LENEXT:
  18298. if (state.extra) {
  18299. //=== NEEDBITS(state.extra);
  18300. n = state.extra;
  18301. while (bits < n) {
  18302. if (have === 0) { break inf_leave; }
  18303. have--;
  18304. hold += input[next++] << bits;
  18305. bits += 8;
  18306. }
  18307. //===//
  18308. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18309. //--- DROPBITS(state.extra) ---//
  18310. hold >>>= state.extra;
  18311. bits -= state.extra;
  18312. //---//
  18313. state.back += state.extra;
  18314. }
  18315. //Tracevv((stderr, "inflate: length %u\n", state.length));
  18316. state.was = state.length;
  18317. state.mode = DIST;
  18318. /* falls through */
  18319. case DIST:
  18320. for (;;) {
  18321. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  18322. here_bits = here >>> 24;
  18323. here_op = (here >>> 16) & 0xff;
  18324. here_val = here & 0xffff;
  18325. if ((here_bits) <= bits) { break; }
  18326. //--- PULLBYTE() ---//
  18327. if (have === 0) { break inf_leave; }
  18328. have--;
  18329. hold += input[next++] << bits;
  18330. bits += 8;
  18331. //---//
  18332. }
  18333. if ((here_op & 0xf0) === 0) {
  18334. last_bits = here_bits;
  18335. last_op = here_op;
  18336. last_val = here_val;
  18337. for (;;) {
  18338. here = state.distcode[last_val +
  18339. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18340. here_bits = here >>> 24;
  18341. here_op = (here >>> 16) & 0xff;
  18342. here_val = here & 0xffff;
  18343. if ((last_bits + here_bits) <= bits) { break; }
  18344. //--- PULLBYTE() ---//
  18345. if (have === 0) { break inf_leave; }
  18346. have--;
  18347. hold += input[next++] << bits;
  18348. bits += 8;
  18349. //---//
  18350. }
  18351. //--- DROPBITS(last.bits) ---//
  18352. hold >>>= last_bits;
  18353. bits -= last_bits;
  18354. //---//
  18355. state.back += last_bits;
  18356. }
  18357. //--- DROPBITS(here.bits) ---//
  18358. hold >>>= here_bits;
  18359. bits -= here_bits;
  18360. //---//
  18361. state.back += here_bits;
  18362. if (here_op & 64) {
  18363. strm.msg = 'invalid distance code';
  18364. state.mode = BAD;
  18365. break;
  18366. }
  18367. state.offset = here_val;
  18368. state.extra = (here_op) & 15;
  18369. state.mode = DISTEXT;
  18370. /* falls through */
  18371. case DISTEXT:
  18372. if (state.extra) {
  18373. //=== NEEDBITS(state.extra);
  18374. n = state.extra;
  18375. while (bits < n) {
  18376. if (have === 0) { break inf_leave; }
  18377. have--;
  18378. hold += input[next++] << bits;
  18379. bits += 8;
  18380. }
  18381. //===//
  18382. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18383. //--- DROPBITS(state.extra) ---//
  18384. hold >>>= state.extra;
  18385. bits -= state.extra;
  18386. //---//
  18387. state.back += state.extra;
  18388. }
  18389. //#ifdef INFLATE_STRICT
  18390. if (state.offset > state.dmax) {
  18391. strm.msg = 'invalid distance too far back';
  18392. state.mode = BAD;
  18393. break;
  18394. }
  18395. //#endif
  18396. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  18397. state.mode = MATCH;
  18398. /* falls through */
  18399. case MATCH:
  18400. if (left === 0) { break inf_leave; }
  18401. copy = _out - left;
  18402. if (state.offset > copy) { /* copy from window */
  18403. copy = state.offset - copy;
  18404. if (copy > state.whave) {
  18405. if (state.sane) {
  18406. strm.msg = 'invalid distance too far back';
  18407. state.mode = BAD;
  18408. break;
  18409. }
  18410. // (!) This block is disabled in zlib defailts,
  18411. // don't enable it for binary compatibility
  18412. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  18413. // Trace((stderr, "inflate.c too far\n"));
  18414. // copy -= state.whave;
  18415. // if (copy > state.length) { copy = state.length; }
  18416. // if (copy > left) { copy = left; }
  18417. // left -= copy;
  18418. // state.length -= copy;
  18419. // do {
  18420. // output[put++] = 0;
  18421. // } while (--copy);
  18422. // if (state.length === 0) { state.mode = LEN; }
  18423. // break;
  18424. //#endif
  18425. }
  18426. if (copy > state.wnext) {
  18427. copy -= state.wnext;
  18428. from = state.wsize - copy;
  18429. }
  18430. else {
  18431. from = state.wnext - copy;
  18432. }
  18433. if (copy > state.length) { copy = state.length; }
  18434. from_source = state.window;
  18435. }
  18436. else { /* copy from output */
  18437. from_source = output;
  18438. from = put - state.offset;
  18439. copy = state.length;
  18440. }
  18441. if (copy > left) { copy = left; }
  18442. left -= copy;
  18443. state.length -= copy;
  18444. do {
  18445. output[put++] = from_source[from++];
  18446. } while (--copy);
  18447. if (state.length === 0) { state.mode = LEN; }
  18448. break;
  18449. case LIT:
  18450. if (left === 0) { break inf_leave; }
  18451. output[put++] = state.length;
  18452. left--;
  18453. state.mode = LEN;
  18454. break;
  18455. case CHECK:
  18456. if (state.wrap) {
  18457. //=== NEEDBITS(32);
  18458. while (bits < 32) {
  18459. if (have === 0) { break inf_leave; }
  18460. have--;
  18461. // Use '|' insdead of '+' to make sure that result is signed
  18462. hold |= input[next++] << bits;
  18463. bits += 8;
  18464. }
  18465. //===//
  18466. _out -= left;
  18467. strm.total_out += _out;
  18468. state.total += _out;
  18469. if (_out) {
  18470. strm.adler = state.check =
  18471. /*UPDATE(state.check, put - _out, _out);*/
  18472. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  18473. }
  18474. _out = left;
  18475. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  18476. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  18477. strm.msg = 'incorrect data check';
  18478. state.mode = BAD;
  18479. break;
  18480. }
  18481. //=== INITBITS();
  18482. hold = 0;
  18483. bits = 0;
  18484. //===//
  18485. //Tracev((stderr, "inflate: check matches trailer\n"));
  18486. }
  18487. state.mode = LENGTH;
  18488. /* falls through */
  18489. case LENGTH:
  18490. if (state.wrap && state.flags) {
  18491. //=== NEEDBITS(32);
  18492. while (bits < 32) {
  18493. if (have === 0) { break inf_leave; }
  18494. have--;
  18495. hold += input[next++] << bits;
  18496. bits += 8;
  18497. }
  18498. //===//
  18499. if (hold !== (state.total & 0xffffffff)) {
  18500. strm.msg = 'incorrect length check';
  18501. state.mode = BAD;
  18502. break;
  18503. }
  18504. //=== INITBITS();
  18505. hold = 0;
  18506. bits = 0;
  18507. //===//
  18508. //Tracev((stderr, "inflate: length matches trailer\n"));
  18509. }
  18510. state.mode = DONE;
  18511. /* falls through */
  18512. case DONE:
  18513. ret = Z_STREAM_END;
  18514. break inf_leave;
  18515. case BAD:
  18516. ret = Z_DATA_ERROR;
  18517. break inf_leave;
  18518. case MEM:
  18519. return Z_MEM_ERROR;
  18520. case SYNC:
  18521. /* falls through */
  18522. default:
  18523. return Z_STREAM_ERROR;
  18524. }
  18525. }
  18526. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  18527. /*
  18528. Return from inflate(), updating the total counts and the check value.
  18529. If there was no progress during the inflate() call, return a buffer
  18530. error. Call updatewindow() to create and/or update the window state.
  18531. Note: a memory error from inflate() is non-recoverable.
  18532. */
  18533. //--- RESTORE() ---
  18534. strm.next_out = put;
  18535. strm.avail_out = left;
  18536. strm.next_in = next;
  18537. strm.avail_in = have;
  18538. state.hold = hold;
  18539. state.bits = bits;
  18540. //---
  18541. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  18542. (state.mode < CHECK || flush !== Z_FINISH))) {
  18543. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  18544. state.mode = MEM;
  18545. return Z_MEM_ERROR;
  18546. }
  18547. }
  18548. _in -= strm.avail_in;
  18549. _out -= strm.avail_out;
  18550. strm.total_in += _in;
  18551. strm.total_out += _out;
  18552. state.total += _out;
  18553. if (state.wrap && _out) {
  18554. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  18555. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  18556. }
  18557. strm.data_type = state.bits + (state.last ? 64 : 0) +
  18558. (state.mode === TYPE ? 128 : 0) +
  18559. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  18560. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  18561. ret = Z_BUF_ERROR;
  18562. }
  18563. return ret;
  18564. }
  18565. function inflateEnd(strm) {
  18566. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  18567. return Z_STREAM_ERROR;
  18568. }
  18569. var state = strm.state;
  18570. if (state.window) {
  18571. state.window = null;
  18572. }
  18573. strm.state = null;
  18574. return Z_OK;
  18575. }
  18576. function inflateGetHeader(strm, head) {
  18577. var state;
  18578. /* check state */
  18579. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18580. state = strm.state;
  18581. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  18582. /* save header structure */
  18583. state.head = head;
  18584. head.done = false;
  18585. return Z_OK;
  18586. }
  18587. exports.inflateReset = inflateReset;
  18588. exports.inflateReset2 = inflateReset2;
  18589. exports.inflateResetKeep = inflateResetKeep;
  18590. exports.inflateInit = inflateInit;
  18591. exports.inflateInit2 = inflateInit2;
  18592. exports.inflate = inflate;
  18593. exports.inflateEnd = inflateEnd;
  18594. exports.inflateGetHeader = inflateGetHeader;
  18595. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  18596. /* Not implemented
  18597. exports.inflateCopy = inflateCopy;
  18598. exports.inflateGetDictionary = inflateGetDictionary;
  18599. exports.inflateMark = inflateMark;
  18600. exports.inflatePrime = inflatePrime;
  18601. exports.inflateSetDictionary = inflateSetDictionary;
  18602. exports.inflateSync = inflateSync;
  18603. exports.inflateSyncPoint = inflateSyncPoint;
  18604. exports.inflateUndermine = inflateUndermine;
  18605. */
  18606. },{"../utils/common":54,"./adler32":56,"./crc32":58,"./inffast":61,"./inftrees":63}],63:[function(require,module,exports){
  18607. 'use strict';
  18608. var utils = require('../utils/common');
  18609. var MAXBITS = 15;
  18610. var ENOUGH_LENS = 852;
  18611. var ENOUGH_DISTS = 592;
  18612. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  18613. var CODES = 0;
  18614. var LENS = 1;
  18615. var DISTS = 2;
  18616. var lbase = [ /* Length codes 257..285 base */
  18617. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  18618. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  18619. ];
  18620. var lext = [ /* Length codes 257..285 extra */
  18621. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  18622. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  18623. ];
  18624. var dbase = [ /* Distance codes 0..29 base */
  18625. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  18626. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  18627. 8193, 12289, 16385, 24577, 0, 0
  18628. ];
  18629. var dext = [ /* Distance codes 0..29 extra */
  18630. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  18631. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  18632. 28, 28, 29, 29, 64, 64
  18633. ];
  18634. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  18635. {
  18636. var bits = opts.bits;
  18637. //here = opts.here; /* table entry for duplication */
  18638. var len = 0; /* a code's length in bits */
  18639. var sym = 0; /* index of code symbols */
  18640. var min = 0, max = 0; /* minimum and maximum code lengths */
  18641. var root = 0; /* number of index bits for root table */
  18642. var curr = 0; /* number of index bits for current table */
  18643. var drop = 0; /* code bits to drop for sub-table */
  18644. var left = 0; /* number of prefix codes available */
  18645. var used = 0; /* code entries in table used */
  18646. var huff = 0; /* Huffman code */
  18647. var incr; /* for incrementing code, index */
  18648. var fill; /* index for replicating entries */
  18649. var low; /* low bits for current root entry */
  18650. var mask; /* mask for low root bits */
  18651. var next; /* next available space in table */
  18652. var base = null; /* base value table to use */
  18653. var base_index = 0;
  18654. // var shoextra; /* extra bits table to use */
  18655. var end; /* use base and extra for symbol > end */
  18656. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  18657. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  18658. var extra = null;
  18659. var extra_index = 0;
  18660. var here_bits, here_op, here_val;
  18661. /*
  18662. Process a set of code lengths to create a canonical Huffman code. The
  18663. code lengths are lens[0..codes-1]. Each length corresponds to the
  18664. symbols 0..codes-1. The Huffman code is generated by first sorting the
  18665. symbols by length from short to long, and retaining the symbol order
  18666. for codes with equal lengths. Then the code starts with all zero bits
  18667. for the first code of the shortest length, and the codes are integer
  18668. increments for the same length, and zeros are appended as the length
  18669. increases. For the deflate format, these bits are stored backwards
  18670. from their more natural integer increment ordering, and so when the
  18671. decoding tables are built in the large loop below, the integer codes
  18672. are incremented backwards.
  18673. This routine assumes, but does not check, that all of the entries in
  18674. lens[] are in the range 0..MAXBITS. The caller must assure this.
  18675. 1..MAXBITS is interpreted as that code length. zero means that that
  18676. symbol does not occur in this code.
  18677. The codes are sorted by computing a count of codes for each length,
  18678. creating from that a table of starting indices for each length in the
  18679. sorted table, and then entering the symbols in order in the sorted
  18680. table. The sorted table is work[], with that space being provided by
  18681. the caller.
  18682. The length counts are used for other purposes as well, i.e. finding
  18683. the minimum and maximum length codes, determining if there are any
  18684. codes at all, checking for a valid set of lengths, and looking ahead
  18685. at length counts to determine sub-table sizes when building the
  18686. decoding tables.
  18687. */
  18688. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  18689. for (len = 0; len <= MAXBITS; len++) {
  18690. count[len] = 0;
  18691. }
  18692. for (sym = 0; sym < codes; sym++) {
  18693. count[lens[lens_index + sym]]++;
  18694. }
  18695. /* bound code lengths, force root to be within code lengths */
  18696. root = bits;
  18697. for (max = MAXBITS; max >= 1; max--) {
  18698. if (count[max] !== 0) { break; }
  18699. }
  18700. if (root > max) {
  18701. root = max;
  18702. }
  18703. if (max === 0) { /* no symbols to code at all */
  18704. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  18705. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  18706. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  18707. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18708. //table.op[opts.table_index] = 64;
  18709. //table.bits[opts.table_index] = 1;
  18710. //table.val[opts.table_index++] = 0;
  18711. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18712. opts.bits = 1;
  18713. return 0; /* no symbols, but wait for decoding to report error */
  18714. }
  18715. for (min = 1; min < max; min++) {
  18716. if (count[min] !== 0) { break; }
  18717. }
  18718. if (root < min) {
  18719. root = min;
  18720. }
  18721. /* check for an over-subscribed or incomplete set of lengths */
  18722. left = 1;
  18723. for (len = 1; len <= MAXBITS; len++) {
  18724. left <<= 1;
  18725. left -= count[len];
  18726. if (left < 0) {
  18727. return -1;
  18728. } /* over-subscribed */
  18729. }
  18730. if (left > 0 && (type === CODES || max !== 1)) {
  18731. return -1; /* incomplete set */
  18732. }
  18733. /* generate offsets into symbol table for each length for sorting */
  18734. offs[1] = 0;
  18735. for (len = 1; len < MAXBITS; len++) {
  18736. offs[len + 1] = offs[len] + count[len];
  18737. }
  18738. /* sort symbols by length, by symbol order within each length */
  18739. for (sym = 0; sym < codes; sym++) {
  18740. if (lens[lens_index + sym] !== 0) {
  18741. work[offs[lens[lens_index + sym]]++] = sym;
  18742. }
  18743. }
  18744. /*
  18745. Create and fill in decoding tables. In this loop, the table being
  18746. filled is at next and has curr index bits. The code being used is huff
  18747. with length len. That code is converted to an index by dropping drop
  18748. bits off of the bottom. For codes where len is less than drop + curr,
  18749. those top drop + curr - len bits are incremented through all values to
  18750. fill the table with replicated entries.
  18751. root is the number of index bits for the root table. When len exceeds
  18752. root, sub-tables are created pointed to by the root entry with an index
  18753. of the low root bits of huff. This is saved in low to check for when a
  18754. new sub-table should be started. drop is zero when the root table is
  18755. being filled, and drop is root when sub-tables are being filled.
  18756. When a new sub-table is needed, it is necessary to look ahead in the
  18757. code lengths to determine what size sub-table is needed. The length
  18758. counts are used for this, and so count[] is decremented as codes are
  18759. entered in the tables.
  18760. used keeps track of how many table entries have been allocated from the
  18761. provided *table space. It is checked for LENS and DIST tables against
  18762. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  18763. the initial root table size constants. See the comments in inftrees.h
  18764. for more information.
  18765. sym increments through all symbols, and the loop terminates when
  18766. all codes of length max, i.e. all codes, have been processed. This
  18767. routine permits incomplete codes, so another loop after this one fills
  18768. in the rest of the decoding tables with invalid code markers.
  18769. */
  18770. /* set up for code type */
  18771. // poor man optimization - use if-else instead of switch,
  18772. // to avoid deopts in old v8
  18773. if (type === CODES) {
  18774. base = extra = work; /* dummy value--not used */
  18775. end = 19;
  18776. } else if (type === LENS) {
  18777. base = lbase;
  18778. base_index -= 257;
  18779. extra = lext;
  18780. extra_index -= 257;
  18781. end = 256;
  18782. } else { /* DISTS */
  18783. base = dbase;
  18784. extra = dext;
  18785. end = -1;
  18786. }
  18787. /* initialize opts for loop */
  18788. huff = 0; /* starting code */
  18789. sym = 0; /* starting code symbol */
  18790. len = min; /* starting code length */
  18791. next = table_index; /* current table to fill in */
  18792. curr = root; /* current table index bits */
  18793. drop = 0; /* current bits to drop from code for index */
  18794. low = -1; /* trigger new sub-table when len > root */
  18795. used = 1 << root; /* use root table entries */
  18796. mask = used - 1; /* mask for comparing low */
  18797. /* check available table space */
  18798. if ((type === LENS && used > ENOUGH_LENS) ||
  18799. (type === DISTS && used > ENOUGH_DISTS)) {
  18800. return 1;
  18801. }
  18802. var i=0;
  18803. /* process all codes and make table entries */
  18804. for (;;) {
  18805. i++;
  18806. /* create table entry */
  18807. here_bits = len - drop;
  18808. if (work[sym] < end) {
  18809. here_op = 0;
  18810. here_val = work[sym];
  18811. }
  18812. else if (work[sym] > end) {
  18813. here_op = extra[extra_index + work[sym]];
  18814. here_val = base[base_index + work[sym]];
  18815. }
  18816. else {
  18817. here_op = 32 + 64; /* end of block */
  18818. here_val = 0;
  18819. }
  18820. /* replicate for those indices with low len bits equal to huff */
  18821. incr = 1 << (len - drop);
  18822. fill = 1 << curr;
  18823. min = fill; /* save offset to next table */
  18824. do {
  18825. fill -= incr;
  18826. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  18827. } while (fill !== 0);
  18828. /* backwards increment the len-bit code huff */
  18829. incr = 1 << (len - 1);
  18830. while (huff & incr) {
  18831. incr >>= 1;
  18832. }
  18833. if (incr !== 0) {
  18834. huff &= incr - 1;
  18835. huff += incr;
  18836. } else {
  18837. huff = 0;
  18838. }
  18839. /* go to next symbol, update count, len */
  18840. sym++;
  18841. if (--count[len] === 0) {
  18842. if (len === max) { break; }
  18843. len = lens[lens_index + work[sym]];
  18844. }
  18845. /* create new sub-table if needed */
  18846. if (len > root && (huff & mask) !== low) {
  18847. /* if first time, transition to sub-tables */
  18848. if (drop === 0) {
  18849. drop = root;
  18850. }
  18851. /* increment past last table */
  18852. next += min; /* here min is 1 << curr */
  18853. /* determine length of next table */
  18854. curr = len - drop;
  18855. left = 1 << curr;
  18856. while (curr + drop < max) {
  18857. left -= count[curr + drop];
  18858. if (left <= 0) { break; }
  18859. curr++;
  18860. left <<= 1;
  18861. }
  18862. /* check for enough space */
  18863. used += 1 << curr;
  18864. if ((type === LENS && used > ENOUGH_LENS) ||
  18865. (type === DISTS && used > ENOUGH_DISTS)) {
  18866. return 1;
  18867. }
  18868. /* point entry in root table to sub-table */
  18869. low = huff & mask;
  18870. /*table.op[low] = curr;
  18871. table.bits[low] = root;
  18872. table.val[low] = next - opts.table_index;*/
  18873. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  18874. }
  18875. }
  18876. /* fill in remaining table entry if code is incomplete (guaranteed to have
  18877. at most one remaining entry, since if the code is incomplete, the
  18878. maximum code length that was allowed to get this far is one bit) */
  18879. if (huff !== 0) {
  18880. //table.op[next + huff] = 64; /* invalid code marker */
  18881. //table.bits[next + huff] = len - drop;
  18882. //table.val[next + huff] = 0;
  18883. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  18884. }
  18885. /* set return parameters */
  18886. //opts.table_index += used;
  18887. opts.bits = root;
  18888. return 0;
  18889. };
  18890. },{"../utils/common":54}],64:[function(require,module,exports){
  18891. 'use strict';
  18892. module.exports = {
  18893. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  18894. '1': 'stream end', /* Z_STREAM_END 1 */
  18895. '0': '', /* Z_OK 0 */
  18896. '-1': 'file error', /* Z_ERRNO (-1) */
  18897. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  18898. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  18899. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  18900. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  18901. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  18902. };
  18903. },{}],65:[function(require,module,exports){
  18904. 'use strict';
  18905. var utils = require('../utils/common');
  18906. /* Public constants ==========================================================*/
  18907. /* ===========================================================================*/
  18908. //var Z_FILTERED = 1;
  18909. //var Z_HUFFMAN_ONLY = 2;
  18910. //var Z_RLE = 3;
  18911. var Z_FIXED = 4;
  18912. //var Z_DEFAULT_STRATEGY = 0;
  18913. /* Possible values of the data_type field (though see inflate()) */
  18914. var Z_BINARY = 0;
  18915. var Z_TEXT = 1;
  18916. //var Z_ASCII = 1; // = Z_TEXT
  18917. var Z_UNKNOWN = 2;
  18918. /*============================================================================*/
  18919. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18920. // From zutil.h
  18921. var STORED_BLOCK = 0;
  18922. var STATIC_TREES = 1;
  18923. var DYN_TREES = 2;
  18924. /* The three kinds of block type */
  18925. var MIN_MATCH = 3;
  18926. var MAX_MATCH = 258;
  18927. /* The minimum and maximum match lengths */
  18928. // From deflate.h
  18929. /* ===========================================================================
  18930. * Internal compression state.
  18931. */
  18932. var LENGTH_CODES = 29;
  18933. /* number of length codes, not counting the special END_BLOCK code */
  18934. var LITERALS = 256;
  18935. /* number of literal bytes 0..255 */
  18936. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18937. /* number of Literal or Length codes, including the END_BLOCK code */
  18938. var D_CODES = 30;
  18939. /* number of distance codes */
  18940. var BL_CODES = 19;
  18941. /* number of codes used to transfer the bit lengths */
  18942. var HEAP_SIZE = 2*L_CODES + 1;
  18943. /* maximum heap size */
  18944. var MAX_BITS = 15;
  18945. /* All codes must not exceed MAX_BITS bits */
  18946. var Buf_size = 16;
  18947. /* size of bit buffer in bi_buf */
  18948. /* ===========================================================================
  18949. * Constants
  18950. */
  18951. var MAX_BL_BITS = 7;
  18952. /* Bit length codes must not exceed MAX_BL_BITS bits */
  18953. var END_BLOCK = 256;
  18954. /* end of block literal code */
  18955. var REP_3_6 = 16;
  18956. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  18957. var REPZ_3_10 = 17;
  18958. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  18959. var REPZ_11_138 = 18;
  18960. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  18961. var extra_lbits = /* extra bits for each length code */
  18962. [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  18963. var extra_dbits = /* extra bits for each distance code */
  18964. [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  18965. var extra_blbits = /* extra bits for each bit length code */
  18966. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  18967. var bl_order =
  18968. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  18969. /* The lengths of the bit length codes are sent in order of decreasing
  18970. * probability, to avoid transmitting the lengths for unused bit length codes.
  18971. */
  18972. /* ===========================================================================
  18973. * Local data. These are initialized only once.
  18974. */
  18975. // We pre-fill arrays with 0 to avoid uninitialized gaps
  18976. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  18977. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  18978. var static_ltree = new Array((L_CODES+2) * 2);
  18979. zero(static_ltree);
  18980. /* The static literal tree. Since the bit lengths are imposed, there is no
  18981. * need for the L_CODES extra codes used during heap construction. However
  18982. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  18983. * below).
  18984. */
  18985. var static_dtree = new Array(D_CODES * 2);
  18986. zero(static_dtree);
  18987. /* The static distance tree. (Actually a trivial tree since all codes use
  18988. * 5 bits.)
  18989. */
  18990. var _dist_code = new Array(DIST_CODE_LEN);
  18991. zero(_dist_code);
  18992. /* Distance codes. The first 256 values correspond to the distances
  18993. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  18994. * the 15 bit distances.
  18995. */
  18996. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  18997. zero(_length_code);
  18998. /* length code for each normalized match length (0 == MIN_MATCH) */
  18999. var base_length = new Array(LENGTH_CODES);
  19000. zero(base_length);
  19001. /* First normalized length for each code (0 = MIN_MATCH) */
  19002. var base_dist = new Array(D_CODES);
  19003. zero(base_dist);
  19004. /* First normalized distance for each code (0 = distance of 1) */
  19005. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  19006. this.static_tree = static_tree; /* static tree or NULL */
  19007. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  19008. this.extra_base = extra_base; /* base index for extra_bits */
  19009. this.elems = elems; /* max number of elements in the tree */
  19010. this.max_length = max_length; /* max bit length for the codes */
  19011. // show if `static_tree` has data or dummy - needed for monomorphic objects
  19012. this.has_stree = static_tree && static_tree.length;
  19013. };
  19014. var static_l_desc;
  19015. var static_d_desc;
  19016. var static_bl_desc;
  19017. var TreeDesc = function(dyn_tree, stat_desc) {
  19018. this.dyn_tree = dyn_tree; /* the dynamic tree */
  19019. this.max_code = 0; /* largest code with non zero frequency */
  19020. this.stat_desc = stat_desc; /* the corresponding static tree */
  19021. };
  19022. function d_code(dist) {
  19023. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  19024. }
  19025. /* ===========================================================================
  19026. * Output a short LSB first on the stream.
  19027. * IN assertion: there is enough room in pendingBuf.
  19028. */
  19029. function put_short (s, w) {
  19030. // put_byte(s, (uch)((w) & 0xff));
  19031. // put_byte(s, (uch)((ush)(w) >> 8));
  19032. s.pending_buf[s.pending++] = (w) & 0xff;
  19033. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  19034. }
  19035. /* ===========================================================================
  19036. * Send a value on a given number of bits.
  19037. * IN assertion: length <= 16 and value fits in length bits.
  19038. */
  19039. function send_bits(s, value, length) {
  19040. if (s.bi_valid > (Buf_size - length)) {
  19041. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19042. put_short(s, s.bi_buf);
  19043. s.bi_buf = value >> (Buf_size - s.bi_valid);
  19044. s.bi_valid += length - Buf_size;
  19045. } else {
  19046. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19047. s.bi_valid += length;
  19048. }
  19049. }
  19050. function send_code(s, c, tree) {
  19051. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  19052. }
  19053. /* ===========================================================================
  19054. * Reverse the first len bits of a code, using straightforward code (a faster
  19055. * method would use a table)
  19056. * IN assertion: 1 <= len <= 15
  19057. */
  19058. function bi_reverse(code, len) {
  19059. var res = 0;
  19060. do {
  19061. res |= code & 1;
  19062. code >>>= 1;
  19063. res <<= 1;
  19064. } while (--len > 0);
  19065. return res >>> 1;
  19066. }
  19067. /* ===========================================================================
  19068. * Flush the bit buffer, keeping at most 7 bits in it.
  19069. */
  19070. function bi_flush(s) {
  19071. if (s.bi_valid === 16) {
  19072. put_short(s, s.bi_buf);
  19073. s.bi_buf = 0;
  19074. s.bi_valid = 0;
  19075. } else if (s.bi_valid >= 8) {
  19076. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  19077. s.bi_buf >>= 8;
  19078. s.bi_valid -= 8;
  19079. }
  19080. }
  19081. /* ===========================================================================
  19082. * Compute the optimal bit lengths for a tree and update the total bit length
  19083. * for the current block.
  19084. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  19085. * above are the tree nodes sorted by increasing frequency.
  19086. * OUT assertions: the field len is set to the optimal bit length, the
  19087. * array bl_count contains the frequencies for each bit length.
  19088. * The length opt_len is updated; static_len is also updated if stree is
  19089. * not null.
  19090. */
  19091. function gen_bitlen(s, desc)
  19092. // deflate_state *s;
  19093. // tree_desc *desc; /* the tree descriptor */
  19094. {
  19095. var tree = desc.dyn_tree;
  19096. var max_code = desc.max_code;
  19097. var stree = desc.stat_desc.static_tree;
  19098. var has_stree = desc.stat_desc.has_stree;
  19099. var extra = desc.stat_desc.extra_bits;
  19100. var base = desc.stat_desc.extra_base;
  19101. var max_length = desc.stat_desc.max_length;
  19102. var h; /* heap index */
  19103. var n, m; /* iterate over the tree elements */
  19104. var bits; /* bit length */
  19105. var xbits; /* extra bits */
  19106. var f; /* frequency */
  19107. var overflow = 0; /* number of elements with bit length too large */
  19108. for (bits = 0; bits <= MAX_BITS; bits++) {
  19109. s.bl_count[bits] = 0;
  19110. }
  19111. /* In a first pass, compute the optimal bit lengths (which may
  19112. * overflow in the case of the bit length tree).
  19113. */
  19114. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  19115. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  19116. n = s.heap[h];
  19117. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  19118. if (bits > max_length) {
  19119. bits = max_length;
  19120. overflow++;
  19121. }
  19122. tree[n*2 + 1]/*.Len*/ = bits;
  19123. /* We overwrite tree[n].Dad which is no longer needed */
  19124. if (n > max_code) { continue; } /* not a leaf node */
  19125. s.bl_count[bits]++;
  19126. xbits = 0;
  19127. if (n >= base) {
  19128. xbits = extra[n-base];
  19129. }
  19130. f = tree[n * 2]/*.Freq*/;
  19131. s.opt_len += f * (bits + xbits);
  19132. if (has_stree) {
  19133. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  19134. }
  19135. }
  19136. if (overflow === 0) { return; }
  19137. // Trace((stderr,"\nbit length overflow\n"));
  19138. /* This happens for example on obj2 and pic of the Calgary corpus */
  19139. /* Find the first bit length which could increase: */
  19140. do {
  19141. bits = max_length-1;
  19142. while (s.bl_count[bits] === 0) { bits--; }
  19143. s.bl_count[bits]--; /* move one leaf down the tree */
  19144. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  19145. s.bl_count[max_length]--;
  19146. /* The brother of the overflow item also moves one step up,
  19147. * but this does not affect bl_count[max_length]
  19148. */
  19149. overflow -= 2;
  19150. } while (overflow > 0);
  19151. /* Now recompute all bit lengths, scanning in increasing frequency.
  19152. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  19153. * lengths instead of fixing only the wrong ones. This idea is taken
  19154. * from 'ar' written by Haruhiko Okumura.)
  19155. */
  19156. for (bits = max_length; bits !== 0; bits--) {
  19157. n = s.bl_count[bits];
  19158. while (n !== 0) {
  19159. m = s.heap[--h];
  19160. if (m > max_code) { continue; }
  19161. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  19162. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  19163. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  19164. tree[m*2 + 1]/*.Len*/ = bits;
  19165. }
  19166. n--;
  19167. }
  19168. }
  19169. }
  19170. /* ===========================================================================
  19171. * Generate the codes for a given tree and bit counts (which need not be
  19172. * optimal).
  19173. * IN assertion: the array bl_count contains the bit length statistics for
  19174. * the given tree and the field len is set for all tree elements.
  19175. * OUT assertion: the field code is set for all tree elements of non
  19176. * zero code length.
  19177. */
  19178. function gen_codes(tree, max_code, bl_count)
  19179. // ct_data *tree; /* the tree to decorate */
  19180. // int max_code; /* largest code with non zero frequency */
  19181. // ushf *bl_count; /* number of codes at each bit length */
  19182. {
  19183. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  19184. var code = 0; /* running code value */
  19185. var bits; /* bit index */
  19186. var n; /* code index */
  19187. /* The distribution counts are first used to generate the code values
  19188. * without bit reversal.
  19189. */
  19190. for (bits = 1; bits <= MAX_BITS; bits++) {
  19191. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  19192. }
  19193. /* Check that the bit counts in bl_count are consistent. The last code
  19194. * must be all ones.
  19195. */
  19196. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  19197. // "inconsistent bit counts");
  19198. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  19199. for (n = 0; n <= max_code; n++) {
  19200. var len = tree[n*2 + 1]/*.Len*/;
  19201. if (len === 0) { continue; }
  19202. /* Now reverse the bits */
  19203. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  19204. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  19205. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  19206. }
  19207. }
  19208. /* ===========================================================================
  19209. * Initialize the various 'constant' tables.
  19210. */
  19211. function tr_static_init() {
  19212. var n; /* iterates over tree elements */
  19213. var bits; /* bit counter */
  19214. var length; /* length value */
  19215. var code; /* code value */
  19216. var dist; /* distance index */
  19217. var bl_count = new Array(MAX_BITS+1);
  19218. /* number of codes at each bit length for an optimal tree */
  19219. // do check in _tr_init()
  19220. //if (static_init_done) return;
  19221. /* For some embedded targets, global variables are not initialized: */
  19222. /*#ifdef NO_INIT_GLOBAL_POINTERS
  19223. static_l_desc.static_tree = static_ltree;
  19224. static_l_desc.extra_bits = extra_lbits;
  19225. static_d_desc.static_tree = static_dtree;
  19226. static_d_desc.extra_bits = extra_dbits;
  19227. static_bl_desc.extra_bits = extra_blbits;
  19228. #endif*/
  19229. /* Initialize the mapping length (0..255) -> length code (0..28) */
  19230. length = 0;
  19231. for (code = 0; code < LENGTH_CODES-1; code++) {
  19232. base_length[code] = length;
  19233. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  19234. _length_code[length++] = code;
  19235. }
  19236. }
  19237. //Assert (length == 256, "tr_static_init: length != 256");
  19238. /* Note that the length 255 (match length 258) can be represented
  19239. * in two different ways: code 284 + 5 bits or code 285, so we
  19240. * overwrite length_code[255] to use the best encoding:
  19241. */
  19242. _length_code[length-1] = code;
  19243. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  19244. dist = 0;
  19245. for (code = 0 ; code < 16; code++) {
  19246. base_dist[code] = dist;
  19247. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  19248. _dist_code[dist++] = code;
  19249. }
  19250. }
  19251. //Assert (dist == 256, "tr_static_init: dist != 256");
  19252. dist >>= 7; /* from now on, all distances are divided by 128 */
  19253. for (; code < D_CODES; code++) {
  19254. base_dist[code] = dist << 7;
  19255. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  19256. _dist_code[256 + dist++] = code;
  19257. }
  19258. }
  19259. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  19260. /* Construct the codes of the static literal tree */
  19261. for (bits = 0; bits <= MAX_BITS; bits++) {
  19262. bl_count[bits] = 0;
  19263. }
  19264. n = 0;
  19265. while (n <= 143) {
  19266. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19267. n++;
  19268. bl_count[8]++;
  19269. }
  19270. while (n <= 255) {
  19271. static_ltree[n*2 + 1]/*.Len*/ = 9;
  19272. n++;
  19273. bl_count[9]++;
  19274. }
  19275. while (n <= 279) {
  19276. static_ltree[n*2 + 1]/*.Len*/ = 7;
  19277. n++;
  19278. bl_count[7]++;
  19279. }
  19280. while (n <= 287) {
  19281. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19282. n++;
  19283. bl_count[8]++;
  19284. }
  19285. /* Codes 286 and 287 do not exist, but we must include them in the
  19286. * tree construction to get a canonical Huffman tree (longest code
  19287. * all ones)
  19288. */
  19289. gen_codes(static_ltree, L_CODES+1, bl_count);
  19290. /* The static distance tree is trivial: */
  19291. for (n = 0; n < D_CODES; n++) {
  19292. static_dtree[n*2 + 1]/*.Len*/ = 5;
  19293. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  19294. }
  19295. // Now data ready and we can init static trees
  19296. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  19297. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  19298. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  19299. //static_init_done = true;
  19300. }
  19301. /* ===========================================================================
  19302. * Initialize a new block.
  19303. */
  19304. function init_block(s) {
  19305. var n; /* iterates over tree elements */
  19306. /* Initialize the trees. */
  19307. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  19308. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  19309. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  19310. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  19311. s.opt_len = s.static_len = 0;
  19312. s.last_lit = s.matches = 0;
  19313. }
  19314. /* ===========================================================================
  19315. * Flush the bit buffer and align the output on a byte boundary
  19316. */
  19317. function bi_windup(s)
  19318. {
  19319. if (s.bi_valid > 8) {
  19320. put_short(s, s.bi_buf);
  19321. } else if (s.bi_valid > 0) {
  19322. //put_byte(s, (Byte)s->bi_buf);
  19323. s.pending_buf[s.pending++] = s.bi_buf;
  19324. }
  19325. s.bi_buf = 0;
  19326. s.bi_valid = 0;
  19327. }
  19328. /* ===========================================================================
  19329. * Copy a stored block, storing first the length and its
  19330. * one's complement if requested.
  19331. */
  19332. function copy_block(s, buf, len, header)
  19333. //DeflateState *s;
  19334. //charf *buf; /* the input data */
  19335. //unsigned len; /* its length */
  19336. //int header; /* true if block header must be written */
  19337. {
  19338. bi_windup(s); /* align on byte boundary */
  19339. if (header) {
  19340. put_short(s, len);
  19341. put_short(s, ~len);
  19342. }
  19343. // while (len--) {
  19344. // put_byte(s, *buf++);
  19345. // }
  19346. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  19347. s.pending += len;
  19348. }
  19349. /* ===========================================================================
  19350. * Compares to subtrees, using the tree depth as tie breaker when
  19351. * the subtrees have equal frequency. This minimizes the worst case length.
  19352. */
  19353. function smaller(tree, n, m, depth) {
  19354. var _n2 = n*2;
  19355. var _m2 = m*2;
  19356. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  19357. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  19358. }
  19359. /* ===========================================================================
  19360. * Restore the heap property by moving down the tree starting at node k,
  19361. * exchanging a node with the smallest of its two sons if necessary, stopping
  19362. * when the heap property is re-established (each father smaller than its
  19363. * two sons).
  19364. */
  19365. function pqdownheap(s, tree, k)
  19366. // deflate_state *s;
  19367. // ct_data *tree; /* the tree to restore */
  19368. // int k; /* node to move down */
  19369. {
  19370. var v = s.heap[k];
  19371. var j = k << 1; /* left son of k */
  19372. while (j <= s.heap_len) {
  19373. /* Set j to the smallest of the two sons: */
  19374. if (j < s.heap_len &&
  19375. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  19376. j++;
  19377. }
  19378. /* Exit if v is smaller than both sons */
  19379. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  19380. /* Exchange v with the smallest son */
  19381. s.heap[k] = s.heap[j];
  19382. k = j;
  19383. /* And continue down the tree, setting j to the left son of k */
  19384. j <<= 1;
  19385. }
  19386. s.heap[k] = v;
  19387. }
  19388. // inlined manually
  19389. // var SMALLEST = 1;
  19390. /* ===========================================================================
  19391. * Send the block data compressed using the given Huffman trees
  19392. */
  19393. function compress_block(s, ltree, dtree)
  19394. // deflate_state *s;
  19395. // const ct_data *ltree; /* literal tree */
  19396. // const ct_data *dtree; /* distance tree */
  19397. {
  19398. var dist; /* distance of matched string */
  19399. var lc; /* match length or unmatched char (if dist == 0) */
  19400. var lx = 0; /* running index in l_buf */
  19401. var code; /* the code to send */
  19402. var extra; /* number of extra bits to send */
  19403. if (s.last_lit !== 0) {
  19404. do {
  19405. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  19406. lc = s.pending_buf[s.l_buf + lx];
  19407. lx++;
  19408. if (dist === 0) {
  19409. send_code(s, lc, ltree); /* send a literal byte */
  19410. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  19411. } else {
  19412. /* Here, lc is the match length - MIN_MATCH */
  19413. code = _length_code[lc];
  19414. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  19415. extra = extra_lbits[code];
  19416. if (extra !== 0) {
  19417. lc -= base_length[code];
  19418. send_bits(s, lc, extra); /* send the extra length bits */
  19419. }
  19420. dist--; /* dist is now the match distance - 1 */
  19421. code = d_code(dist);
  19422. //Assert (code < D_CODES, "bad d_code");
  19423. send_code(s, code, dtree); /* send the distance code */
  19424. extra = extra_dbits[code];
  19425. if (extra !== 0) {
  19426. dist -= base_dist[code];
  19427. send_bits(s, dist, extra); /* send the extra distance bits */
  19428. }
  19429. } /* literal or match pair ? */
  19430. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  19431. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  19432. // "pendingBuf overflow");
  19433. } while (lx < s.last_lit);
  19434. }
  19435. send_code(s, END_BLOCK, ltree);
  19436. }
  19437. /* ===========================================================================
  19438. * Construct one Huffman tree and assigns the code bit strings and lengths.
  19439. * Update the total bit length for the current block.
  19440. * IN assertion: the field freq is set for all tree elements.
  19441. * OUT assertions: the fields len and code are set to the optimal bit length
  19442. * and corresponding code. The length opt_len is updated; static_len is
  19443. * also updated if stree is not null. The field max_code is set.
  19444. */
  19445. function build_tree(s, desc)
  19446. // deflate_state *s;
  19447. // tree_desc *desc; /* the tree descriptor */
  19448. {
  19449. var tree = desc.dyn_tree;
  19450. var stree = desc.stat_desc.static_tree;
  19451. var has_stree = desc.stat_desc.has_stree;
  19452. var elems = desc.stat_desc.elems;
  19453. var n, m; /* iterate over heap elements */
  19454. var max_code = -1; /* largest code with non zero frequency */
  19455. var node; /* new node being created */
  19456. /* Construct the initial heap, with least frequent element in
  19457. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  19458. * heap[0] is not used.
  19459. */
  19460. s.heap_len = 0;
  19461. s.heap_max = HEAP_SIZE;
  19462. for (n = 0; n < elems; n++) {
  19463. if (tree[n * 2]/*.Freq*/ !== 0) {
  19464. s.heap[++s.heap_len] = max_code = n;
  19465. s.depth[n] = 0;
  19466. } else {
  19467. tree[n*2 + 1]/*.Len*/ = 0;
  19468. }
  19469. }
  19470. /* The pkzip format requires that at least one distance code exists,
  19471. * and that at least one bit should be sent even if there is only one
  19472. * possible code. So to avoid special checks later on we force at least
  19473. * two codes of non zero frequency.
  19474. */
  19475. while (s.heap_len < 2) {
  19476. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  19477. tree[node * 2]/*.Freq*/ = 1;
  19478. s.depth[node] = 0;
  19479. s.opt_len--;
  19480. if (has_stree) {
  19481. s.static_len -= stree[node*2 + 1]/*.Len*/;
  19482. }
  19483. /* node is 0 or 1 so it does not have extra bits */
  19484. }
  19485. desc.max_code = max_code;
  19486. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  19487. * establish sub-heaps of increasing lengths:
  19488. */
  19489. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  19490. /* Construct the Huffman tree by repeatedly combining the least two
  19491. * frequent nodes.
  19492. */
  19493. node = elems; /* next internal node of the tree */
  19494. do {
  19495. //pqremove(s, tree, n); /* n = node of least frequency */
  19496. /*** pqremove ***/
  19497. n = s.heap[1/*SMALLEST*/];
  19498. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  19499. pqdownheap(s, tree, 1/*SMALLEST*/);
  19500. /***/
  19501. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  19502. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  19503. s.heap[--s.heap_max] = m;
  19504. /* Create a new node father of n and m */
  19505. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  19506. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  19507. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  19508. /* and insert the new node in the heap */
  19509. s.heap[1/*SMALLEST*/] = node++;
  19510. pqdownheap(s, tree, 1/*SMALLEST*/);
  19511. } while (s.heap_len >= 2);
  19512. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  19513. /* At this point, the fields freq and dad are set. We can now
  19514. * generate the bit lengths.
  19515. */
  19516. gen_bitlen(s, desc);
  19517. /* The field len is now set, we can generate the bit codes */
  19518. gen_codes(tree, max_code, s.bl_count);
  19519. }
  19520. /* ===========================================================================
  19521. * Scan a literal or distance tree to determine the frequencies of the codes
  19522. * in the bit length tree.
  19523. */
  19524. function scan_tree(s, tree, max_code)
  19525. // deflate_state *s;
  19526. // ct_data *tree; /* the tree to be scanned */
  19527. // int max_code; /* and its largest code of non zero frequency */
  19528. {
  19529. var n; /* iterates over all tree elements */
  19530. var prevlen = -1; /* last emitted length */
  19531. var curlen; /* length of current code */
  19532. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19533. var count = 0; /* repeat count of the current code */
  19534. var max_count = 7; /* max repeat count */
  19535. var min_count = 4; /* min repeat count */
  19536. if (nextlen === 0) {
  19537. max_count = 138;
  19538. min_count = 3;
  19539. }
  19540. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  19541. for (n = 0; n <= max_code; n++) {
  19542. curlen = nextlen;
  19543. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19544. if (++count < max_count && curlen === nextlen) {
  19545. continue;
  19546. } else if (count < min_count) {
  19547. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  19548. } else if (curlen !== 0) {
  19549. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  19550. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  19551. } else if (count <= 10) {
  19552. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  19553. } else {
  19554. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  19555. }
  19556. count = 0;
  19557. prevlen = curlen;
  19558. if (nextlen === 0) {
  19559. max_count = 138;
  19560. min_count = 3;
  19561. } else if (curlen === nextlen) {
  19562. max_count = 6;
  19563. min_count = 3;
  19564. } else {
  19565. max_count = 7;
  19566. min_count = 4;
  19567. }
  19568. }
  19569. }
  19570. /* ===========================================================================
  19571. * Send a literal or distance tree in compressed form, using the codes in
  19572. * bl_tree.
  19573. */
  19574. function send_tree(s, tree, max_code)
  19575. // deflate_state *s;
  19576. // ct_data *tree; /* the tree to be scanned */
  19577. // int max_code; /* and its largest code of non zero frequency */
  19578. {
  19579. var n; /* iterates over all tree elements */
  19580. var prevlen = -1; /* last emitted length */
  19581. var curlen; /* length of current code */
  19582. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19583. var count = 0; /* repeat count of the current code */
  19584. var max_count = 7; /* max repeat count */
  19585. var min_count = 4; /* min repeat count */
  19586. /* tree[max_code+1].Len = -1; */ /* guard already set */
  19587. if (nextlen === 0) {
  19588. max_count = 138;
  19589. min_count = 3;
  19590. }
  19591. for (n = 0; n <= max_code; n++) {
  19592. curlen = nextlen;
  19593. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19594. if (++count < max_count && curlen === nextlen) {
  19595. continue;
  19596. } else if (count < min_count) {
  19597. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  19598. } else if (curlen !== 0) {
  19599. if (curlen !== prevlen) {
  19600. send_code(s, curlen, s.bl_tree);
  19601. count--;
  19602. }
  19603. //Assert(count >= 3 && count <= 6, " 3_6?");
  19604. send_code(s, REP_3_6, s.bl_tree);
  19605. send_bits(s, count-3, 2);
  19606. } else if (count <= 10) {
  19607. send_code(s, REPZ_3_10, s.bl_tree);
  19608. send_bits(s, count-3, 3);
  19609. } else {
  19610. send_code(s, REPZ_11_138, s.bl_tree);
  19611. send_bits(s, count-11, 7);
  19612. }
  19613. count = 0;
  19614. prevlen = curlen;
  19615. if (nextlen === 0) {
  19616. max_count = 138;
  19617. min_count = 3;
  19618. } else if (curlen === nextlen) {
  19619. max_count = 6;
  19620. min_count = 3;
  19621. } else {
  19622. max_count = 7;
  19623. min_count = 4;
  19624. }
  19625. }
  19626. }
  19627. /* ===========================================================================
  19628. * Construct the Huffman tree for the bit lengths and return the index in
  19629. * bl_order of the last bit length code to send.
  19630. */
  19631. function build_bl_tree(s) {
  19632. var max_blindex; /* index of last bit length code of non zero freq */
  19633. /* Determine the bit length frequencies for literal and distance trees */
  19634. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  19635. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  19636. /* Build the bit length tree: */
  19637. build_tree(s, s.bl_desc);
  19638. /* opt_len now includes the length of the tree representations, except
  19639. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  19640. */
  19641. /* Determine the number of bit length codes to send. The pkzip format
  19642. * requires that at least 4 bit length codes be sent. (appnote.txt says
  19643. * 3 but the actual value used is 4.)
  19644. */
  19645. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  19646. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  19647. break;
  19648. }
  19649. }
  19650. /* Update opt_len to include the bit length tree and counts */
  19651. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  19652. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  19653. // s->opt_len, s->static_len));
  19654. return max_blindex;
  19655. }
  19656. /* ===========================================================================
  19657. * Send the header for a block using dynamic Huffman trees: the counts, the
  19658. * lengths of the bit length codes, the literal tree and the distance tree.
  19659. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  19660. */
  19661. function send_all_trees(s, lcodes, dcodes, blcodes)
  19662. // deflate_state *s;
  19663. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  19664. {
  19665. var rank; /* index in bl_order */
  19666. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  19667. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  19668. // "too many codes");
  19669. //Tracev((stderr, "\nbl counts: "));
  19670. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  19671. send_bits(s, dcodes-1, 5);
  19672. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  19673. for (rank = 0; rank < blcodes; rank++) {
  19674. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  19675. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  19676. }
  19677. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  19678. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  19679. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  19680. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  19681. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  19682. }
  19683. /* ===========================================================================
  19684. * Check if the data type is TEXT or BINARY, using the following algorithm:
  19685. * - TEXT if the two conditions below are satisfied:
  19686. * a) There are no non-portable control characters belonging to the
  19687. * "black list" (0..6, 14..25, 28..31).
  19688. * b) There is at least one printable character belonging to the
  19689. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  19690. * - BINARY otherwise.
  19691. * - The following partially-portable control characters form a
  19692. * "gray list" that is ignored in this detection algorithm:
  19693. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  19694. * IN assertion: the fields Freq of dyn_ltree are set.
  19695. */
  19696. function detect_data_type(s) {
  19697. /* black_mask is the bit mask of black-listed bytes
  19698. * set bits 0..6, 14..25, and 28..31
  19699. * 0xf3ffc07f = binary 11110011111111111100000001111111
  19700. */
  19701. var black_mask = 0xf3ffc07f;
  19702. var n;
  19703. /* Check for non-textual ("black-listed") bytes. */
  19704. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  19705. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  19706. return Z_BINARY;
  19707. }
  19708. }
  19709. /* Check for textual ("white-listed") bytes. */
  19710. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  19711. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  19712. return Z_TEXT;
  19713. }
  19714. for (n = 32; n < LITERALS; n++) {
  19715. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  19716. return Z_TEXT;
  19717. }
  19718. }
  19719. /* There are no "black-listed" or "white-listed" bytes:
  19720. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  19721. */
  19722. return Z_BINARY;
  19723. }
  19724. var static_init_done = false;
  19725. /* ===========================================================================
  19726. * Initialize the tree data structures for a new zlib stream.
  19727. */
  19728. function _tr_init(s)
  19729. {
  19730. if (!static_init_done) {
  19731. tr_static_init();
  19732. static_init_done = true;
  19733. }
  19734. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  19735. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  19736. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  19737. s.bi_buf = 0;
  19738. s.bi_valid = 0;
  19739. /* Initialize the first block of the first file: */
  19740. init_block(s);
  19741. }
  19742. /* ===========================================================================
  19743. * Send a stored block
  19744. */
  19745. function _tr_stored_block(s, buf, stored_len, last)
  19746. //DeflateState *s;
  19747. //charf *buf; /* input block */
  19748. //ulg stored_len; /* length of input block */
  19749. //int last; /* one if this is the last block for a file */
  19750. {
  19751. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  19752. copy_block(s, buf, stored_len, true); /* with header */
  19753. }
  19754. /* ===========================================================================
  19755. * Send one empty static block to give enough lookahead for inflate.
  19756. * This takes 10 bits, of which 7 may remain in the bit buffer.
  19757. */
  19758. function _tr_align(s) {
  19759. send_bits(s, STATIC_TREES<<1, 3);
  19760. send_code(s, END_BLOCK, static_ltree);
  19761. bi_flush(s);
  19762. }
  19763. /* ===========================================================================
  19764. * Determine the best encoding for the current block: dynamic trees, static
  19765. * trees or store, and output the encoded block to the zip file.
  19766. */
  19767. function _tr_flush_block(s, buf, stored_len, last)
  19768. //DeflateState *s;
  19769. //charf *buf; /* input block, or NULL if too old */
  19770. //ulg stored_len; /* length of input block */
  19771. //int last; /* one if this is the last block for a file */
  19772. {
  19773. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  19774. var max_blindex = 0; /* index of last bit length code of non zero freq */
  19775. /* Build the Huffman trees unless a stored block is forced */
  19776. if (s.level > 0) {
  19777. /* Check if the file is binary or text */
  19778. if (s.strm.data_type === Z_UNKNOWN) {
  19779. s.strm.data_type = detect_data_type(s);
  19780. }
  19781. /* Construct the literal and distance trees */
  19782. build_tree(s, s.l_desc);
  19783. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  19784. // s->static_len));
  19785. build_tree(s, s.d_desc);
  19786. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  19787. // s->static_len));
  19788. /* At this point, opt_len and static_len are the total bit lengths of
  19789. * the compressed block data, excluding the tree representations.
  19790. */
  19791. /* Build the bit length tree for the above two trees, and get the index
  19792. * in bl_order of the last bit length code to send.
  19793. */
  19794. max_blindex = build_bl_tree(s);
  19795. /* Determine the best encoding. Compute the block lengths in bytes. */
  19796. opt_lenb = (s.opt_len+3+7) >>> 3;
  19797. static_lenb = (s.static_len+3+7) >>> 3;
  19798. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  19799. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  19800. // s->last_lit));
  19801. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  19802. } else {
  19803. // Assert(buf != (char*)0, "lost buf");
  19804. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  19805. }
  19806. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  19807. /* 4: two words for the lengths */
  19808. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  19809. * Otherwise we can't have processed more than WSIZE input bytes since
  19810. * the last block flush, because compression would have been
  19811. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  19812. * transform a block into a stored block.
  19813. */
  19814. _tr_stored_block(s, buf, stored_len, last);
  19815. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  19816. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  19817. compress_block(s, static_ltree, static_dtree);
  19818. } else {
  19819. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  19820. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  19821. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  19822. }
  19823. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  19824. /* The above check is made mod 2^32, for files larger than 512 MB
  19825. * and uLong implemented on 32 bits.
  19826. */
  19827. init_block(s);
  19828. if (last) {
  19829. bi_windup(s);
  19830. }
  19831. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  19832. // s->compressed_len-7*last));
  19833. }
  19834. /* ===========================================================================
  19835. * Save the match info and tally the frequency counts. Return true if
  19836. * the current block must be flushed.
  19837. */
  19838. function _tr_tally(s, dist, lc)
  19839. // deflate_state *s;
  19840. // unsigned dist; /* distance of matched string */
  19841. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  19842. {
  19843. //var out_length, in_length, dcode;
  19844. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  19845. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  19846. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  19847. s.last_lit++;
  19848. if (dist === 0) {
  19849. /* lc is the unmatched char */
  19850. s.dyn_ltree[lc*2]/*.Freq*/++;
  19851. } else {
  19852. s.matches++;
  19853. /* Here, lc is the match length - MIN_MATCH */
  19854. dist--; /* dist = match distance - 1 */
  19855. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  19856. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  19857. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  19858. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  19859. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  19860. }
  19861. // (!) This block is disabled in zlib defailts,
  19862. // don't enable it for binary compatibility
  19863. //#ifdef TRUNCATE_BLOCK
  19864. // /* Try to guess if it is profitable to stop the current block here */
  19865. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  19866. // /* Compute an upper bound for the compressed length */
  19867. // out_length = s.last_lit*8;
  19868. // in_length = s.strstart - s.block_start;
  19869. //
  19870. // for (dcode = 0; dcode < D_CODES; dcode++) {
  19871. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  19872. // }
  19873. // out_length >>>= 3;
  19874. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  19875. // // s->last_lit, in_length, out_length,
  19876. // // 100L - out_length*100L/in_length));
  19877. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  19878. // return true;
  19879. // }
  19880. // }
  19881. //#endif
  19882. return (s.last_lit === s.lit_bufsize-1);
  19883. /* We avoid equality with lit_bufsize because of wraparound at 64K
  19884. * on 16 bit machines and because stored blocks are restricted to
  19885. * 64K-1 bytes.
  19886. */
  19887. }
  19888. exports._tr_init = _tr_init;
  19889. exports._tr_stored_block = _tr_stored_block;
  19890. exports._tr_flush_block = _tr_flush_block;
  19891. exports._tr_tally = _tr_tally;
  19892. exports._tr_align = _tr_align;
  19893. },{"../utils/common":54}],66:[function(require,module,exports){
  19894. 'use strict';
  19895. function ZStream() {
  19896. /* next input byte */
  19897. this.input = null; // JS specific, because we have no pointers
  19898. this.next_in = 0;
  19899. /* number of bytes available at input */
  19900. this.avail_in = 0;
  19901. /* total number of input bytes read so far */
  19902. this.total_in = 0;
  19903. /* next output byte should be put there */
  19904. this.output = null; // JS specific, because we have no pointers
  19905. this.next_out = 0;
  19906. /* remaining free space at output */
  19907. this.avail_out = 0;
  19908. /* total number of bytes output so far */
  19909. this.total_out = 0;
  19910. /* last error message, NULL if no error */
  19911. this.msg = ''/*Z_NULL*/;
  19912. /* not visible by applications */
  19913. this.state = null;
  19914. /* best guess about the data type: binary or text */
  19915. this.data_type = 2/*Z_UNKNOWN*/;
  19916. /* adler32 value of the uncompressed data */
  19917. this.adler = 0;
  19918. }
  19919. module.exports = ZStream;
  19920. },{}],67:[function(require,module,exports){
  19921. /* Copyright @ 2015 Atlassian Pty Ltd
  19922. *
  19923. * Licensed under the Apache License, Version 2.0 (the "License");
  19924. * you may not use this file except in compliance with the License.
  19925. * You may obtain a copy of the License at
  19926. *
  19927. * http://www.apache.org/licenses/LICENSE-2.0
  19928. *
  19929. * Unless required by applicable law or agreed to in writing, software
  19930. * distributed under the License is distributed on an "AS IS" BASIS,
  19931. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19932. * See the License for the specific language governing permissions and
  19933. * limitations under the License.
  19934. */
  19935. module.exports = function arrayEquals(array) {
  19936. // if the other array is a falsy value, return
  19937. if (!array)
  19938. return false;
  19939. // compare lengths - can save a lot of time
  19940. if (this.length != array.length)
  19941. return false;
  19942. for (var i = 0, l = this.length; i < l; i++) {
  19943. // Check if we have nested arrays
  19944. if (this[i] instanceof Array && array[i] instanceof Array) {
  19945. // recurse into the nested arrays
  19946. if (!arrayEquals.apply(this[i], [array[i]]))
  19947. return false;
  19948. } else if (this[i] != array[i]) {
  19949. // Warning - two different object instances will never be equal:
  19950. // {x:20} != {x:20}
  19951. return false;
  19952. }
  19953. }
  19954. return true;
  19955. };
  19956. },{}],68:[function(require,module,exports){
  19957. /* Copyright @ 2015 Atlassian Pty Ltd
  19958. *
  19959. * Licensed under the Apache License, Version 2.0 (the "License");
  19960. * you may not use this file except in compliance with the License.
  19961. * You may obtain a copy of the License at
  19962. *
  19963. * http://www.apache.org/licenses/LICENSE-2.0
  19964. *
  19965. * Unless required by applicable law or agreed to in writing, software
  19966. * distributed under the License is distributed on an "AS IS" BASIS,
  19967. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19968. * See the License for the specific language governing permissions and
  19969. * limitations under the License.
  19970. */
  19971. exports.Interop = require('./interop');
  19972. },{"./interop":69}],69:[function(require,module,exports){
  19973. /* Copyright @ 2015 Atlassian Pty Ltd
  19974. *
  19975. * Licensed under the Apache License, Version 2.0 (the "License");
  19976. * you may not use this file except in compliance with the License.
  19977. * You may obtain a copy of the License at
  19978. *
  19979. * http://www.apache.org/licenses/LICENSE-2.0
  19980. *
  19981. * Unless required by applicable law or agreed to in writing, software
  19982. * distributed under the License is distributed on an "AS IS" BASIS,
  19983. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19984. * See the License for the specific language governing permissions and
  19985. * limitations under the License.
  19986. */
  19987. /* global RTCSessionDescription */
  19988. /* jshint -W097 */
  19989. "use strict";
  19990. var transform = require('./transform');
  19991. var arrayEquals = require('./array-equals');
  19992. function Interop() {
  19993. /**
  19994. * This map holds the most recent Unified Plan offer/answer SDP that was
  19995. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  19996. * the SDP string as values.
  19997. *
  19998. * @type {{}}
  19999. */
  20000. this.cache = {};
  20001. }
  20002. module.exports = Interop;
  20003. /**
  20004. * Returns the index of the first m-line with the given media type and with a
  20005. * direction which allows sending, in the last Unified Plan description with
  20006. * type "answer" converted to Plan B. Returns {null} if there is no saved
  20007. * answer, or if none of its m-lines with the given type allow sending.
  20008. * @param type the media type ("audio" or "video").
  20009. * @returns {*}
  20010. */
  20011. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  20012. if (!this.cache.answer) {
  20013. return null;
  20014. }
  20015. var session = transform.parse(this.cache.answer);
  20016. if (session && session.media && Array.isArray(session.media)){
  20017. for (var i = 0; i < session.media.length; i++) {
  20018. if (session.media[i].type == type &&
  20019. (!session.media[i].direction /* default to sendrecv */ ||
  20020. session.media[i].direction === 'sendrecv' ||
  20021. session.media[i].direction === 'sendonly')){
  20022. return i;
  20023. }
  20024. }
  20025. }
  20026. return null;
  20027. };
  20028. /**
  20029. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  20030. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  20031. * application.
  20032. *
  20033. * @param desc
  20034. * @returns {*}
  20035. */
  20036. Interop.prototype.toPlanB = function(desc) {
  20037. var self = this;
  20038. //#region Preliminary input validation.
  20039. if (typeof desc !== 'object' || desc === null ||
  20040. typeof desc.sdp !== 'string') {
  20041. console.warn('An empty description was passed as an argument.');
  20042. return desc;
  20043. }
  20044. // Objectify the SDP for easier manipulation.
  20045. var session = transform.parse(desc.sdp);
  20046. // If the SDP contains no media, there's nothing to transform.
  20047. if (typeof session.media === 'undefined' ||
  20048. !Array.isArray(session.media) || session.media.length === 0) {
  20049. console.warn('The description has no media.');
  20050. return desc;
  20051. }
  20052. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  20053. // SDP has a video, an audio and a data "channel" at most.
  20054. if (session.media.length <= 3 && session.media.every(function(m) {
  20055. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20056. })) {
  20057. console.warn('This description does not look like Unified Plan.');
  20058. return desc;
  20059. }
  20060. //#endregion
  20061. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  20062. var sdp = desc.sdp;
  20063. var rewrite = false;
  20064. for (var i = 0; i < session.media.length; i++) {
  20065. var uLine = session.media[i];
  20066. uLine.rtp.forEach(function(rtp) {
  20067. if (rtp.codec === 'NULL')
  20068. {
  20069. rewrite = true;
  20070. var offer = transform.parse(self.cache['offer']);
  20071. rtp.codec = offer.media[i].rtp[0].codec;
  20072. }
  20073. });
  20074. };
  20075. if (rewrite) {
  20076. sdp = transform.write(session);
  20077. }
  20078. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  20079. // -> Unified Plan transformation.
  20080. this.cache[desc.type] = sdp;
  20081. //#region Convert from Unified Plan to Plan B.
  20082. // We rebuild the session.media array.
  20083. var media = session.media;
  20084. session.media = [];
  20085. // Associative array that maps channel types to channel objects for fast
  20086. // access to channel objects by their type, e.g. type2bl['audio']->channel
  20087. // obj.
  20088. var type2bl = {};
  20089. // Used to build the group:BUNDLE value after the channels construction
  20090. // loop.
  20091. var types = [];
  20092. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  20093. media.forEach(function(uLine) {
  20094. // rtcp-mux is required in the Plan B SDP.
  20095. if ((typeof uLine.rtcpMux !== 'string' ||
  20096. uLine.rtcpMux !== 'rtcp-mux') &&
  20097. uLine.direction !== 'inactive') {
  20098. throw new Error('Cannot convert to Plan B because m-lines ' +
  20099. 'without the rtcp-mux attribute were found.');
  20100. }
  20101. if (uLine.type === 'application') {
  20102. session.media.push(uLine);
  20103. types.push(uLine.mid);
  20104. return;
  20105. }
  20106. // If we don't have a channel for this uLine.type, then use this
  20107. // uLine as the channel basis.
  20108. if (typeof type2bl[uLine.type] === 'undefined') {
  20109. type2bl[uLine.type] = uLine;
  20110. }
  20111. // Add sources to the channel and handle a=msid.
  20112. if (typeof uLine.sources === 'object') {
  20113. Object.keys(uLine.sources).forEach(function(ssrc) {
  20114. if (typeof type2bl[uLine.type].sources !== 'object')
  20115. type2bl[uLine.type].sources = {};
  20116. // Assign the sources to the channel.
  20117. type2bl[uLine.type].sources[ssrc] =
  20118. uLine.sources[ssrc];
  20119. if (typeof uLine.msid !== 'undefined') {
  20120. // In Plan B the msid is an SSRC attribute. Also, we don't
  20121. // care about the obsolete label and mslabel attributes.
  20122. //
  20123. // Note that it is not guaranteed that the uLine will
  20124. // have an msid. recvonly channels in particular don't have
  20125. // one.
  20126. type2bl[uLine.type].sources[ssrc].msid =
  20127. uLine.msid;
  20128. }
  20129. // NOTE ssrcs in ssrc groups will share msids, as
  20130. // draft-uberti-rtcweb-plan-00 mandates.
  20131. });
  20132. }
  20133. // Add ssrc groups to the channel.
  20134. if (typeof uLine.ssrcGroups !== 'undefined' &&
  20135. Array.isArray(uLine.ssrcGroups)) {
  20136. // Create the ssrcGroups array, if it's not defined.
  20137. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  20138. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  20139. type2bl[uLine.type].ssrcGroups = [];
  20140. }
  20141. type2bl[uLine.type].ssrcGroups =
  20142. type2bl[uLine.type].ssrcGroups.concat(
  20143. uLine.ssrcGroups);
  20144. }
  20145. if (type2bl[uLine.type] === uLine) {
  20146. // Copy ICE related stuff from the principal media line.
  20147. uLine.candidates = media[0].candidates;
  20148. uLine.iceUfrag = media[0].iceUfrag;
  20149. uLine.icePwd = media[0].icePwd;
  20150. uLine.fingerprint = media[0].fingerprint;
  20151. // Plan B mids are in ['audio', 'video', 'data']
  20152. uLine.mid = uLine.type;
  20153. // Plan B doesn't support/need the bundle-only attribute.
  20154. delete uLine.bundleOnly;
  20155. // In Plan B the msid is an SSRC attribute.
  20156. delete uLine.msid;
  20157. // Used to build the group:BUNDLE value after this loop.
  20158. types.push(uLine.type);
  20159. // Add the channel to the new media array.
  20160. session.media.push(uLine);
  20161. }
  20162. });
  20163. // We regenerate the BUNDLE group with the new mids.
  20164. session.groups.some(function(group) {
  20165. if (group.type === 'BUNDLE') {
  20166. group.mids = types.join(' ');
  20167. return true;
  20168. }
  20169. });
  20170. // msid semantic
  20171. session.msidSemantic = {
  20172. semantic: 'WMS',
  20173. token: '*'
  20174. };
  20175. var resStr = transform.write(session);
  20176. return new RTCSessionDescription({
  20177. type: desc.type,
  20178. sdp: resStr
  20179. });
  20180. //#endregion
  20181. };
  20182. /**
  20183. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  20184. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  20185. * to FF.
  20186. *
  20187. * @param desc
  20188. * @returns {*}
  20189. */
  20190. Interop.prototype.toUnifiedPlan = function(desc) {
  20191. var self = this;
  20192. //#region Preliminary input validation.
  20193. if (typeof desc !== 'object' || desc === null ||
  20194. typeof desc.sdp !== 'string') {
  20195. console.warn('An empty description was passed as an argument.');
  20196. return desc;
  20197. }
  20198. var session = transform.parse(desc.sdp);
  20199. // If the SDP contains no media, there's nothing to transform.
  20200. if (typeof session.media === 'undefined' ||
  20201. !Array.isArray(session.media) || session.media.length === 0) {
  20202. console.warn('The description has no media.');
  20203. return desc;
  20204. }
  20205. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  20206. // a video, an audio and a data "channel" at most.
  20207. if (session.media.length > 3 || !session.media.every(function(m) {
  20208. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20209. })) {
  20210. console.warn('This description does not look like Plan B.');
  20211. return desc;
  20212. }
  20213. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  20214. var mids = [];
  20215. session.media.forEach(function(m) {
  20216. mids.push(m.mid);
  20217. });
  20218. var hasBundle = false;
  20219. if (typeof session.groups !== 'undefined' &&
  20220. Array.isArray(session.groups)) {
  20221. hasBundle = session.groups.every(function(g) {
  20222. return g.type !== 'BUNDLE' ||
  20223. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  20224. });
  20225. }
  20226. if (!hasBundle) {
  20227. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  20228. " are not bundled were found.");
  20229. }
  20230. //#endregion
  20231. //#region Convert from Plan B to Unified Plan.
  20232. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  20233. // rebuild an equivalent Unified Plan offer/answer.
  20234. //
  20235. // For example, if this is a local answer (in Unified Plan style) that we
  20236. // convert to Plan B prior to handing it over to the application (the
  20237. // PeerConnection wrapper called us, for instance, after a successful
  20238. // createAnswer), we want to remember the m-line at which we've seen the
  20239. // (local) SSRC. That's because when the application wants to do call the
  20240. // SLD method, forcing us to do the inverse transformation (from Plan B to
  20241. // Unified Plan), we need to know to which m-line to assign the (local)
  20242. // SSRC. We also need to know all the other m-lines that the original
  20243. // answer had and include them in the transformed answer as well.
  20244. //
  20245. // Another example is if this is a remote offer that we convert to Plan B
  20246. // prior to giving it to the application, we want to remember the mid at
  20247. // which we've seen the (remote) SSRC.
  20248. //
  20249. // In the iteration that follows, we use the cached Unified Plan (if it
  20250. // exists) to assign mids to ssrcs.
  20251. var cached;
  20252. if (typeof this.cache[desc.type] !== 'undefined') {
  20253. cached = transform.parse(this.cache[desc.type]);
  20254. }
  20255. var recvonlySsrcs = {
  20256. audio: {},
  20257. video: {}
  20258. };
  20259. // A helper map that sends mids to m-line objects. We use it later to
  20260. // rebuild the Unified Plan style session.media array.
  20261. var mid2ul = {};
  20262. session.media.forEach(function(bLine) {
  20263. if ((typeof bLine.rtcpMux !== 'string' ||
  20264. bLine.rtcpMux !== 'rtcp-mux') &&
  20265. bLine.direction !== 'inactive') {
  20266. throw new Error("Cannot convert to Unified Plan because m-lines " +
  20267. "without the rtcp-mux attribute were found.");
  20268. }
  20269. if (bLine.type === 'application') {
  20270. mid2ul[bLine.mid] = bLine;
  20271. return;
  20272. }
  20273. // With rtcp-mux and bundle all the channels should have the same ICE
  20274. // stuff.
  20275. var sources = bLine.sources;
  20276. var ssrcGroups = bLine.ssrcGroups;
  20277. var candidates = bLine.candidates;
  20278. var iceUfrag = bLine.iceUfrag;
  20279. var icePwd = bLine.icePwd;
  20280. var fingerprint = bLine.fingerprint;
  20281. var port = bLine.port;
  20282. // We'll use the "bLine" object as a prototype for each new "mLine"
  20283. // that we create, but first we need to clean it up a bit.
  20284. delete bLine.sources;
  20285. delete bLine.ssrcGroups;
  20286. delete bLine.candidates;
  20287. delete bLine.iceUfrag;
  20288. delete bLine.icePwd;
  20289. delete bLine.fingerprint;
  20290. delete bLine.port;
  20291. delete bLine.mid;
  20292. // inverted ssrc group map
  20293. var ssrc2group = {};
  20294. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  20295. ssrcGroups.forEach(function (ssrcGroup) {
  20296. // TODO(gp) find out how to receive simulcast with FF. For the
  20297. // time being, hide it.
  20298. if (ssrcGroup.semantics === 'SIM') {
  20299. return;
  20300. }
  20301. // XXX This might brake if an SSRC is in more than one group
  20302. // for some reason.
  20303. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20304. Array.isArray(ssrcGroup.ssrcs)) {
  20305. ssrcGroup.ssrcs.forEach(function (ssrc) {
  20306. if (typeof ssrc2group[ssrc] === 'undefined') {
  20307. ssrc2group[ssrc] = [];
  20308. }
  20309. ssrc2group[ssrc].push(ssrcGroup);
  20310. });
  20311. }
  20312. });
  20313. }
  20314. // ssrc to m-line index.
  20315. var ssrc2ml = {};
  20316. if (typeof sources === 'object') {
  20317. // Explode the Plan B channel sources with one m-line per source.
  20318. Object.keys(sources).forEach(function(ssrc) {
  20319. // The (unified) m-line for this SSRC. We either create it from
  20320. // scratch or, if it's a grouped SSRC, we re-use a related
  20321. // mline. In other words, if the source is grouped with another
  20322. // source, put the two together in the same m-line.
  20323. var uLine;
  20324. // We assume here that we are the answerer in the O/A, so any
  20325. // offers which we translate come from the remote side, while
  20326. // answers are local. So the check below is to make that we
  20327. // handle receive-only SSRCs in a special way only if they come
  20328. // from the remote side.
  20329. if (desc.type==='offer') {
  20330. // We want to detect SSRCs which are used by a remote peer
  20331. // in an m-line with direction=recvonly (i.e. they are
  20332. // being used for RTCP only).
  20333. // This information would have gotten lost if the remote
  20334. // peer used Unified Plan and their local description was
  20335. // translated to Plan B. So we use the lack of an MSID
  20336. // attribute to deduce a "receive only" SSRC.
  20337. if (!sources[ssrc].msid) {
  20338. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  20339. // Receive-only SSRCs must not create new m-lines. We
  20340. // will assign them to an existing m-line later.
  20341. return;
  20342. }
  20343. }
  20344. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  20345. Array.isArray(ssrc2group[ssrc])) {
  20346. ssrc2group[ssrc].some(function (ssrcGroup) {
  20347. // ssrcGroup.ssrcs *is* an Array, no need to check
  20348. // again here.
  20349. return ssrcGroup.ssrcs.some(function (related) {
  20350. if (typeof ssrc2ml[related] === 'object') {
  20351. uLine = ssrc2ml[related];
  20352. return true;
  20353. }
  20354. });
  20355. });
  20356. }
  20357. if (typeof uLine === 'object') {
  20358. // the m-line already exists. Just add the source.
  20359. uLine.sources[ssrc] = sources[ssrc];
  20360. delete sources[ssrc].msid;
  20361. } else {
  20362. // Use the "bLine" as a prototype for the "uLine".
  20363. uLine = Object.create(bLine);
  20364. ssrc2ml[ssrc] = uLine;
  20365. if (typeof sources[ssrc].msid !== 'undefined') {
  20366. // Assign the msid of the source to the m-line. Note
  20367. // that it is not guaranteed that the source will have
  20368. // msid. In particular "recvonly" sources don't have an
  20369. // msid. Note that "recvonly" is a term only defined
  20370. // for m-lines.
  20371. uLine.msid = sources[ssrc].msid;
  20372. uLine.direction = 'sendrecv';
  20373. delete sources[ssrc].msid;
  20374. }
  20375. // We assign one SSRC per media line.
  20376. uLine.sources = {};
  20377. uLine.sources[ssrc] = sources[ssrc];
  20378. uLine.ssrcGroups = ssrc2group[ssrc];
  20379. // Use the cached Unified Plan SDP (if it exists) to assign
  20380. // SSRCs to mids.
  20381. if (typeof cached !== 'undefined' &&
  20382. typeof cached.media !== 'undefined' &&
  20383. Array.isArray(cached.media)) {
  20384. cached.media.forEach(function (m) {
  20385. if (typeof m.sources === 'object') {
  20386. Object.keys(m.sources).forEach(function (s) {
  20387. if (s === ssrc) {
  20388. uLine.mid = m.mid;
  20389. }
  20390. });
  20391. }
  20392. });
  20393. }
  20394. if (typeof uLine.mid === 'undefined') {
  20395. // If this is an SSRC that we see for the first time
  20396. // assign it a new mid. This is typically the case when
  20397. // this method is called to transform a remote
  20398. // description for the first time or when there is a
  20399. // new SSRC in the remote description because a new
  20400. // peer has joined the conference. Local SSRCs should
  20401. // have already been added to the map in the toPlanB
  20402. // method.
  20403. //
  20404. // Because FF generates answers in Unified Plan style,
  20405. // we MUST already have a cached answer with all the
  20406. // local SSRCs mapped to some m-line/mid.
  20407. if (desc.type === 'answer') {
  20408. throw new Error("An unmapped SSRC was found.");
  20409. }
  20410. uLine.mid = [bLine.type, '-', ssrc].join('');
  20411. }
  20412. // Include the candidates in the 1st media line.
  20413. uLine.candidates = candidates;
  20414. uLine.iceUfrag = iceUfrag;
  20415. uLine.icePwd = icePwd;
  20416. uLine.fingerprint = fingerprint;
  20417. uLine.port = port;
  20418. mid2ul[uLine.mid] = uLine;
  20419. }
  20420. });
  20421. }
  20422. });
  20423. // Rebuild the media array in the right order and add the missing mLines
  20424. // (missing from the Plan B SDP).
  20425. session.media = [];
  20426. mids = []; // reuse
  20427. if (desc.type === 'answer') {
  20428. // The media lines in the answer must match the media lines in the
  20429. // offer. The order is important too. Here we assume that Firefox is
  20430. // the answerer, so we merely have to use the reconstructed (unified)
  20431. // answer to update the cached (unified) answer accordingly.
  20432. //
  20433. // In the general case, one would have to use the cached (unified)
  20434. // offer to find the m-lines that are missing from the reconstructed
  20435. // answer, potentially grabbing them from the cached (unified) answer.
  20436. // One has to be careful with this approach because inactive m-lines do
  20437. // not always have an mid, making it tricky (impossible?) to find where
  20438. // exactly and which m-lines are missing from the reconstructed answer.
  20439. for (var i = 0; i < cached.media.length; i++) {
  20440. var uLine = cached.media[i];
  20441. if (typeof mid2ul[uLine.mid] === 'undefined') {
  20442. // The mid isn't in the reconstructed (unified) answer.
  20443. // This is either a (unified) m-line containing a remote
  20444. // track only, or a (unified) m-line containing a remote
  20445. // track and a local track that has been removed.
  20446. // In either case, it MUST exist in the cached
  20447. // (unified) answer.
  20448. //
  20449. // In case this is a removed local track, clean-up
  20450. // the (unified) m-line and make sure it's 'recvonly' or
  20451. // 'inactive'.
  20452. delete uLine.msid;
  20453. delete uLine.sources;
  20454. delete uLine.ssrcGroups;
  20455. if (!uLine.direction
  20456. || uLine.direction === 'sendrecv')
  20457. uLine.direction = 'recvonly';
  20458. else if (uLine.direction === 'sendonly')
  20459. uLine.direction = 'inactive';
  20460. } else {
  20461. // This is an (unified) m-line/channel that contains a local
  20462. // track (sendrecv or sendonly channel) or it's a unified
  20463. // recvonly m-line/channel. In either case, since we're
  20464. // going from PlanB -> Unified Plan this m-line MUST
  20465. // exist in the cached answer.
  20466. }
  20467. session.media.push(uLine);
  20468. if (typeof uLine.mid === 'string') {
  20469. // inactive lines don't/may not have an mid.
  20470. mids.push(uLine.mid);
  20471. }
  20472. }
  20473. } else {
  20474. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  20475. // under any circumstances. If we are no longer interested in sending a
  20476. // track, we just remove the msid and ssrc attributes and set it to
  20477. // either a=recvonly (as the reofferer, we must use recvonly if the
  20478. // other side was previously sending on the m-section, but we can also
  20479. // leave the possibility open if it wasn't previously in use), or
  20480. // a=inactive.
  20481. if (typeof cached !== 'undefined' &&
  20482. typeof cached.media !== 'undefined' &&
  20483. Array.isArray(cached.media)) {
  20484. cached.media.forEach(function(uLine) {
  20485. mids.push(uLine.mid);
  20486. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  20487. session.media.push(mid2ul[uLine.mid]);
  20488. } else {
  20489. delete uLine.msid;
  20490. delete uLine.sources;
  20491. delete uLine.ssrcGroups;
  20492. if (!uLine.direction
  20493. || uLine.direction === 'sendrecv')
  20494. uLine.direction = 'recvonly';
  20495. if (!uLine.direction
  20496. || uLine.direction === 'sendonly')
  20497. uLine.direction = 'inactive';
  20498. session.media.push(uLine);
  20499. }
  20500. });
  20501. }
  20502. // Add all the remaining (new) m-lines of the transformed SDP.
  20503. Object.keys(mid2ul).forEach(function(mid) {
  20504. if (mids.indexOf(mid) === -1) {
  20505. mids.push(mid);
  20506. if (mid2ul[mid].direction === 'recvonly') {
  20507. // This is a remote recvonly channel. Add its SSRC to the
  20508. // appropriate sendrecv or sendonly channel.
  20509. // TODO(gp) what if we don't have sendrecv/sendonly
  20510. // channel?
  20511. session.media.some(function (uLine) {
  20512. if ((uLine.direction === 'sendrecv' ||
  20513. uLine.direction === 'sendonly') &&
  20514. uLine.type === mid2ul[mid].type) {
  20515. // mid2ul[mid] shouldn't have any ssrc-groups
  20516. Object.keys(mid2ul[mid].sources).forEach(
  20517. function (ssrc) {
  20518. uLine.sources[ssrc] =
  20519. mid2ul[mid].sources[ssrc];
  20520. });
  20521. return true;
  20522. }
  20523. });
  20524. } else {
  20525. session.media.push(mid2ul[mid]);
  20526. }
  20527. }
  20528. });
  20529. }
  20530. // After we have constructed the Plan Unified m-lines we can figure out
  20531. // where (in which m-line) to place the 'recvonly SSRCs'.
  20532. // Note: we assume here that we are the answerer in the O/A, so any offers
  20533. // which we translate come from the remote side, while answers are local
  20534. // (and so our last local description is cached as an 'answer').
  20535. ["audio", "video"].forEach(function (type) {
  20536. if (!session || !session.media || !Array.isArray(session.media))
  20537. return;
  20538. var idx = null;
  20539. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  20540. idx = self.getFirstSendingIndexFromAnswer(type);
  20541. if (idx === null){
  20542. // If this is the first offer we receive, we don't have a
  20543. // cached answer. Assume that we will be sending media using
  20544. // the first m-line for each media type.
  20545. for (var i = 0; i < session.media.length; i++) {
  20546. if (session.media[i].type === type) {
  20547. idx = i;
  20548. break;
  20549. }
  20550. }
  20551. }
  20552. }
  20553. if (idx && session.media.length > idx) {
  20554. var mLine = session.media[idx];
  20555. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  20556. if (mLine.sources && mLine.sources[ssrc]) {
  20557. console.warn("Replacing an existing SSRC.");
  20558. }
  20559. if (!mLine.sources) {
  20560. mLine.sources = {};
  20561. }
  20562. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  20563. });
  20564. }
  20565. });
  20566. // We regenerate the BUNDLE group (since we regenerated the mids)
  20567. session.groups.some(function(group) {
  20568. if (group.type === 'BUNDLE') {
  20569. group.mids = mids.join(' ');
  20570. return true;
  20571. }
  20572. });
  20573. // msid semantic
  20574. session.msidSemantic = {
  20575. semantic: 'WMS',
  20576. token: '*'
  20577. };
  20578. var resStr = transform.write(session);
  20579. // Cache the transformed SDP (Unified Plan) for later re-use in this
  20580. // function.
  20581. this.cache[desc.type] = resStr;
  20582. return new RTCSessionDescription({
  20583. type: desc.type,
  20584. sdp: resStr
  20585. });
  20586. //#endregion
  20587. };
  20588. },{"./array-equals":67,"./transform":70}],70:[function(require,module,exports){
  20589. /* Copyright @ 2015 Atlassian Pty Ltd
  20590. *
  20591. * Licensed under the Apache License, Version 2.0 (the "License");
  20592. * you may not use this file except in compliance with the License.
  20593. * You may obtain a copy of the License at
  20594. *
  20595. * http://www.apache.org/licenses/LICENSE-2.0
  20596. *
  20597. * Unless required by applicable law or agreed to in writing, software
  20598. * distributed under the License is distributed on an "AS IS" BASIS,
  20599. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20600. * See the License for the specific language governing permissions and
  20601. * limitations under the License.
  20602. */
  20603. var transform = require('sdp-transform');
  20604. exports.write = function(session, opts) {
  20605. if (typeof session !== 'undefined' &&
  20606. typeof session.media !== 'undefined' &&
  20607. Array.isArray(session.media)) {
  20608. session.media.forEach(function (mLine) {
  20609. // expand sources to ssrcs
  20610. if (typeof mLine.sources !== 'undefined' &&
  20611. Object.keys(mLine.sources).length !== 0) {
  20612. mLine.ssrcs = [];
  20613. Object.keys(mLine.sources).forEach(function (ssrc) {
  20614. var source = mLine.sources[ssrc];
  20615. Object.keys(source).forEach(function (attribute) {
  20616. mLine.ssrcs.push({
  20617. id: ssrc,
  20618. attribute: attribute,
  20619. value: source[attribute]
  20620. });
  20621. });
  20622. });
  20623. delete mLine.sources;
  20624. }
  20625. // join ssrcs in ssrc groups
  20626. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20627. Array.isArray(mLine.ssrcGroups)) {
  20628. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20629. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20630. Array.isArray(ssrcGroup.ssrcs)) {
  20631. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  20632. }
  20633. });
  20634. }
  20635. });
  20636. }
  20637. // join group mids
  20638. if (typeof session !== 'undefined' &&
  20639. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20640. session.groups.forEach(function (g) {
  20641. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  20642. g.mids = g.mids.join(' ');
  20643. }
  20644. });
  20645. }
  20646. return transform.write(session, opts);
  20647. };
  20648. exports.parse = function(sdp) {
  20649. var session = transform.parse(sdp);
  20650. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  20651. Array.isArray(session.media)) {
  20652. session.media.forEach(function (mLine) {
  20653. // group sources attributes by ssrc
  20654. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20655. mLine.sources = {};
  20656. mLine.ssrcs.forEach(function (ssrc) {
  20657. if (!mLine.sources[ssrc.id])
  20658. mLine.sources[ssrc.id] = {};
  20659. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20660. });
  20661. delete mLine.ssrcs;
  20662. }
  20663. // split ssrcs in ssrc groups
  20664. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20665. Array.isArray(mLine.ssrcGroups)) {
  20666. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20667. if (typeof ssrcGroup.ssrcs === 'string') {
  20668. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  20669. }
  20670. });
  20671. }
  20672. });
  20673. }
  20674. // split group mids
  20675. if (typeof session !== 'undefined' &&
  20676. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20677. session.groups.forEach(function (g) {
  20678. if (typeof g.mids === 'string') {
  20679. g.mids = g.mids.split(' ');
  20680. }
  20681. });
  20682. }
  20683. return session;
  20684. };
  20685. },{"sdp-transform":72}],71:[function(require,module,exports){
  20686. var grammar = module.exports = {
  20687. v: [{
  20688. name: 'version',
  20689. reg: /^(\d*)$/
  20690. }],
  20691. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20692. // NB: sessionId will be a String in most cases because it is huge
  20693. name: 'origin',
  20694. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20695. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20696. format: "%s %s %d %s IP%d %s"
  20697. }],
  20698. // default parsing of these only (though some of these feel outdated)
  20699. s: [{ name: 'name' }],
  20700. i: [{ name: 'description' }],
  20701. u: [{ name: 'uri' }],
  20702. e: [{ name: 'email' }],
  20703. p: [{ name: 'phone' }],
  20704. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20705. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20706. //k: [{}], // outdated thing ignored
  20707. t: [{ //t=0 0
  20708. name: 'timing',
  20709. reg: /^(\d*) (\d*)/,
  20710. names: ['start', 'stop'],
  20711. format: "%d %d"
  20712. }],
  20713. c: [{ //c=IN IP4 10.47.197.26
  20714. name: 'connection',
  20715. reg: /^IN IP(\d) (\S*)/,
  20716. names: ['version', 'ip'],
  20717. format: "IN IP%d %s"
  20718. }],
  20719. b: [{ //b=AS:4000
  20720. push: 'bandwidth',
  20721. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20722. names: ['type', 'limit'],
  20723. format: "%s:%s"
  20724. }],
  20725. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20726. // NB: special - pushes to session
  20727. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20728. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20729. names: ['type', 'port', 'protocol', 'payloads'],
  20730. format: "%s %d %s %s"
  20731. }],
  20732. a: [
  20733. { //a=rtpmap:110 opus/48000/2
  20734. push: 'rtp',
  20735. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  20736. names: ['payload', 'codec', 'rate', 'encoding'],
  20737. format: function (o) {
  20738. return (o.encoding) ?
  20739. "rtpmap:%d %s/%s/%s":
  20740. o.rate ?
  20741. "rtpmap:%d %s/%s":
  20742. "rtpmap:%d %s";
  20743. }
  20744. },
  20745. {
  20746. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20747. //a=fmtp:111 minptime=10; useinbandfec=1
  20748. push: 'fmtp',
  20749. reg: /^fmtp:(\d*) ([\S| ]*)/,
  20750. names: ['payload', 'config'],
  20751. format: "fmtp:%d %s"
  20752. },
  20753. { //a=control:streamid=0
  20754. name: 'control',
  20755. reg: /^control:(.*)/,
  20756. format: "control:%s"
  20757. },
  20758. { //a=rtcp:65179 IN IP4 193.84.77.194
  20759. name: 'rtcp',
  20760. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20761. names: ['port', 'netType', 'ipVer', 'address'],
  20762. format: function (o) {
  20763. return (o.address != null) ?
  20764. "rtcp:%d %s IP%d %s":
  20765. "rtcp:%d";
  20766. }
  20767. },
  20768. { //a=rtcp-fb:98 trr-int 100
  20769. push: 'rtcpFbTrrInt',
  20770. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20771. names: ['payload', 'value'],
  20772. format: "rtcp-fb:%d trr-int %d"
  20773. },
  20774. { //a=rtcp-fb:98 nack rpsi
  20775. push: 'rtcpFb',
  20776. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20777. names: ['payload', 'type', 'subtype'],
  20778. format: function (o) {
  20779. return (o.subtype != null) ?
  20780. "rtcp-fb:%s %s %s":
  20781. "rtcp-fb:%s %s";
  20782. }
  20783. },
  20784. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20785. //a=extmap:1/recvonly URI-gps-string
  20786. push: 'ext',
  20787. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  20788. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  20789. format: function (o) {
  20790. return (o.config != null) ?
  20791. "extmap:%s %s %s":
  20792. "extmap:%s %s";
  20793. }
  20794. },
  20795. {
  20796. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  20797. push: 'crypto',
  20798. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  20799. names: ['id', 'suite', 'config', 'sessionConfig'],
  20800. format: function (o) {
  20801. return (o.sessionConfig != null) ?
  20802. "crypto:%d %s %s %s":
  20803. "crypto:%d %s %s";
  20804. }
  20805. },
  20806. { //a=setup:actpass
  20807. name: 'setup',
  20808. reg: /^setup:(\w*)/,
  20809. format: "setup:%s"
  20810. },
  20811. { //a=mid:1
  20812. name: 'mid',
  20813. reg: /^mid:([^\s]*)/,
  20814. format: "mid:%s"
  20815. },
  20816. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  20817. name: 'msid',
  20818. reg: /^msid:(.*)/,
  20819. format: "msid:%s"
  20820. },
  20821. { //a=ptime:20
  20822. name: 'ptime',
  20823. reg: /^ptime:(\d*)/,
  20824. format: "ptime:%d"
  20825. },
  20826. { //a=maxptime:60
  20827. name: 'maxptime',
  20828. reg: /^maxptime:(\d*)/,
  20829. format: "maxptime:%d"
  20830. },
  20831. { //a=sendrecv
  20832. name: 'direction',
  20833. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20834. },
  20835. { //a=ice-lite
  20836. name: 'icelite',
  20837. reg: /^(ice-lite)/
  20838. },
  20839. { //a=ice-ufrag:F7gI
  20840. name: 'iceUfrag',
  20841. reg: /^ice-ufrag:(\S*)/,
  20842. format: "ice-ufrag:%s"
  20843. },
  20844. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20845. name: 'icePwd',
  20846. reg: /^ice-pwd:(\S*)/,
  20847. format: "ice-pwd:%s"
  20848. },
  20849. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  20850. name: 'fingerprint',
  20851. reg: /^fingerprint:(\S*) (\S*)/,
  20852. names: ['type', 'hash'],
  20853. format: "fingerprint:%s %s"
  20854. },
  20855. {
  20856. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  20857. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  20858. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  20859. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  20860. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  20861. push:'candidates',
  20862. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  20863. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  20864. format: function (o) {
  20865. var str = "candidate:%s %d %s %d %s %d typ %s";
  20866. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  20867. // NB: candidate has three optional chunks, so %void middles one if it's missing
  20868. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  20869. if (o.generation != null) {
  20870. str += " generation %d";
  20871. }
  20872. return str;
  20873. }
  20874. },
  20875. { //a=end-of-candidates (keep after the candidates line for readability)
  20876. name: 'endOfCandidates',
  20877. reg: /^(end-of-candidates)/
  20878. },
  20879. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  20880. name: 'remoteCandidates',
  20881. reg: /^remote-candidates:(.*)/,
  20882. format: "remote-candidates:%s"
  20883. },
  20884. { //a=ice-options:google-ice
  20885. name: 'iceOptions',
  20886. reg: /^ice-options:(\S*)/,
  20887. format: "ice-options:%s"
  20888. },
  20889. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20890. push: "ssrcs",
  20891. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20892. names: ['id', 'attribute', 'value'],
  20893. format: "ssrc:%d %s:%s"
  20894. },
  20895. { //a=ssrc-group:FEC 1 2
  20896. push: "ssrcGroups",
  20897. reg: /^ssrc-group:(\w*) (.*)/,
  20898. names: ['semantics', 'ssrcs'],
  20899. format: "ssrc-group:%s %s"
  20900. },
  20901. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20902. name: "msidSemantic",
  20903. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20904. names: ['semantic', 'token'],
  20905. format: "msid-semantic: %s %s" // space after ":" is not accidental
  20906. },
  20907. { //a=group:BUNDLE audio video
  20908. push: 'groups',
  20909. reg: /^group:(\w*) (.*)/,
  20910. names: ['type', 'mids'],
  20911. format: "group:%s %s"
  20912. },
  20913. { //a=rtcp-mux
  20914. name: 'rtcpMux',
  20915. reg: /^(rtcp-mux)/
  20916. },
  20917. { //a=rtcp-rsize
  20918. name: 'rtcpRsize',
  20919. reg: /^(rtcp-rsize)/
  20920. },
  20921. { // any a= that we don't understand is kepts verbatim on media.invalid
  20922. push: 'invalid',
  20923. names: ["value"]
  20924. }
  20925. ]
  20926. };
  20927. // set sensible defaults to avoid polluting the grammar with boring details
  20928. Object.keys(grammar).forEach(function (key) {
  20929. var objs = grammar[key];
  20930. objs.forEach(function (obj) {
  20931. if (!obj.reg) {
  20932. obj.reg = /(.*)/;
  20933. }
  20934. if (!obj.format) {
  20935. obj.format = "%s";
  20936. }
  20937. });
  20938. });
  20939. },{}],72:[function(require,module,exports){
  20940. var parser = require('./parser');
  20941. var writer = require('./writer');
  20942. exports.write = writer;
  20943. exports.parse = parser.parse;
  20944. exports.parseFmtpConfig = parser.parseFmtpConfig;
  20945. exports.parsePayloads = parser.parsePayloads;
  20946. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  20947. },{"./parser":73,"./writer":74}],73:[function(require,module,exports){
  20948. var toIntIfInt = function (v) {
  20949. return String(Number(v)) === v ? Number(v) : v;
  20950. };
  20951. var attachProperties = function (match, location, names, rawName) {
  20952. if (rawName && !names) {
  20953. location[rawName] = toIntIfInt(match[1]);
  20954. }
  20955. else {
  20956. for (var i = 0; i < names.length; i += 1) {
  20957. if (match[i+1] != null) {
  20958. location[names[i]] = toIntIfInt(match[i+1]);
  20959. }
  20960. }
  20961. }
  20962. };
  20963. var parseReg = function (obj, location, content) {
  20964. var needsBlank = obj.name && obj.names;
  20965. if (obj.push && !location[obj.push]) {
  20966. location[obj.push] = [];
  20967. }
  20968. else if (needsBlank && !location[obj.name]) {
  20969. location[obj.name] = {};
  20970. }
  20971. var keyLocation = obj.push ?
  20972. {} : // blank object that will be pushed
  20973. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  20974. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  20975. if (obj.push) {
  20976. location[obj.push].push(keyLocation);
  20977. }
  20978. };
  20979. var grammar = require('./grammar');
  20980. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  20981. exports.parse = function (sdp) {
  20982. var session = {}
  20983. , media = []
  20984. , location = session; // points at where properties go under (one of the above)
  20985. // parse lines we understand
  20986. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  20987. var type = l[0];
  20988. var content = l.slice(2);
  20989. if (type === 'm') {
  20990. media.push({rtp: [], fmtp: []});
  20991. location = media[media.length-1]; // point at latest media line
  20992. }
  20993. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  20994. var obj = grammar[type][j];
  20995. if (obj.reg.test(content)) {
  20996. return parseReg(obj, location, content);
  20997. }
  20998. }
  20999. });
  21000. session.media = media; // link it up
  21001. return session;
  21002. };
  21003. var fmtpReducer = function (acc, expr) {
  21004. var s = expr.split('=');
  21005. if (s.length === 2) {
  21006. acc[s[0]] = toIntIfInt(s[1]);
  21007. }
  21008. return acc;
  21009. };
  21010. exports.parseFmtpConfig = function (str) {
  21011. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  21012. };
  21013. exports.parsePayloads = function (str) {
  21014. return str.split(' ').map(Number);
  21015. };
  21016. exports.parseRemoteCandidates = function (str) {
  21017. var candidates = [];
  21018. var parts = str.split(' ').map(toIntIfInt);
  21019. for (var i = 0; i < parts.length; i += 3) {
  21020. candidates.push({
  21021. component: parts[i],
  21022. ip: parts[i + 1],
  21023. port: parts[i + 2]
  21024. });
  21025. }
  21026. return candidates;
  21027. };
  21028. },{"./grammar":71}],74:[function(require,module,exports){
  21029. var grammar = require('./grammar');
  21030. // customized util.format - discards excess arguments and can void middle ones
  21031. var formatRegExp = /%[sdv%]/g;
  21032. var format = function (formatStr) {
  21033. var i = 1;
  21034. var args = arguments;
  21035. var len = args.length;
  21036. return formatStr.replace(formatRegExp, function (x) {
  21037. if (i >= len) {
  21038. return x; // missing argument
  21039. }
  21040. var arg = args[i];
  21041. i += 1;
  21042. switch (x) {
  21043. case '%%':
  21044. return '%';
  21045. case '%s':
  21046. return String(arg);
  21047. case '%d':
  21048. return Number(arg);
  21049. case '%v':
  21050. return '';
  21051. }
  21052. });
  21053. // NB: we discard excess arguments - they are typically undefined from makeLine
  21054. };
  21055. var makeLine = function (type, obj, location) {
  21056. var str = obj.format instanceof Function ?
  21057. (obj.format(obj.push ? location : location[obj.name])) :
  21058. obj.format;
  21059. var args = [type + '=' + str];
  21060. if (obj.names) {
  21061. for (var i = 0; i < obj.names.length; i += 1) {
  21062. var n = obj.names[i];
  21063. if (obj.name) {
  21064. args.push(location[obj.name][n]);
  21065. }
  21066. else { // for mLine and push attributes
  21067. args.push(location[obj.names[i]]);
  21068. }
  21069. }
  21070. }
  21071. else {
  21072. args.push(location[obj.name]);
  21073. }
  21074. return format.apply(null, args);
  21075. };
  21076. // RFC specified order
  21077. // TODO: extend this with all the rest
  21078. var defaultOuterOrder = [
  21079. 'v', 'o', 's', 'i',
  21080. 'u', 'e', 'p', 'c',
  21081. 'b', 't', 'r', 'z', 'a'
  21082. ];
  21083. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  21084. module.exports = function (session, opts) {
  21085. opts = opts || {};
  21086. // ensure certain properties exist
  21087. if (session.version == null) {
  21088. session.version = 0; // "v=0" must be there (only defined version atm)
  21089. }
  21090. if (session.name == null) {
  21091. session.name = " "; // "s= " must be there if no meaningful name set
  21092. }
  21093. session.media.forEach(function (mLine) {
  21094. if (mLine.payloads == null) {
  21095. mLine.payloads = "";
  21096. }
  21097. });
  21098. var outerOrder = opts.outerOrder || defaultOuterOrder;
  21099. var innerOrder = opts.innerOrder || defaultInnerOrder;
  21100. var sdp = [];
  21101. // loop through outerOrder for matching properties on session
  21102. outerOrder.forEach(function (type) {
  21103. grammar[type].forEach(function (obj) {
  21104. if (obj.name in session && session[obj.name] != null) {
  21105. sdp.push(makeLine(type, obj, session));
  21106. }
  21107. else if (obj.push in session && session[obj.push] != null) {
  21108. session[obj.push].forEach(function (el) {
  21109. sdp.push(makeLine(type, obj, el));
  21110. });
  21111. }
  21112. });
  21113. });
  21114. // then for each media line, follow the innerOrder
  21115. session.media.forEach(function (mLine) {
  21116. sdp.push(makeLine('m', grammar.m[0], mLine));
  21117. innerOrder.forEach(function (type) {
  21118. grammar[type].forEach(function (obj) {
  21119. if (obj.name in mLine && mLine[obj.name] != null) {
  21120. sdp.push(makeLine(type, obj, mLine));
  21121. }
  21122. else if (obj.push in mLine && mLine[obj.push] != null) {
  21123. mLine[obj.push].forEach(function (el) {
  21124. sdp.push(makeLine(type, obj, el));
  21125. });
  21126. }
  21127. });
  21128. });
  21129. });
  21130. return sdp.join('\r\n') + '\r\n';
  21131. };
  21132. },{"./grammar":71}],75:[function(require,module,exports){
  21133. /* Copyright @ 2015 Atlassian Pty Ltd
  21134. *
  21135. * Licensed under the Apache License, Version 2.0 (the "License");
  21136. * you may not use this file except in compliance with the License.
  21137. * You may obtain a copy of the License at
  21138. *
  21139. * http://www.apache.org/licenses/LICENSE-2.0
  21140. *
  21141. * Unless required by applicable law or agreed to in writing, software
  21142. * distributed under the License is distributed on an "AS IS" BASIS,
  21143. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21144. * See the License for the specific language governing permissions and
  21145. * limitations under the License.
  21146. */
  21147. var transform = require('sdp-transform');
  21148. var transformUtils = require('./transform-utils');
  21149. var parseSsrcs = transformUtils.parseSsrcs;
  21150. var writeSsrcs = transformUtils.writeSsrcs;
  21151. //region Constants
  21152. var DEFAULT_NUM_OF_LAYERS = 3;
  21153. //endregion
  21154. //region Ctor
  21155. function Simulcast(options) {
  21156. this.options = options ? options : {};
  21157. if (!this.options.numOfLayers) {
  21158. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  21159. }
  21160. this.layers = [];
  21161. }
  21162. //endregion
  21163. //region Stateless private utility functions
  21164. /**
  21165. * Returns a random integer between min (included) and max (excluded)
  21166. * Using Math.round() gives a non-uniform distribution!
  21167. * @returns {number}
  21168. */
  21169. function generateSSRC() {
  21170. var min = 0, max = 0xffffffff;
  21171. return Math.floor(Math.random() * (max - min)) + min;
  21172. };
  21173. function processVideo(session, action) {
  21174. if (session == null || !Array.isArray(session.media)) {
  21175. return;
  21176. }
  21177. session.media.forEach(function (mLine) {
  21178. if (mLine.type === 'video') {
  21179. action(mLine);
  21180. }
  21181. });
  21182. }
  21183. function validateDescription(desc)
  21184. {
  21185. return desc && desc != null
  21186. && desc.type && desc.type != ''
  21187. && desc.sdp && desc.sdp != '';
  21188. }
  21189. function explodeRemoteSimulcast(mLine) {
  21190. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21191. return;
  21192. }
  21193. var sources = parseSsrcs(mLine);
  21194. var order = [];
  21195. // Find the SIM group and explode its sources.
  21196. var j = mLine.ssrcGroups.length;
  21197. while (j--) {
  21198. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  21199. continue;
  21200. }
  21201. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  21202. for (var i = 0; i < simulcastSsrcs.length; i++) {
  21203. var ssrc = simulcastSsrcs[i];
  21204. order.push(ssrc);
  21205. var parts = sources[ssrc].msid.split(' ');
  21206. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  21207. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  21208. // Remove all the groups that this SSRC participates in.
  21209. mLine.ssrcGroups.forEach(function (relatedGroup) {
  21210. if (relatedGroup.semantics === 'SIM') {
  21211. return;
  21212. }
  21213. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  21214. if (relatedSsrcs.indexOf(ssrc) === -1) {
  21215. return;
  21216. }
  21217. // Nuke all the related SSRCs.
  21218. relatedSsrcs.forEach(function (relatedSSRC) {
  21219. sources[relatedSSRC].msid = sources[ssrc].msid;
  21220. sources[relatedSSRC].cname = sources[ssrc].cname;
  21221. if (relatedSSRC !== ssrc) {
  21222. order.push(relatedSSRC);
  21223. }
  21224. });
  21225. // Schedule the related group for nuking.
  21226. })
  21227. }
  21228. mLine.ssrcs = writeSsrcs(sources, order);
  21229. mLine.ssrcGroups.splice(j, 1);
  21230. };
  21231. }
  21232. function implodeRemoteSimulcast(mLine) {
  21233. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21234. console.info('Halt: There are no SSRC groups in the remote ' +
  21235. 'description.');
  21236. return;
  21237. }
  21238. var sources = parseSsrcs(mLine);
  21239. // Find the SIM group and nuke it.
  21240. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  21241. if (simulcastGroup.semantics !== 'SIM') {
  21242. return;
  21243. }
  21244. console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
  21245. // Schedule the SIM group for nuking.
  21246. simulcastGroup.nuke = true;
  21247. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  21248. // Nuke all the higher layer SSRCs.
  21249. for (var i = 1; i < simulcastSsrcs.length; i++) {
  21250. var ssrc = simulcastSsrcs[i];
  21251. delete sources[ssrc];
  21252. // Remove all the groups that this SSRC participates in.
  21253. mLine.ssrcGroups.forEach(function (relatedGroup) {
  21254. if (relatedGroup.semantics === 'SIM') {
  21255. return;
  21256. }
  21257. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  21258. if (relatedSsrcs.indexOf(ssrc) === -1) {
  21259. return;
  21260. }
  21261. // Nuke all the related SSRCs.
  21262. relatedSsrcs.forEach(function (relatedSSRC) {
  21263. delete sources[relatedSSRC];
  21264. });
  21265. // Schedule the related group for nuking.
  21266. relatedGroup.nuke = true;
  21267. })
  21268. }
  21269. return;
  21270. });
  21271. mLine.ssrcs = writeSsrcs(sources);
  21272. // Nuke all the scheduled groups.
  21273. var i = mLine.ssrcGroups.length;
  21274. while (i--) {
  21275. if (mLine.ssrcGroups[i].nuke) {
  21276. mLine.ssrcGroups.splice(i, 1);
  21277. }
  21278. }
  21279. }
  21280. function removeGoogConference(mLine) {
  21281. if (!mLine || !Array.isArray(mLine.invalid)) {
  21282. return;
  21283. }
  21284. var i = mLine.invalid.length;
  21285. while (i--) {
  21286. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  21287. mLine.invalid.splice(i, 1);
  21288. }
  21289. }
  21290. }
  21291. function assertGoogConference(mLine) {
  21292. if (!mLine) {
  21293. return;
  21294. }
  21295. if (!Array.isArray(mLine.invalid)) {
  21296. mLine.invalid = [];
  21297. }
  21298. if (!mLine.invalid.some(
  21299. function (i) { return i.value === 'x-google-flag:conference' })) {
  21300. mLine.invalid.push({'value': 'x-google-flag:conference'});
  21301. }
  21302. }
  21303. //endregion
  21304. //region "Private" functions
  21305. /**
  21306. *
  21307. * @param mLine
  21308. * @private
  21309. */
  21310. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  21311. if (!mLine || mLine.type !== 'video') {
  21312. return;
  21313. }
  21314. var sources = parseSsrcs(mLine);
  21315. if (Object.keys(sources).length === 0) {
  21316. // no sources, disable simulcast.
  21317. if (this.layers.length !== 0) {
  21318. this.layers = [];
  21319. }
  21320. return;
  21321. }
  21322. // find the base layer (we'll reuse its msid and cname).
  21323. var baseLayerSSRC = Object.keys(sources)[0];
  21324. var baseLayer = sources[baseLayerSSRC];
  21325. // todo(gp) handle screen sharing.
  21326. // check if base CNAME has changed and reinitialise layers.
  21327. if (this.layers.length > 0
  21328. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  21329. this.layers = [];
  21330. }
  21331. // (re)initialise layers
  21332. if (this.layers.length < 1) {
  21333. // first push the base layer.
  21334. this.layers.push({
  21335. ssrc: baseLayerSSRC,
  21336. msid: baseLayer.msid,
  21337. cname: baseLayer.cname
  21338. });
  21339. var rtx = false; // RFC 4588
  21340. if (Array.isArray(mLine.rtp)) {
  21341. rtx = mLine.rtp.some(
  21342. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  21343. }
  21344. if (rtx) {
  21345. this.layers[0].rtx = generateSSRC();
  21346. }
  21347. // now push additional layers.
  21348. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  21349. var layer = { ssrc: generateSSRC() };
  21350. if (rtx) {
  21351. layer.rtx = generateSSRC();
  21352. }
  21353. this.layers.push(layer);
  21354. }
  21355. }
  21356. };
  21357. /**
  21358. *
  21359. * @param mLine
  21360. * @private
  21361. */
  21362. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  21363. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  21364. var sources = {};
  21365. var msid = this.layers[0].msid;
  21366. var cname = this.layers[0].cname;
  21367. var simulcastSsrcs = [];
  21368. var ssrcGroups = [];
  21369. for (var i = 0; i < this.layers.length; i++) {
  21370. var layer = this.layers[i];
  21371. sources[layer.ssrc] = { msid: msid, cname: cname };
  21372. simulcastSsrcs.push(layer.ssrc);
  21373. if (layer.rtx) {
  21374. sources[layer.rtx] = {
  21375. msid: msid,
  21376. cname: cname
  21377. }
  21378. ssrcGroups.push({
  21379. semantics: 'FID',
  21380. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  21381. });
  21382. }
  21383. }
  21384. ssrcGroups.push({
  21385. semantics: 'SIM',
  21386. ssrcs: simulcastSsrcs.join(' ')
  21387. });
  21388. mLine.ssrcGroups = ssrcGroups;
  21389. mLine.ssrcs = writeSsrcs(sources);
  21390. }
  21391. }
  21392. //endregion
  21393. //region "Public" functions
  21394. Simulcast.prototype.isSupported = function () {
  21395. return window.chrome;
  21396. // TODO this needs improvements. For example I doubt that Chrome in Android
  21397. // has simulcast support. Also, only recent versions of Chromium have native
  21398. // simulcast support.
  21399. }
  21400. /**
  21401. *
  21402. * @param desc
  21403. * @returns {RTCSessionDescription}
  21404. */
  21405. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  21406. if (!validateDescription(desc)) {
  21407. return desc;
  21408. }
  21409. var session = transform.parse(desc.sdp);
  21410. var self = this;
  21411. processVideo(session, function (mLine) {
  21412. // Handle simulcast reception.
  21413. if (self.options.explodeRemoteSimulcast) {
  21414. explodeRemoteSimulcast(mLine);
  21415. } else {
  21416. implodeRemoteSimulcast(mLine);
  21417. }
  21418. // If native simulcast is enabled, we must append the x-goog-conference
  21419. // attribute to the SDP.
  21420. if (self.layers.length < 1) {
  21421. removeGoogConference(mLine);
  21422. } else {
  21423. assertGoogConference(mLine);
  21424. }
  21425. });
  21426. return new RTCSessionDescription({
  21427. type: desc.type,
  21428. sdp: transform.write(session)
  21429. });
  21430. };
  21431. /**
  21432. *
  21433. * @param desc
  21434. * @returns {RTCSessionDescription}
  21435. */
  21436. Simulcast.prototype.mungeLocalDescription = function (desc) {
  21437. if (!validateDescription(desc) || !this.isSupported()) {
  21438. return desc;
  21439. }
  21440. var session = transform.parse(desc.sdp);
  21441. var self = this;
  21442. processVideo(session, function (mLine) {
  21443. if (mLine.direction == 'recvonly' || mLine.direction == 'inactive')
  21444. {
  21445. return;
  21446. }
  21447. // Initialize native simulcast layers, if not already done.
  21448. self._maybeInitializeLayers(mLine);
  21449. // Update the SDP with the simulcast layers.
  21450. self._restoreSimulcastView(mLine);
  21451. });
  21452. return new RTCSessionDescription({
  21453. type: desc.type,
  21454. sdp: transform.write(session)
  21455. });
  21456. };
  21457. //endregion
  21458. module.exports = Simulcast;
  21459. },{"./transform-utils":76,"sdp-transform":78}],76:[function(require,module,exports){
  21460. /* Copyright @ 2015 Atlassian Pty Ltd
  21461. *
  21462. * Licensed under the Apache License, Version 2.0 (the "License");
  21463. * you may not use this file except in compliance with the License.
  21464. * You may obtain a copy of the License at
  21465. *
  21466. * http://www.apache.org/licenses/LICENSE-2.0
  21467. *
  21468. * Unless required by applicable law or agreed to in writing, software
  21469. * distributed under the License is distributed on an "AS IS" BASIS,
  21470. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21471. * See the License for the specific language governing permissions and
  21472. * limitations under the License.
  21473. */
  21474. exports.writeSsrcs = function(sources, order) {
  21475. var ssrcs = [];
  21476. // expand sources to ssrcs
  21477. if (typeof sources !== 'undefined' &&
  21478. Object.keys(sources).length !== 0) {
  21479. if (Array.isArray(order)) {
  21480. for (var i = 0; i < order.length; i++) {
  21481. var ssrc = order[i];
  21482. var source = sources[ssrc];
  21483. Object.keys(source).forEach(function (attribute) {
  21484. ssrcs.push({
  21485. id: ssrc,
  21486. attribute: attribute,
  21487. value: source[attribute]
  21488. });
  21489. });
  21490. }
  21491. } else {
  21492. Object.keys(sources).forEach(function (ssrc) {
  21493. var source = sources[ssrc];
  21494. Object.keys(source).forEach(function (attribute) {
  21495. ssrcs.push({
  21496. id: ssrc,
  21497. attribute: attribute,
  21498. value: source[attribute]
  21499. });
  21500. });
  21501. });
  21502. }
  21503. }
  21504. return ssrcs;
  21505. };
  21506. exports.parseSsrcs = function (mLine) {
  21507. var sources = {};
  21508. // group sources attributes by ssrc.
  21509. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  21510. mLine.ssrcs.forEach(function (ssrc) {
  21511. if (!sources[ssrc.id])
  21512. sources[ssrc.id] = {};
  21513. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  21514. });
  21515. }
  21516. return sources;
  21517. };
  21518. },{}],77:[function(require,module,exports){
  21519. arguments[4][71][0].apply(exports,arguments)
  21520. },{"dup":71}],78:[function(require,module,exports){
  21521. arguments[4][72][0].apply(exports,arguments)
  21522. },{"./parser":79,"./writer":80,"dup":72}],79:[function(require,module,exports){
  21523. arguments[4][73][0].apply(exports,arguments)
  21524. },{"./grammar":77,"dup":73}],80:[function(require,module,exports){
  21525. arguments[4][74][0].apply(exports,arguments)
  21526. },{"./grammar":77,"dup":74}],81:[function(require,module,exports){
  21527. module.exports = require('./lib/');
  21528. },{"./lib/":82}],82:[function(require,module,exports){
  21529. /**
  21530. * Module dependencies.
  21531. */
  21532. var url = require('./url');
  21533. var parser = require('socket.io-parser');
  21534. var Manager = require('./manager');
  21535. var debug = require('debug')('socket.io-client');
  21536. /**
  21537. * Module exports.
  21538. */
  21539. module.exports = exports = lookup;
  21540. /**
  21541. * Managers cache.
  21542. */
  21543. var cache = exports.managers = {};
  21544. /**
  21545. * Looks up an existing `Manager` for multiplexing.
  21546. * If the user summons:
  21547. *
  21548. * `io('http://localhost/a');`
  21549. * `io('http://localhost/b');`
  21550. *
  21551. * We reuse the existing instance based on same scheme/port/host,
  21552. * and we initialize sockets for each namespace.
  21553. *
  21554. * @api public
  21555. */
  21556. function lookup(uri, opts) {
  21557. if (typeof uri == 'object') {
  21558. opts = uri;
  21559. uri = undefined;
  21560. }
  21561. opts = opts || {};
  21562. var parsed = url(uri);
  21563. var source = parsed.source;
  21564. var id = parsed.id;
  21565. var io;
  21566. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  21567. debug('ignoring socket cache for %s', source);
  21568. io = Manager(source, opts);
  21569. } else {
  21570. if (!cache[id]) {
  21571. debug('new io instance for %s', source);
  21572. cache[id] = Manager(source, opts);
  21573. }
  21574. io = cache[id];
  21575. }
  21576. return io.socket(parsed.path);
  21577. }
  21578. /**
  21579. * Protocol version.
  21580. *
  21581. * @api public
  21582. */
  21583. exports.protocol = parser.protocol;
  21584. /**
  21585. * `connect`.
  21586. *
  21587. * @param {String} uri
  21588. * @api public
  21589. */
  21590. exports.connect = lookup;
  21591. /**
  21592. * Expose constructors for standalone build.
  21593. *
  21594. * @api public
  21595. */
  21596. exports.Manager = require('./manager');
  21597. exports.Socket = require('./socket');
  21598. },{"./manager":83,"./socket":85,"./url":86,"debug":90,"socket.io-parser":126}],83:[function(require,module,exports){
  21599. /**
  21600. * Module dependencies.
  21601. */
  21602. var url = require('./url');
  21603. var eio = require('engine.io-client');
  21604. var Socket = require('./socket');
  21605. var Emitter = require('component-emitter');
  21606. var parser = require('socket.io-parser');
  21607. var on = require('./on');
  21608. var bind = require('component-bind');
  21609. var object = require('object-component');
  21610. var debug = require('debug')('socket.io-client:manager');
  21611. var indexOf = require('indexof');
  21612. var Backoff = require('backo2');
  21613. /**
  21614. * Module exports
  21615. */
  21616. module.exports = Manager;
  21617. /**
  21618. * `Manager` constructor.
  21619. *
  21620. * @param {String} engine instance or engine uri/opts
  21621. * @param {Object} options
  21622. * @api public
  21623. */
  21624. function Manager(uri, opts){
  21625. if (!(this instanceof Manager)) return new Manager(uri, opts);
  21626. if (uri && ('object' == typeof uri)) {
  21627. opts = uri;
  21628. uri = undefined;
  21629. }
  21630. opts = opts || {};
  21631. opts.path = opts.path || '/socket.io';
  21632. this.nsps = {};
  21633. this.subs = [];
  21634. this.opts = opts;
  21635. this.reconnection(opts.reconnection !== false);
  21636. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  21637. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  21638. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  21639. this.randomizationFactor(opts.randomizationFactor || 0.5);
  21640. this.backoff = new Backoff({
  21641. min: this.reconnectionDelay(),
  21642. max: this.reconnectionDelayMax(),
  21643. jitter: this.randomizationFactor()
  21644. });
  21645. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  21646. this.readyState = 'closed';
  21647. this.uri = uri;
  21648. this.connected = [];
  21649. this.encoding = false;
  21650. this.packetBuffer = [];
  21651. this.encoder = new parser.Encoder();
  21652. this.decoder = new parser.Decoder();
  21653. this.autoConnect = opts.autoConnect !== false;
  21654. if (this.autoConnect) this.open();
  21655. }
  21656. /**
  21657. * Propagate given event to sockets and emit on `this`
  21658. *
  21659. * @api private
  21660. */
  21661. Manager.prototype.emitAll = function() {
  21662. this.emit.apply(this, arguments);
  21663. for (var nsp in this.nsps) {
  21664. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  21665. }
  21666. };
  21667. /**
  21668. * Update `socket.id` of all sockets
  21669. *
  21670. * @api private
  21671. */
  21672. Manager.prototype.updateSocketIds = function(){
  21673. for (var nsp in this.nsps) {
  21674. this.nsps[nsp].id = this.engine.id;
  21675. }
  21676. };
  21677. /**
  21678. * Mix in `Emitter`.
  21679. */
  21680. Emitter(Manager.prototype);
  21681. /**
  21682. * Sets the `reconnection` config.
  21683. *
  21684. * @param {Boolean} true/false if it should automatically reconnect
  21685. * @return {Manager} self or value
  21686. * @api public
  21687. */
  21688. Manager.prototype.reconnection = function(v){
  21689. if (!arguments.length) return this._reconnection;
  21690. this._reconnection = !!v;
  21691. return this;
  21692. };
  21693. /**
  21694. * Sets the reconnection attempts config.
  21695. *
  21696. * @param {Number} max reconnection attempts before giving up
  21697. * @return {Manager} self or value
  21698. * @api public
  21699. */
  21700. Manager.prototype.reconnectionAttempts = function(v){
  21701. if (!arguments.length) return this._reconnectionAttempts;
  21702. this._reconnectionAttempts = v;
  21703. return this;
  21704. };
  21705. /**
  21706. * Sets the delay between reconnections.
  21707. *
  21708. * @param {Number} delay
  21709. * @return {Manager} self or value
  21710. * @api public
  21711. */
  21712. Manager.prototype.reconnectionDelay = function(v){
  21713. if (!arguments.length) return this._reconnectionDelay;
  21714. this._reconnectionDelay = v;
  21715. this.backoff && this.backoff.setMin(v);
  21716. return this;
  21717. };
  21718. Manager.prototype.randomizationFactor = function(v){
  21719. if (!arguments.length) return this._randomizationFactor;
  21720. this._randomizationFactor = v;
  21721. this.backoff && this.backoff.setJitter(v);
  21722. return this;
  21723. };
  21724. /**
  21725. * Sets the maximum delay between reconnections.
  21726. *
  21727. * @param {Number} delay
  21728. * @return {Manager} self or value
  21729. * @api public
  21730. */
  21731. Manager.prototype.reconnectionDelayMax = function(v){
  21732. if (!arguments.length) return this._reconnectionDelayMax;
  21733. this._reconnectionDelayMax = v;
  21734. this.backoff && this.backoff.setMax(v);
  21735. return this;
  21736. };
  21737. /**
  21738. * Sets the connection timeout. `false` to disable
  21739. *
  21740. * @return {Manager} self or value
  21741. * @api public
  21742. */
  21743. Manager.prototype.timeout = function(v){
  21744. if (!arguments.length) return this._timeout;
  21745. this._timeout = v;
  21746. return this;
  21747. };
  21748. /**
  21749. * Starts trying to reconnect if reconnection is enabled and we have not
  21750. * started reconnecting yet
  21751. *
  21752. * @api private
  21753. */
  21754. Manager.prototype.maybeReconnectOnOpen = function() {
  21755. // Only try to reconnect if it's the first time we're connecting
  21756. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  21757. // keeps reconnection from firing twice for the same reconnection loop
  21758. this.reconnect();
  21759. }
  21760. };
  21761. /**
  21762. * Sets the current transport `socket`.
  21763. *
  21764. * @param {Function} optional, callback
  21765. * @return {Manager} self
  21766. * @api public
  21767. */
  21768. Manager.prototype.open =
  21769. Manager.prototype.connect = function(fn){
  21770. debug('readyState %s', this.readyState);
  21771. if (~this.readyState.indexOf('open')) return this;
  21772. debug('opening %s', this.uri);
  21773. this.engine = eio(this.uri, this.opts);
  21774. var socket = this.engine;
  21775. var self = this;
  21776. this.readyState = 'opening';
  21777. this.skipReconnect = false;
  21778. // emit `open`
  21779. var openSub = on(socket, 'open', function() {
  21780. self.onopen();
  21781. fn && fn();
  21782. });
  21783. // emit `connect_error`
  21784. var errorSub = on(socket, 'error', function(data){
  21785. debug('connect_error');
  21786. self.cleanup();
  21787. self.readyState = 'closed';
  21788. self.emitAll('connect_error', data);
  21789. if (fn) {
  21790. var err = new Error('Connection error');
  21791. err.data = data;
  21792. fn(err);
  21793. } else {
  21794. // Only do this if there is no fn to handle the error
  21795. self.maybeReconnectOnOpen();
  21796. }
  21797. });
  21798. // emit `connect_timeout`
  21799. if (false !== this._timeout) {
  21800. var timeout = this._timeout;
  21801. debug('connect attempt will timeout after %d', timeout);
  21802. // set timer
  21803. var timer = setTimeout(function(){
  21804. debug('connect attempt timed out after %d', timeout);
  21805. openSub.destroy();
  21806. socket.close();
  21807. socket.emit('error', 'timeout');
  21808. self.emitAll('connect_timeout', timeout);
  21809. }, timeout);
  21810. this.subs.push({
  21811. destroy: function(){
  21812. clearTimeout(timer);
  21813. }
  21814. });
  21815. }
  21816. this.subs.push(openSub);
  21817. this.subs.push(errorSub);
  21818. return this;
  21819. };
  21820. /**
  21821. * Called upon transport open.
  21822. *
  21823. * @api private
  21824. */
  21825. Manager.prototype.onopen = function(){
  21826. debug('open');
  21827. // clear old subs
  21828. this.cleanup();
  21829. // mark as open
  21830. this.readyState = 'open';
  21831. this.emit('open');
  21832. // add new subs
  21833. var socket = this.engine;
  21834. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  21835. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  21836. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  21837. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  21838. };
  21839. /**
  21840. * Called with data.
  21841. *
  21842. * @api private
  21843. */
  21844. Manager.prototype.ondata = function(data){
  21845. this.decoder.add(data);
  21846. };
  21847. /**
  21848. * Called when parser fully decodes a packet.
  21849. *
  21850. * @api private
  21851. */
  21852. Manager.prototype.ondecoded = function(packet) {
  21853. this.emit('packet', packet);
  21854. };
  21855. /**
  21856. * Called upon socket error.
  21857. *
  21858. * @api private
  21859. */
  21860. Manager.prototype.onerror = function(err){
  21861. debug('error', err);
  21862. this.emitAll('error', err);
  21863. };
  21864. /**
  21865. * Creates a new socket for the given `nsp`.
  21866. *
  21867. * @return {Socket}
  21868. * @api public
  21869. */
  21870. Manager.prototype.socket = function(nsp){
  21871. var socket = this.nsps[nsp];
  21872. if (!socket) {
  21873. socket = new Socket(this, nsp);
  21874. this.nsps[nsp] = socket;
  21875. var self = this;
  21876. socket.on('connect', function(){
  21877. socket.id = self.engine.id;
  21878. if (!~indexOf(self.connected, socket)) {
  21879. self.connected.push(socket);
  21880. }
  21881. });
  21882. }
  21883. return socket;
  21884. };
  21885. /**
  21886. * Called upon a socket close.
  21887. *
  21888. * @param {Socket} socket
  21889. */
  21890. Manager.prototype.destroy = function(socket){
  21891. var index = indexOf(this.connected, socket);
  21892. if (~index) this.connected.splice(index, 1);
  21893. if (this.connected.length) return;
  21894. this.close();
  21895. };
  21896. /**
  21897. * Writes a packet.
  21898. *
  21899. * @param {Object} packet
  21900. * @api private
  21901. */
  21902. Manager.prototype.packet = function(packet){
  21903. debug('writing packet %j', packet);
  21904. var self = this;
  21905. if (!self.encoding) {
  21906. // encode, then write to engine with result
  21907. self.encoding = true;
  21908. this.encoder.encode(packet, function(encodedPackets) {
  21909. for (var i = 0; i < encodedPackets.length; i++) {
  21910. self.engine.write(encodedPackets[i]);
  21911. }
  21912. self.encoding = false;
  21913. self.processPacketQueue();
  21914. });
  21915. } else { // add packet to the queue
  21916. self.packetBuffer.push(packet);
  21917. }
  21918. };
  21919. /**
  21920. * If packet buffer is non-empty, begins encoding the
  21921. * next packet in line.
  21922. *
  21923. * @api private
  21924. */
  21925. Manager.prototype.processPacketQueue = function() {
  21926. if (this.packetBuffer.length > 0 && !this.encoding) {
  21927. var pack = this.packetBuffer.shift();
  21928. this.packet(pack);
  21929. }
  21930. };
  21931. /**
  21932. * Clean up transport subscriptions and packet buffer.
  21933. *
  21934. * @api private
  21935. */
  21936. Manager.prototype.cleanup = function(){
  21937. var sub;
  21938. while (sub = this.subs.shift()) sub.destroy();
  21939. this.packetBuffer = [];
  21940. this.encoding = false;
  21941. this.decoder.destroy();
  21942. };
  21943. /**
  21944. * Close the current socket.
  21945. *
  21946. * @api private
  21947. */
  21948. Manager.prototype.close =
  21949. Manager.prototype.disconnect = function(){
  21950. this.skipReconnect = true;
  21951. this.backoff.reset();
  21952. this.readyState = 'closed';
  21953. this.engine && this.engine.close();
  21954. };
  21955. /**
  21956. * Called upon engine close.
  21957. *
  21958. * @api private
  21959. */
  21960. Manager.prototype.onclose = function(reason){
  21961. debug('close');
  21962. this.cleanup();
  21963. this.backoff.reset();
  21964. this.readyState = 'closed';
  21965. this.emit('close', reason);
  21966. if (this._reconnection && !this.skipReconnect) {
  21967. this.reconnect();
  21968. }
  21969. };
  21970. /**
  21971. * Attempt a reconnection.
  21972. *
  21973. * @api private
  21974. */
  21975. Manager.prototype.reconnect = function(){
  21976. if (this.reconnecting || this.skipReconnect) return this;
  21977. var self = this;
  21978. if (this.backoff.attempts >= this._reconnectionAttempts) {
  21979. debug('reconnect failed');
  21980. this.backoff.reset();
  21981. this.emitAll('reconnect_failed');
  21982. this.reconnecting = false;
  21983. } else {
  21984. var delay = this.backoff.duration();
  21985. debug('will wait %dms before reconnect attempt', delay);
  21986. this.reconnecting = true;
  21987. var timer = setTimeout(function(){
  21988. if (self.skipReconnect) return;
  21989. debug('attempting reconnect');
  21990. self.emitAll('reconnect_attempt', self.backoff.attempts);
  21991. self.emitAll('reconnecting', self.backoff.attempts);
  21992. // check again for the case socket closed in above events
  21993. if (self.skipReconnect) return;
  21994. self.open(function(err){
  21995. if (err) {
  21996. debug('reconnect attempt error');
  21997. self.reconnecting = false;
  21998. self.reconnect();
  21999. self.emitAll('reconnect_error', err.data);
  22000. } else {
  22001. debug('reconnect success');
  22002. self.onreconnect();
  22003. }
  22004. });
  22005. }, delay);
  22006. this.subs.push({
  22007. destroy: function(){
  22008. clearTimeout(timer);
  22009. }
  22010. });
  22011. }
  22012. };
  22013. /**
  22014. * Called upon successful reconnect.
  22015. *
  22016. * @api private
  22017. */
  22018. Manager.prototype.onreconnect = function(){
  22019. var attempt = this.backoff.attempts;
  22020. this.reconnecting = false;
  22021. this.backoff.reset();
  22022. this.updateSocketIds();
  22023. this.emitAll('reconnect', attempt);
  22024. };
  22025. },{"./on":84,"./socket":85,"./url":86,"backo2":87,"component-bind":88,"component-emitter":89,"debug":90,"engine.io-client":91,"indexof":122,"object-component":123,"socket.io-parser":126}],84:[function(require,module,exports){
  22026. /**
  22027. * Module exports.
  22028. */
  22029. module.exports = on;
  22030. /**
  22031. * Helper for subscriptions.
  22032. *
  22033. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  22034. * @param {String} event name
  22035. * @param {Function} callback
  22036. * @api public
  22037. */
  22038. function on(obj, ev, fn) {
  22039. obj.on(ev, fn);
  22040. return {
  22041. destroy: function(){
  22042. obj.removeListener(ev, fn);
  22043. }
  22044. };
  22045. }
  22046. },{}],85:[function(require,module,exports){
  22047. /**
  22048. * Module dependencies.
  22049. */
  22050. var parser = require('socket.io-parser');
  22051. var Emitter = require('component-emitter');
  22052. var toArray = require('to-array');
  22053. var on = require('./on');
  22054. var bind = require('component-bind');
  22055. var debug = require('debug')('socket.io-client:socket');
  22056. var hasBin = require('has-binary');
  22057. /**
  22058. * Module exports.
  22059. */
  22060. module.exports = exports = Socket;
  22061. /**
  22062. * Internal events (blacklisted).
  22063. * These events can't be emitted by the user.
  22064. *
  22065. * @api private
  22066. */
  22067. var events = {
  22068. connect: 1,
  22069. connect_error: 1,
  22070. connect_timeout: 1,
  22071. disconnect: 1,
  22072. error: 1,
  22073. reconnect: 1,
  22074. reconnect_attempt: 1,
  22075. reconnect_failed: 1,
  22076. reconnect_error: 1,
  22077. reconnecting: 1
  22078. };
  22079. /**
  22080. * Shortcut to `Emitter#emit`.
  22081. */
  22082. var emit = Emitter.prototype.emit;
  22083. /**
  22084. * `Socket` constructor.
  22085. *
  22086. * @api public
  22087. */
  22088. function Socket(io, nsp){
  22089. this.io = io;
  22090. this.nsp = nsp;
  22091. this.json = this; // compat
  22092. this.ids = 0;
  22093. this.acks = {};
  22094. if (this.io.autoConnect) this.open();
  22095. this.receiveBuffer = [];
  22096. this.sendBuffer = [];
  22097. this.connected = false;
  22098. this.disconnected = true;
  22099. }
  22100. /**
  22101. * Mix in `Emitter`.
  22102. */
  22103. Emitter(Socket.prototype);
  22104. /**
  22105. * Subscribe to open, close and packet events
  22106. *
  22107. * @api private
  22108. */
  22109. Socket.prototype.subEvents = function() {
  22110. if (this.subs) return;
  22111. var io = this.io;
  22112. this.subs = [
  22113. on(io, 'open', bind(this, 'onopen')),
  22114. on(io, 'packet', bind(this, 'onpacket')),
  22115. on(io, 'close', bind(this, 'onclose'))
  22116. ];
  22117. };
  22118. /**
  22119. * "Opens" the socket.
  22120. *
  22121. * @api public
  22122. */
  22123. Socket.prototype.open =
  22124. Socket.prototype.connect = function(){
  22125. if (this.connected) return this;
  22126. this.subEvents();
  22127. this.io.open(); // ensure open
  22128. if ('open' == this.io.readyState) this.onopen();
  22129. return this;
  22130. };
  22131. /**
  22132. * Sends a `message` event.
  22133. *
  22134. * @return {Socket} self
  22135. * @api public
  22136. */
  22137. Socket.prototype.send = function(){
  22138. var args = toArray(arguments);
  22139. args.unshift('message');
  22140. this.emit.apply(this, args);
  22141. return this;
  22142. };
  22143. /**
  22144. * Override `emit`.
  22145. * If the event is in `events`, it's emitted normally.
  22146. *
  22147. * @param {String} event name
  22148. * @return {Socket} self
  22149. * @api public
  22150. */
  22151. Socket.prototype.emit = function(ev){
  22152. if (events.hasOwnProperty(ev)) {
  22153. emit.apply(this, arguments);
  22154. return this;
  22155. }
  22156. var args = toArray(arguments);
  22157. var parserType = parser.EVENT; // default
  22158. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  22159. var packet = { type: parserType, data: args };
  22160. // event ack callback
  22161. if ('function' == typeof args[args.length - 1]) {
  22162. debug('emitting packet with ack id %d', this.ids);
  22163. this.acks[this.ids] = args.pop();
  22164. packet.id = this.ids++;
  22165. }
  22166. if (this.connected) {
  22167. this.packet(packet);
  22168. } else {
  22169. this.sendBuffer.push(packet);
  22170. }
  22171. return this;
  22172. };
  22173. /**
  22174. * Sends a packet.
  22175. *
  22176. * @param {Object} packet
  22177. * @api private
  22178. */
  22179. Socket.prototype.packet = function(packet){
  22180. packet.nsp = this.nsp;
  22181. this.io.packet(packet);
  22182. };
  22183. /**
  22184. * Called upon engine `open`.
  22185. *
  22186. * @api private
  22187. */
  22188. Socket.prototype.onopen = function(){
  22189. debug('transport is open - connecting');
  22190. // write connect packet if necessary
  22191. if ('/' != this.nsp) {
  22192. this.packet({ type: parser.CONNECT });
  22193. }
  22194. };
  22195. /**
  22196. * Called upon engine `close`.
  22197. *
  22198. * @param {String} reason
  22199. * @api private
  22200. */
  22201. Socket.prototype.onclose = function(reason){
  22202. debug('close (%s)', reason);
  22203. this.connected = false;
  22204. this.disconnected = true;
  22205. delete this.id;
  22206. this.emit('disconnect', reason);
  22207. };
  22208. /**
  22209. * Called with socket packet.
  22210. *
  22211. * @param {Object} packet
  22212. * @api private
  22213. */
  22214. Socket.prototype.onpacket = function(packet){
  22215. if (packet.nsp != this.nsp) return;
  22216. switch (packet.type) {
  22217. case parser.CONNECT:
  22218. this.onconnect();
  22219. break;
  22220. case parser.EVENT:
  22221. this.onevent(packet);
  22222. break;
  22223. case parser.BINARY_EVENT:
  22224. this.onevent(packet);
  22225. break;
  22226. case parser.ACK:
  22227. this.onack(packet);
  22228. break;
  22229. case parser.BINARY_ACK:
  22230. this.onack(packet);
  22231. break;
  22232. case parser.DISCONNECT:
  22233. this.ondisconnect();
  22234. break;
  22235. case parser.ERROR:
  22236. this.emit('error', packet.data);
  22237. break;
  22238. }
  22239. };
  22240. /**
  22241. * Called upon a server event.
  22242. *
  22243. * @param {Object} packet
  22244. * @api private
  22245. */
  22246. Socket.prototype.onevent = function(packet){
  22247. var args = packet.data || [];
  22248. debug('emitting event %j', args);
  22249. if (null != packet.id) {
  22250. debug('attaching ack callback to event');
  22251. args.push(this.ack(packet.id));
  22252. }
  22253. if (this.connected) {
  22254. emit.apply(this, args);
  22255. } else {
  22256. this.receiveBuffer.push(args);
  22257. }
  22258. };
  22259. /**
  22260. * Produces an ack callback to emit with an event.
  22261. *
  22262. * @api private
  22263. */
  22264. Socket.prototype.ack = function(id){
  22265. var self = this;
  22266. var sent = false;
  22267. return function(){
  22268. // prevent double callbacks
  22269. if (sent) return;
  22270. sent = true;
  22271. var args = toArray(arguments);
  22272. debug('sending ack %j', args);
  22273. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  22274. self.packet({
  22275. type: type,
  22276. id: id,
  22277. data: args
  22278. });
  22279. };
  22280. };
  22281. /**
  22282. * Called upon a server acknowlegement.
  22283. *
  22284. * @param {Object} packet
  22285. * @api private
  22286. */
  22287. Socket.prototype.onack = function(packet){
  22288. debug('calling ack %s with %j', packet.id, packet.data);
  22289. var fn = this.acks[packet.id];
  22290. fn.apply(this, packet.data);
  22291. delete this.acks[packet.id];
  22292. };
  22293. /**
  22294. * Called upon server connect.
  22295. *
  22296. * @api private
  22297. */
  22298. Socket.prototype.onconnect = function(){
  22299. this.connected = true;
  22300. this.disconnected = false;
  22301. this.emit('connect');
  22302. this.emitBuffered();
  22303. };
  22304. /**
  22305. * Emit buffered events (received and emitted).
  22306. *
  22307. * @api private
  22308. */
  22309. Socket.prototype.emitBuffered = function(){
  22310. var i;
  22311. for (i = 0; i < this.receiveBuffer.length; i++) {
  22312. emit.apply(this, this.receiveBuffer[i]);
  22313. }
  22314. this.receiveBuffer = [];
  22315. for (i = 0; i < this.sendBuffer.length; i++) {
  22316. this.packet(this.sendBuffer[i]);
  22317. }
  22318. this.sendBuffer = [];
  22319. };
  22320. /**
  22321. * Called upon server disconnect.
  22322. *
  22323. * @api private
  22324. */
  22325. Socket.prototype.ondisconnect = function(){
  22326. debug('server disconnect (%s)', this.nsp);
  22327. this.destroy();
  22328. this.onclose('io server disconnect');
  22329. };
  22330. /**
  22331. * Called upon forced client/server side disconnections,
  22332. * this method ensures the manager stops tracking us and
  22333. * that reconnections don't get triggered for this.
  22334. *
  22335. * @api private.
  22336. */
  22337. Socket.prototype.destroy = function(){
  22338. if (this.subs) {
  22339. // clean subscriptions to avoid reconnections
  22340. for (var i = 0; i < this.subs.length; i++) {
  22341. this.subs[i].destroy();
  22342. }
  22343. this.subs = null;
  22344. }
  22345. this.io.destroy(this);
  22346. };
  22347. /**
  22348. * Disconnects the socket manually.
  22349. *
  22350. * @return {Socket} self
  22351. * @api public
  22352. */
  22353. Socket.prototype.close =
  22354. Socket.prototype.disconnect = function(){
  22355. if (this.connected) {
  22356. debug('performing disconnect (%s)', this.nsp);
  22357. this.packet({ type: parser.DISCONNECT });
  22358. }
  22359. // remove socket from pool
  22360. this.destroy();
  22361. if (this.connected) {
  22362. // fire events
  22363. this.onclose('io client disconnect');
  22364. }
  22365. return this;
  22366. };
  22367. },{"./on":84,"component-bind":88,"component-emitter":89,"debug":90,"has-binary":120,"socket.io-parser":126,"to-array":130}],86:[function(require,module,exports){
  22368. (function (global){
  22369. /**
  22370. * Module dependencies.
  22371. */
  22372. var parseuri = require('parseuri');
  22373. var debug = require('debug')('socket.io-client:url');
  22374. /**
  22375. * Module exports.
  22376. */
  22377. module.exports = url;
  22378. /**
  22379. * URL parser.
  22380. *
  22381. * @param {String} url
  22382. * @param {Object} An object meant to mimic window.location.
  22383. * Defaults to window.location.
  22384. * @api public
  22385. */
  22386. function url(uri, loc){
  22387. var obj = uri;
  22388. // default to window.location
  22389. var loc = loc || global.location;
  22390. if (null == uri) uri = loc.protocol + '//' + loc.host;
  22391. // relative path support
  22392. if ('string' == typeof uri) {
  22393. if ('/' == uri.charAt(0)) {
  22394. if ('/' == uri.charAt(1)) {
  22395. uri = loc.protocol + uri;
  22396. } else {
  22397. uri = loc.hostname + uri;
  22398. }
  22399. }
  22400. if (!/^(https?|wss?):\/\//.test(uri)) {
  22401. debug('protocol-less url %s', uri);
  22402. if ('undefined' != typeof loc) {
  22403. uri = loc.protocol + '//' + uri;
  22404. } else {
  22405. uri = 'https://' + uri;
  22406. }
  22407. }
  22408. // parse
  22409. debug('parse %s', uri);
  22410. obj = parseuri(uri);
  22411. }
  22412. // make sure we treat `localhost:80` and `localhost` equally
  22413. if (!obj.port) {
  22414. if (/^(http|ws)$/.test(obj.protocol)) {
  22415. obj.port = '80';
  22416. }
  22417. else if (/^(http|ws)s$/.test(obj.protocol)) {
  22418. obj.port = '443';
  22419. }
  22420. }
  22421. obj.path = obj.path || '/';
  22422. // define unique id
  22423. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  22424. // define href
  22425. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  22426. return obj;
  22427. }
  22428. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  22429. },{"debug":90,"parseuri":124}],87:[function(require,module,exports){
  22430. /**
  22431. * Expose `Backoff`.
  22432. */
  22433. module.exports = Backoff;
  22434. /**
  22435. * Initialize backoff timer with `opts`.
  22436. *
  22437. * - `min` initial timeout in milliseconds [100]
  22438. * - `max` max timeout [10000]
  22439. * - `jitter` [0]
  22440. * - `factor` [2]
  22441. *
  22442. * @param {Object} opts
  22443. * @api public
  22444. */
  22445. function Backoff(opts) {
  22446. opts = opts || {};
  22447. this.ms = opts.min || 100;
  22448. this.max = opts.max || 10000;
  22449. this.factor = opts.factor || 2;
  22450. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  22451. this.attempts = 0;
  22452. }
  22453. /**
  22454. * Return the backoff duration.
  22455. *
  22456. * @return {Number}
  22457. * @api public
  22458. */
  22459. Backoff.prototype.duration = function(){
  22460. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  22461. if (this.jitter) {
  22462. var rand = Math.random();
  22463. var deviation = Math.floor(rand * this.jitter * ms);
  22464. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  22465. }
  22466. return Math.min(ms, this.max) | 0;
  22467. };
  22468. /**
  22469. * Reset the number of attempts.
  22470. *
  22471. * @api public
  22472. */
  22473. Backoff.prototype.reset = function(){
  22474. this.attempts = 0;
  22475. };
  22476. /**
  22477. * Set the minimum duration
  22478. *
  22479. * @api public
  22480. */
  22481. Backoff.prototype.setMin = function(min){
  22482. this.ms = min;
  22483. };
  22484. /**
  22485. * Set the maximum duration
  22486. *
  22487. * @api public
  22488. */
  22489. Backoff.prototype.setMax = function(max){
  22490. this.max = max;
  22491. };
  22492. /**
  22493. * Set the jitter
  22494. *
  22495. * @api public
  22496. */
  22497. Backoff.prototype.setJitter = function(jitter){
  22498. this.jitter = jitter;
  22499. };
  22500. },{}],88:[function(require,module,exports){
  22501. /**
  22502. * Slice reference.
  22503. */
  22504. var slice = [].slice;
  22505. /**
  22506. * Bind `obj` to `fn`.
  22507. *
  22508. * @param {Object} obj
  22509. * @param {Function|String} fn or string
  22510. * @return {Function}
  22511. * @api public
  22512. */
  22513. module.exports = function(obj, fn){
  22514. if ('string' == typeof fn) fn = obj[fn];
  22515. if ('function' != typeof fn) throw new Error('bind() requires a function');
  22516. var args = slice.call(arguments, 2);
  22517. return function(){
  22518. return fn.apply(obj, args.concat(slice.call(arguments)));
  22519. }
  22520. };
  22521. },{}],89:[function(require,module,exports){
  22522. /**
  22523. * Expose `Emitter`.
  22524. */
  22525. module.exports = Emitter;
  22526. /**
  22527. * Initialize a new `Emitter`.
  22528. *
  22529. * @api public
  22530. */
  22531. function Emitter(obj) {
  22532. if (obj) return mixin(obj);
  22533. };
  22534. /**
  22535. * Mixin the emitter properties.
  22536. *
  22537. * @param {Object} obj
  22538. * @return {Object}
  22539. * @api private
  22540. */
  22541. function mixin(obj) {
  22542. for (var key in Emitter.prototype) {
  22543. obj[key] = Emitter.prototype[key];
  22544. }
  22545. return obj;
  22546. }
  22547. /**
  22548. * Listen on the given `event` with `fn`.
  22549. *
  22550. * @param {String} event
  22551. * @param {Function} fn
  22552. * @return {Emitter}
  22553. * @api public
  22554. */
  22555. Emitter.prototype.on =
  22556. Emitter.prototype.addEventListener = function(event, fn){
  22557. this._callbacks = this._callbacks || {};
  22558. (this._callbacks[event] = this._callbacks[event] || [])
  22559. .push(fn);
  22560. return this;
  22561. };
  22562. /**
  22563. * Adds an `event` listener that will be invoked a single
  22564. * time then automatically removed.
  22565. *
  22566. * @param {String} event
  22567. * @param {Function} fn
  22568. * @return {Emitter}
  22569. * @api public
  22570. */
  22571. Emitter.prototype.once = function(event, fn){
  22572. var self = this;
  22573. this._callbacks = this._callbacks || {};
  22574. function on() {
  22575. self.off(event, on);
  22576. fn.apply(this, arguments);
  22577. }
  22578. on.fn = fn;
  22579. this.on(event, on);
  22580. return this;
  22581. };
  22582. /**
  22583. * Remove the given callback for `event` or all
  22584. * registered callbacks.
  22585. *
  22586. * @param {String} event
  22587. * @param {Function} fn
  22588. * @return {Emitter}
  22589. * @api public
  22590. */
  22591. Emitter.prototype.off =
  22592. Emitter.prototype.removeListener =
  22593. Emitter.prototype.removeAllListeners =
  22594. Emitter.prototype.removeEventListener = function(event, fn){
  22595. this._callbacks = this._callbacks || {};
  22596. // all
  22597. if (0 == arguments.length) {
  22598. this._callbacks = {};
  22599. return this;
  22600. }
  22601. // specific event
  22602. var callbacks = this._callbacks[event];
  22603. if (!callbacks) return this;
  22604. // remove all handlers
  22605. if (1 == arguments.length) {
  22606. delete this._callbacks[event];
  22607. return this;
  22608. }
  22609. // remove specific handler
  22610. var cb;
  22611. for (var i = 0; i < callbacks.length; i++) {
  22612. cb = callbacks[i];
  22613. if (cb === fn || cb.fn === fn) {
  22614. callbacks.splice(i, 1);
  22615. break;
  22616. }
  22617. }
  22618. return this;
  22619. };
  22620. /**
  22621. * Emit `event` with the given args.
  22622. *
  22623. * @param {String} event
  22624. * @param {Mixed} ...
  22625. * @return {Emitter}
  22626. */
  22627. Emitter.prototype.emit = function(event){
  22628. this._callbacks = this._callbacks || {};
  22629. var args = [].slice.call(arguments, 1)
  22630. , callbacks = this._callbacks[event];
  22631. if (callbacks) {
  22632. callbacks = callbacks.slice(0);
  22633. for (var i = 0, len = callbacks.length; i < len; ++i) {
  22634. callbacks[i].apply(this, args);
  22635. }
  22636. }
  22637. return this;
  22638. };
  22639. /**
  22640. * Return array of callbacks for `event`.
  22641. *
  22642. * @param {String} event
  22643. * @return {Array}
  22644. * @api public
  22645. */
  22646. Emitter.prototype.listeners = function(event){
  22647. this._callbacks = this._callbacks || {};
  22648. return this._callbacks[event] || [];
  22649. };
  22650. /**
  22651. * Check if this emitter has `event` handlers.
  22652. *
  22653. * @param {String} event
  22654. * @return {Boolean}
  22655. * @api public
  22656. */
  22657. Emitter.prototype.hasListeners = function(event){
  22658. return !! this.listeners(event).length;
  22659. };
  22660. },{}],90:[function(require,module,exports){
  22661. /**
  22662. * Expose `debug()` as the module.
  22663. */
  22664. module.exports = debug;
  22665. /**
  22666. * Create a debugger with the given `name`.
  22667. *
  22668. * @param {String} name
  22669. * @return {Type}
  22670. * @api public
  22671. */
  22672. function debug(name) {
  22673. if (!debug.enabled(name)) return function(){};
  22674. return function(fmt){
  22675. fmt = coerce(fmt);
  22676. var curr = new Date;
  22677. var ms = curr - (debug[name] || curr);
  22678. debug[name] = curr;
  22679. fmt = name
  22680. + ' '
  22681. + fmt
  22682. + ' +' + debug.humanize(ms);
  22683. // This hackery is required for IE8
  22684. // where `console.log` doesn't have 'apply'
  22685. window.console
  22686. && console.log
  22687. && Function.prototype.apply.call(console.log, console, arguments);
  22688. }
  22689. }
  22690. /**
  22691. * The currently active debug mode names.
  22692. */
  22693. debug.names = [];
  22694. debug.skips = [];
  22695. /**
  22696. * Enables a debug mode by name. This can include modes
  22697. * separated by a colon and wildcards.
  22698. *
  22699. * @param {String} name
  22700. * @api public
  22701. */
  22702. debug.enable = function(name) {
  22703. try {
  22704. localStorage.debug = name;
  22705. } catch(e){}
  22706. var split = (name || '').split(/[\s,]+/)
  22707. , len = split.length;
  22708. for (var i = 0; i < len; i++) {
  22709. name = split[i].replace('*', '.*?');
  22710. if (name[0] === '-') {
  22711. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  22712. }
  22713. else {
  22714. debug.names.push(new RegExp('^' + name + '$'));
  22715. }
  22716. }
  22717. };
  22718. /**
  22719. * Disable debug output.
  22720. *
  22721. * @api public
  22722. */
  22723. debug.disable = function(){
  22724. debug.enable('');
  22725. };
  22726. /**
  22727. * Humanize the given `ms`.
  22728. *
  22729. * @param {Number} m
  22730. * @return {String}
  22731. * @api private
  22732. */
  22733. debug.humanize = function(ms) {
  22734. var sec = 1000
  22735. , min = 60 * 1000
  22736. , hour = 60 * min;
  22737. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  22738. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  22739. if (ms >= sec) return (ms / sec | 0) + 's';
  22740. return ms + 'ms';
  22741. };
  22742. /**
  22743. * Returns true if the given mode name is enabled, false otherwise.
  22744. *
  22745. * @param {String} name
  22746. * @return {Boolean}
  22747. * @api public
  22748. */
  22749. debug.enabled = function(name) {
  22750. for (var i = 0, len = debug.skips.length; i < len; i++) {
  22751. if (debug.skips[i].test(name)) {
  22752. return false;
  22753. }
  22754. }
  22755. for (var i = 0, len = debug.names.length; i < len; i++) {
  22756. if (debug.names[i].test(name)) {
  22757. return true;
  22758. }
  22759. }
  22760. return false;
  22761. };
  22762. /**
  22763. * Coerce `val`.
  22764. */
  22765. function coerce(val) {
  22766. if (val instanceof Error) return val.stack || val.message;
  22767. return val;
  22768. }
  22769. // persist
  22770. try {
  22771. if (window.localStorage) debug.enable(localStorage.debug);
  22772. } catch(e){}
  22773. },{}],91:[function(require,module,exports){
  22774. module.exports = require('./lib/');
  22775. },{"./lib/":92}],92:[function(require,module,exports){
  22776. module.exports = require('./socket');
  22777. /**
  22778. * Exports parser
  22779. *
  22780. * @api public
  22781. *
  22782. */
  22783. module.exports.parser = require('engine.io-parser');
  22784. },{"./socket":93,"engine.io-parser":105}],93:[function(require,module,exports){
  22785. (function (global){
  22786. /**
  22787. * Module dependencies.
  22788. */
  22789. var transports = require('./transports');
  22790. var Emitter = require('component-emitter');
  22791. var debug = require('debug')('engine.io-client:socket');
  22792. var index = require('indexof');
  22793. var parser = require('engine.io-parser');
  22794. var parseuri = require('parseuri');
  22795. var parsejson = require('parsejson');
  22796. var parseqs = require('parseqs');
  22797. /**
  22798. * Module exports.
  22799. */
  22800. module.exports = Socket;
  22801. /**
  22802. * Noop function.
  22803. *
  22804. * @api private
  22805. */
  22806. function noop(){}
  22807. /**
  22808. * Socket constructor.
  22809. *
  22810. * @param {String|Object} uri or options
  22811. * @param {Object} options
  22812. * @api public
  22813. */
  22814. function Socket(uri, opts){
  22815. if (!(this instanceof Socket)) return new Socket(uri, opts);
  22816. opts = opts || {};
  22817. if (uri && 'object' == typeof uri) {
  22818. opts = uri;
  22819. uri = null;
  22820. }
  22821. if (uri) {
  22822. uri = parseuri(uri);
  22823. opts.host = uri.host;
  22824. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  22825. opts.port = uri.port;
  22826. if (uri.query) opts.query = uri.query;
  22827. }
  22828. this.secure = null != opts.secure ? opts.secure :
  22829. (global.location && 'https:' == location.protocol);
  22830. if (opts.host) {
  22831. var pieces = opts.host.split(':');
  22832. opts.hostname = pieces.shift();
  22833. if (pieces.length) {
  22834. opts.port = pieces.pop();
  22835. } else if (!opts.port) {
  22836. // if no port is specified manually, use the protocol default
  22837. opts.port = this.secure ? '443' : '80';
  22838. }
  22839. }
  22840. this.agent = opts.agent || false;
  22841. this.hostname = opts.hostname ||
  22842. (global.location ? location.hostname : 'localhost');
  22843. this.port = opts.port || (global.location && location.port ?
  22844. location.port :
  22845. (this.secure ? 443 : 80));
  22846. this.query = opts.query || {};
  22847. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  22848. this.upgrade = false !== opts.upgrade;
  22849. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  22850. this.forceJSONP = !!opts.forceJSONP;
  22851. this.jsonp = false !== opts.jsonp;
  22852. this.forceBase64 = !!opts.forceBase64;
  22853. this.enablesXDR = !!opts.enablesXDR;
  22854. this.timestampParam = opts.timestampParam || 't';
  22855. this.timestampRequests = opts.timestampRequests;
  22856. this.transports = opts.transports || ['polling', 'websocket'];
  22857. this.readyState = '';
  22858. this.writeBuffer = [];
  22859. this.callbackBuffer = [];
  22860. this.policyPort = opts.policyPort || 843;
  22861. this.rememberUpgrade = opts.rememberUpgrade || false;
  22862. this.binaryType = null;
  22863. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  22864. // SSL options for Node.js client
  22865. this.pfx = opts.pfx || null;
  22866. this.key = opts.key || null;
  22867. this.passphrase = opts.passphrase || null;
  22868. this.cert = opts.cert || null;
  22869. this.ca = opts.ca || null;
  22870. this.ciphers = opts.ciphers || null;
  22871. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  22872. this.open();
  22873. }
  22874. Socket.priorWebsocketSuccess = false;
  22875. /**
  22876. * Mix in `Emitter`.
  22877. */
  22878. Emitter(Socket.prototype);
  22879. /**
  22880. * Protocol version.
  22881. *
  22882. * @api public
  22883. */
  22884. Socket.protocol = parser.protocol; // this is an int
  22885. /**
  22886. * Expose deps for legacy compatibility
  22887. * and standalone browser access.
  22888. */
  22889. Socket.Socket = Socket;
  22890. Socket.Transport = require('./transport');
  22891. Socket.transports = require('./transports');
  22892. Socket.parser = require('engine.io-parser');
  22893. /**
  22894. * Creates transport of the given type.
  22895. *
  22896. * @param {String} transport name
  22897. * @return {Transport}
  22898. * @api private
  22899. */
  22900. Socket.prototype.createTransport = function (name) {
  22901. debug('creating transport "%s"', name);
  22902. var query = clone(this.query);
  22903. // append engine.io protocol identifier
  22904. query.EIO = parser.protocol;
  22905. // transport name
  22906. query.transport = name;
  22907. // session id if we already have one
  22908. if (this.id) query.sid = this.id;
  22909. var transport = new transports[name]({
  22910. agent: this.agent,
  22911. hostname: this.hostname,
  22912. port: this.port,
  22913. secure: this.secure,
  22914. path: this.path,
  22915. query: query,
  22916. forceJSONP: this.forceJSONP,
  22917. jsonp: this.jsonp,
  22918. forceBase64: this.forceBase64,
  22919. enablesXDR: this.enablesXDR,
  22920. timestampRequests: this.timestampRequests,
  22921. timestampParam: this.timestampParam,
  22922. policyPort: this.policyPort,
  22923. socket: this,
  22924. pfx: this.pfx,
  22925. key: this.key,
  22926. passphrase: this.passphrase,
  22927. cert: this.cert,
  22928. ca: this.ca,
  22929. ciphers: this.ciphers,
  22930. rejectUnauthorized: this.rejectUnauthorized
  22931. });
  22932. return transport;
  22933. };
  22934. function clone (obj) {
  22935. var o = {};
  22936. for (var i in obj) {
  22937. if (obj.hasOwnProperty(i)) {
  22938. o[i] = obj[i];
  22939. }
  22940. }
  22941. return o;
  22942. }
  22943. /**
  22944. * Initializes transport to use and starts probe.
  22945. *
  22946. * @api private
  22947. */
  22948. Socket.prototype.open = function () {
  22949. var transport;
  22950. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  22951. transport = 'websocket';
  22952. } else if (0 == this.transports.length) {
  22953. // Emit error on next tick so it can be listened to
  22954. var self = this;
  22955. setTimeout(function() {
  22956. self.emit('error', 'No transports available');
  22957. }, 0);
  22958. return;
  22959. } else {
  22960. transport = this.transports[0];
  22961. }
  22962. this.readyState = 'opening';
  22963. // Retry with the next transport if the transport is disabled (jsonp: false)
  22964. var transport;
  22965. try {
  22966. transport = this.createTransport(transport);
  22967. } catch (e) {
  22968. this.transports.shift();
  22969. this.open();
  22970. return;
  22971. }
  22972. transport.open();
  22973. this.setTransport(transport);
  22974. };
  22975. /**
  22976. * Sets the current transport. Disables the existing one (if any).
  22977. *
  22978. * @api private
  22979. */
  22980. Socket.prototype.setTransport = function(transport){
  22981. debug('setting transport %s', transport.name);
  22982. var self = this;
  22983. if (this.transport) {
  22984. debug('clearing existing transport %s', this.transport.name);
  22985. this.transport.removeAllListeners();
  22986. }
  22987. // set up transport
  22988. this.transport = transport;
  22989. // set up transport listeners
  22990. transport
  22991. .on('drain', function(){
  22992. self.onDrain();
  22993. })
  22994. .on('packet', function(packet){
  22995. self.onPacket(packet);
  22996. })
  22997. .on('error', function(e){
  22998. self.onError(e);
  22999. })
  23000. .on('close', function(){
  23001. self.onClose('transport close');
  23002. });
  23003. };
  23004. /**
  23005. * Probes a transport.
  23006. *
  23007. * @param {String} transport name
  23008. * @api private
  23009. */
  23010. Socket.prototype.probe = function (name) {
  23011. debug('probing transport "%s"', name);
  23012. var transport = this.createTransport(name, { probe: 1 })
  23013. , failed = false
  23014. , self = this;
  23015. Socket.priorWebsocketSuccess = false;
  23016. function onTransportOpen(){
  23017. if (self.onlyBinaryUpgrades) {
  23018. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  23019. failed = failed || upgradeLosesBinary;
  23020. }
  23021. if (failed) return;
  23022. debug('probe transport "%s" opened', name);
  23023. transport.send([{ type: 'ping', data: 'probe' }]);
  23024. transport.once('packet', function (msg) {
  23025. if (failed) return;
  23026. if ('pong' == msg.type && 'probe' == msg.data) {
  23027. debug('probe transport "%s" pong', name);
  23028. self.upgrading = true;
  23029. self.emit('upgrading', transport);
  23030. if (!transport) return;
  23031. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  23032. debug('pausing current transport "%s"', self.transport.name);
  23033. self.transport.pause(function () {
  23034. if (failed) return;
  23035. if ('closed' == self.readyState) return;
  23036. debug('changing transport and sending upgrade packet');
  23037. cleanup();
  23038. self.setTransport(transport);
  23039. transport.send([{ type: 'upgrade' }]);
  23040. self.emit('upgrade', transport);
  23041. transport = null;
  23042. self.upgrading = false;
  23043. self.flush();
  23044. });
  23045. } else {
  23046. debug('probe transport "%s" failed', name);
  23047. var err = new Error('probe error');
  23048. err.transport = transport.name;
  23049. self.emit('upgradeError', err);
  23050. }
  23051. });
  23052. }
  23053. function freezeTransport() {
  23054. if (failed) return;
  23055. // Any callback called by transport should be ignored since now
  23056. failed = true;
  23057. cleanup();
  23058. transport.close();
  23059. transport = null;
  23060. }
  23061. //Handle any error that happens while probing
  23062. function onerror(err) {
  23063. var error = new Error('probe error: ' + err);
  23064. error.transport = transport.name;
  23065. freezeTransport();
  23066. debug('probe transport "%s" failed because of error: %s', name, err);
  23067. self.emit('upgradeError', error);
  23068. }
  23069. function onTransportClose(){
  23070. onerror("transport closed");
  23071. }
  23072. //When the socket is closed while we're probing
  23073. function onclose(){
  23074. onerror("socket closed");
  23075. }
  23076. //When the socket is upgraded while we're probing
  23077. function onupgrade(to){
  23078. if (transport && to.name != transport.name) {
  23079. debug('"%s" works - aborting "%s"', to.name, transport.name);
  23080. freezeTransport();
  23081. }
  23082. }
  23083. //Remove all listeners on the transport and on self
  23084. function cleanup(){
  23085. transport.removeListener('open', onTransportOpen);
  23086. transport.removeListener('error', onerror);
  23087. transport.removeListener('close', onTransportClose);
  23088. self.removeListener('close', onclose);
  23089. self.removeListener('upgrading', onupgrade);
  23090. }
  23091. transport.once('open', onTransportOpen);
  23092. transport.once('error', onerror);
  23093. transport.once('close', onTransportClose);
  23094. this.once('close', onclose);
  23095. this.once('upgrading', onupgrade);
  23096. transport.open();
  23097. };
  23098. /**
  23099. * Called when connection is deemed open.
  23100. *
  23101. * @api public
  23102. */
  23103. Socket.prototype.onOpen = function () {
  23104. debug('socket open');
  23105. this.readyState = 'open';
  23106. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  23107. this.emit('open');
  23108. this.flush();
  23109. // we check for `readyState` in case an `open`
  23110. // listener already closed the socket
  23111. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  23112. debug('starting upgrade probes');
  23113. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  23114. this.probe(this.upgrades[i]);
  23115. }
  23116. }
  23117. };
  23118. /**
  23119. * Handles a packet.
  23120. *
  23121. * @api private
  23122. */
  23123. Socket.prototype.onPacket = function (packet) {
  23124. if ('opening' == this.readyState || 'open' == this.readyState) {
  23125. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  23126. this.emit('packet', packet);
  23127. // Socket is live - any packet counts
  23128. this.emit('heartbeat');
  23129. switch (packet.type) {
  23130. case 'open':
  23131. this.onHandshake(parsejson(packet.data));
  23132. break;
  23133. case 'pong':
  23134. this.setPing();
  23135. break;
  23136. case 'error':
  23137. var err = new Error('server error');
  23138. err.code = packet.data;
  23139. this.emit('error', err);
  23140. break;
  23141. case 'message':
  23142. this.emit('data', packet.data);
  23143. this.emit('message', packet.data);
  23144. break;
  23145. }
  23146. } else {
  23147. debug('packet received with socket readyState "%s"', this.readyState);
  23148. }
  23149. };
  23150. /**
  23151. * Called upon handshake completion.
  23152. *
  23153. * @param {Object} handshake obj
  23154. * @api private
  23155. */
  23156. Socket.prototype.onHandshake = function (data) {
  23157. this.emit('handshake', data);
  23158. this.id = data.sid;
  23159. this.transport.query.sid = data.sid;
  23160. this.upgrades = this.filterUpgrades(data.upgrades);
  23161. this.pingInterval = data.pingInterval;
  23162. this.pingTimeout = data.pingTimeout;
  23163. this.onOpen();
  23164. // In case open handler closes socket
  23165. if ('closed' == this.readyState) return;
  23166. this.setPing();
  23167. // Prolong liveness of socket on heartbeat
  23168. this.removeListener('heartbeat', this.onHeartbeat);
  23169. this.on('heartbeat', this.onHeartbeat);
  23170. };
  23171. /**
  23172. * Resets ping timeout.
  23173. *
  23174. * @api private
  23175. */
  23176. Socket.prototype.onHeartbeat = function (timeout) {
  23177. clearTimeout(this.pingTimeoutTimer);
  23178. var self = this;
  23179. self.pingTimeoutTimer = setTimeout(function () {
  23180. if ('closed' == self.readyState) return;
  23181. self.onClose('ping timeout');
  23182. }, timeout || (self.pingInterval + self.pingTimeout));
  23183. };
  23184. /**
  23185. * Pings server every `this.pingInterval` and expects response
  23186. * within `this.pingTimeout` or closes connection.
  23187. *
  23188. * @api private
  23189. */
  23190. Socket.prototype.setPing = function () {
  23191. var self = this;
  23192. clearTimeout(self.pingIntervalTimer);
  23193. self.pingIntervalTimer = setTimeout(function () {
  23194. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  23195. self.ping();
  23196. self.onHeartbeat(self.pingTimeout);
  23197. }, self.pingInterval);
  23198. };
  23199. /**
  23200. * Sends a ping packet.
  23201. *
  23202. * @api public
  23203. */
  23204. Socket.prototype.ping = function () {
  23205. this.sendPacket('ping');
  23206. };
  23207. /**
  23208. * Called on `drain` event
  23209. *
  23210. * @api private
  23211. */
  23212. Socket.prototype.onDrain = function() {
  23213. for (var i = 0; i < this.prevBufferLen; i++) {
  23214. if (this.callbackBuffer[i]) {
  23215. this.callbackBuffer[i]();
  23216. }
  23217. }
  23218. this.writeBuffer.splice(0, this.prevBufferLen);
  23219. this.callbackBuffer.splice(0, this.prevBufferLen);
  23220. // setting prevBufferLen = 0 is very important
  23221. // for example, when upgrading, upgrade packet is sent over,
  23222. // and a nonzero prevBufferLen could cause problems on `drain`
  23223. this.prevBufferLen = 0;
  23224. if (this.writeBuffer.length == 0) {
  23225. this.emit('drain');
  23226. } else {
  23227. this.flush();
  23228. }
  23229. };
  23230. /**
  23231. * Flush write buffers.
  23232. *
  23233. * @api private
  23234. */
  23235. Socket.prototype.flush = function () {
  23236. if ('closed' != this.readyState && this.transport.writable &&
  23237. !this.upgrading && this.writeBuffer.length) {
  23238. debug('flushing %d packets in socket', this.writeBuffer.length);
  23239. this.transport.send(this.writeBuffer);
  23240. // keep track of current length of writeBuffer
  23241. // splice writeBuffer and callbackBuffer on `drain`
  23242. this.prevBufferLen = this.writeBuffer.length;
  23243. this.emit('flush');
  23244. }
  23245. };
  23246. /**
  23247. * Sends a message.
  23248. *
  23249. * @param {String} message.
  23250. * @param {Function} callback function.
  23251. * @return {Socket} for chaining.
  23252. * @api public
  23253. */
  23254. Socket.prototype.write =
  23255. Socket.prototype.send = function (msg, fn) {
  23256. this.sendPacket('message', msg, fn);
  23257. return this;
  23258. };
  23259. /**
  23260. * Sends a packet.
  23261. *
  23262. * @param {String} packet type.
  23263. * @param {String} data.
  23264. * @param {Function} callback function.
  23265. * @api private
  23266. */
  23267. Socket.prototype.sendPacket = function (type, data, fn) {
  23268. if ('closing' == this.readyState || 'closed' == this.readyState) {
  23269. return;
  23270. }
  23271. var packet = { type: type, data: data };
  23272. this.emit('packetCreate', packet);
  23273. this.writeBuffer.push(packet);
  23274. this.callbackBuffer.push(fn);
  23275. this.flush();
  23276. };
  23277. /**
  23278. * Closes the connection.
  23279. *
  23280. * @api private
  23281. */
  23282. Socket.prototype.close = function () {
  23283. if ('opening' == this.readyState || 'open' == this.readyState) {
  23284. this.readyState = 'closing';
  23285. var self = this;
  23286. function close() {
  23287. self.onClose('forced close');
  23288. debug('socket closing - telling transport to close');
  23289. self.transport.close();
  23290. }
  23291. function cleanupAndClose() {
  23292. self.removeListener('upgrade', cleanupAndClose);
  23293. self.removeListener('upgradeError', cleanupAndClose);
  23294. close();
  23295. }
  23296. function waitForUpgrade() {
  23297. // wait for upgrade to finish since we can't send packets while pausing a transport
  23298. self.once('upgrade', cleanupAndClose);
  23299. self.once('upgradeError', cleanupAndClose);
  23300. }
  23301. if (this.writeBuffer.length) {
  23302. this.once('drain', function() {
  23303. if (this.upgrading) {
  23304. waitForUpgrade();
  23305. } else {
  23306. close();
  23307. }
  23308. });
  23309. } else if (this.upgrading) {
  23310. waitForUpgrade();
  23311. } else {
  23312. close();
  23313. }
  23314. }
  23315. return this;
  23316. };
  23317. /**
  23318. * Called upon transport error
  23319. *
  23320. * @api private
  23321. */
  23322. Socket.prototype.onError = function (err) {
  23323. debug('socket error %j', err);
  23324. Socket.priorWebsocketSuccess = false;
  23325. this.emit('error', err);
  23326. this.onClose('transport error', err);
  23327. };
  23328. /**
  23329. * Called upon transport close.
  23330. *
  23331. * @api private
  23332. */
  23333. Socket.prototype.onClose = function (reason, desc) {
  23334. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  23335. debug('socket close with reason: "%s"', reason);
  23336. var self = this;
  23337. // clear timers
  23338. clearTimeout(this.pingIntervalTimer);
  23339. clearTimeout(this.pingTimeoutTimer);
  23340. // clean buffers in next tick, so developers can still
  23341. // grab the buffers on `close` event
  23342. setTimeout(function() {
  23343. self.writeBuffer = [];
  23344. self.callbackBuffer = [];
  23345. self.prevBufferLen = 0;
  23346. }, 0);
  23347. // stop event from firing again for transport
  23348. this.transport.removeAllListeners('close');
  23349. // ensure transport won't stay open
  23350. this.transport.close();
  23351. // ignore further transport communication
  23352. this.transport.removeAllListeners();
  23353. // set ready state
  23354. this.readyState = 'closed';
  23355. // clear session id
  23356. this.id = null;
  23357. // emit close event
  23358. this.emit('close', reason, desc);
  23359. }
  23360. };
  23361. /**
  23362. * Filters upgrades, returning only those matching client transports.
  23363. *
  23364. * @param {Array} server upgrades
  23365. * @api private
  23366. *
  23367. */
  23368. Socket.prototype.filterUpgrades = function (upgrades) {
  23369. var filteredUpgrades = [];
  23370. for (var i = 0, j = upgrades.length; i<j; i++) {
  23371. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  23372. }
  23373. return filteredUpgrades;
  23374. };
  23375. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23376. },{"./transport":94,"./transports":95,"component-emitter":89,"debug":102,"engine.io-parser":105,"indexof":122,"parsejson":116,"parseqs":117,"parseuri":118}],94:[function(require,module,exports){
  23377. /**
  23378. * Module dependencies.
  23379. */
  23380. var parser = require('engine.io-parser');
  23381. var Emitter = require('component-emitter');
  23382. /**
  23383. * Module exports.
  23384. */
  23385. module.exports = Transport;
  23386. /**
  23387. * Transport abstract constructor.
  23388. *
  23389. * @param {Object} options.
  23390. * @api private
  23391. */
  23392. function Transport (opts) {
  23393. this.path = opts.path;
  23394. this.hostname = opts.hostname;
  23395. this.port = opts.port;
  23396. this.secure = opts.secure;
  23397. this.query = opts.query;
  23398. this.timestampParam = opts.timestampParam;
  23399. this.timestampRequests = opts.timestampRequests;
  23400. this.readyState = '';
  23401. this.agent = opts.agent || false;
  23402. this.socket = opts.socket;
  23403. this.enablesXDR = opts.enablesXDR;
  23404. // SSL options for Node.js client
  23405. this.pfx = opts.pfx;
  23406. this.key = opts.key;
  23407. this.passphrase = opts.passphrase;
  23408. this.cert = opts.cert;
  23409. this.ca = opts.ca;
  23410. this.ciphers = opts.ciphers;
  23411. this.rejectUnauthorized = opts.rejectUnauthorized;
  23412. }
  23413. /**
  23414. * Mix in `Emitter`.
  23415. */
  23416. Emitter(Transport.prototype);
  23417. /**
  23418. * A counter used to prevent collisions in the timestamps used
  23419. * for cache busting.
  23420. */
  23421. Transport.timestamps = 0;
  23422. /**
  23423. * Emits an error.
  23424. *
  23425. * @param {String} str
  23426. * @return {Transport} for chaining
  23427. * @api public
  23428. */
  23429. Transport.prototype.onError = function (msg, desc) {
  23430. var err = new Error(msg);
  23431. err.type = 'TransportError';
  23432. err.description = desc;
  23433. this.emit('error', err);
  23434. return this;
  23435. };
  23436. /**
  23437. * Opens the transport.
  23438. *
  23439. * @api public
  23440. */
  23441. Transport.prototype.open = function () {
  23442. if ('closed' == this.readyState || '' == this.readyState) {
  23443. this.readyState = 'opening';
  23444. this.doOpen();
  23445. }
  23446. return this;
  23447. };
  23448. /**
  23449. * Closes the transport.
  23450. *
  23451. * @api private
  23452. */
  23453. Transport.prototype.close = function () {
  23454. if ('opening' == this.readyState || 'open' == this.readyState) {
  23455. this.doClose();
  23456. this.onClose();
  23457. }
  23458. return this;
  23459. };
  23460. /**
  23461. * Sends multiple packets.
  23462. *
  23463. * @param {Array} packets
  23464. * @api private
  23465. */
  23466. Transport.prototype.send = function(packets){
  23467. if ('open' == this.readyState) {
  23468. this.write(packets);
  23469. } else {
  23470. throw new Error('Transport not open');
  23471. }
  23472. };
  23473. /**
  23474. * Called upon open
  23475. *
  23476. * @api private
  23477. */
  23478. Transport.prototype.onOpen = function () {
  23479. this.readyState = 'open';
  23480. this.writable = true;
  23481. this.emit('open');
  23482. };
  23483. /**
  23484. * Called with data.
  23485. *
  23486. * @param {String} data
  23487. * @api private
  23488. */
  23489. Transport.prototype.onData = function(data){
  23490. var packet = parser.decodePacket(data, this.socket.binaryType);
  23491. this.onPacket(packet);
  23492. };
  23493. /**
  23494. * Called with a decoded packet.
  23495. */
  23496. Transport.prototype.onPacket = function (packet) {
  23497. this.emit('packet', packet);
  23498. };
  23499. /**
  23500. * Called upon close.
  23501. *
  23502. * @api private
  23503. */
  23504. Transport.prototype.onClose = function () {
  23505. this.readyState = 'closed';
  23506. this.emit('close');
  23507. };
  23508. },{"component-emitter":89,"engine.io-parser":105}],95:[function(require,module,exports){
  23509. (function (global){
  23510. /**
  23511. * Module dependencies
  23512. */
  23513. var XMLHttpRequest = require('xmlhttprequest');
  23514. var XHR = require('./polling-xhr');
  23515. var JSONP = require('./polling-jsonp');
  23516. var websocket = require('./websocket');
  23517. /**
  23518. * Export transports.
  23519. */
  23520. exports.polling = polling;
  23521. exports.websocket = websocket;
  23522. /**
  23523. * Polling transport polymorphic constructor.
  23524. * Decides on xhr vs jsonp based on feature detection.
  23525. *
  23526. * @api private
  23527. */
  23528. function polling(opts){
  23529. var xhr;
  23530. var xd = false;
  23531. var xs = false;
  23532. var jsonp = false !== opts.jsonp;
  23533. if (global.location) {
  23534. var isSSL = 'https:' == location.protocol;
  23535. var port = location.port;
  23536. // some user agents have empty `location.port`
  23537. if (!port) {
  23538. port = isSSL ? 443 : 80;
  23539. }
  23540. xd = opts.hostname != location.hostname || port != opts.port;
  23541. xs = opts.secure != isSSL;
  23542. }
  23543. opts.xdomain = xd;
  23544. opts.xscheme = xs;
  23545. xhr = new XMLHttpRequest(opts);
  23546. if ('open' in xhr && !opts.forceJSONP) {
  23547. return new XHR(opts);
  23548. } else {
  23549. if (!jsonp) throw new Error('JSONP disabled');
  23550. return new JSONP(opts);
  23551. }
  23552. }
  23553. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23554. },{"./polling-jsonp":96,"./polling-xhr":97,"./websocket":99,"xmlhttprequest":100}],96:[function(require,module,exports){
  23555. (function (global){
  23556. /**
  23557. * Module requirements.
  23558. */
  23559. var Polling = require('./polling');
  23560. var inherit = require('component-inherit');
  23561. /**
  23562. * Module exports.
  23563. */
  23564. module.exports = JSONPPolling;
  23565. /**
  23566. * Cached regular expressions.
  23567. */
  23568. var rNewline = /\n/g;
  23569. var rEscapedNewline = /\\n/g;
  23570. /**
  23571. * Global JSONP callbacks.
  23572. */
  23573. var callbacks;
  23574. /**
  23575. * Callbacks count.
  23576. */
  23577. var index = 0;
  23578. /**
  23579. * Noop.
  23580. */
  23581. function empty () { }
  23582. /**
  23583. * JSONP Polling constructor.
  23584. *
  23585. * @param {Object} opts.
  23586. * @api public
  23587. */
  23588. function JSONPPolling (opts) {
  23589. Polling.call(this, opts);
  23590. this.query = this.query || {};
  23591. // define global callbacks array if not present
  23592. // we do this here (lazily) to avoid unneeded global pollution
  23593. if (!callbacks) {
  23594. // we need to consider multiple engines in the same page
  23595. if (!global.___eio) global.___eio = [];
  23596. callbacks = global.___eio;
  23597. }
  23598. // callback identifier
  23599. this.index = callbacks.length;
  23600. // add callback to jsonp global
  23601. var self = this;
  23602. callbacks.push(function (msg) {
  23603. self.onData(msg);
  23604. });
  23605. // append to query string
  23606. this.query.j = this.index;
  23607. // prevent spurious errors from being emitted when the window is unloaded
  23608. if (global.document && global.addEventListener) {
  23609. global.addEventListener('beforeunload', function () {
  23610. if (self.script) self.script.onerror = empty;
  23611. }, false);
  23612. }
  23613. }
  23614. /**
  23615. * Inherits from Polling.
  23616. */
  23617. inherit(JSONPPolling, Polling);
  23618. /*
  23619. * JSONP only supports binary as base64 encoded strings
  23620. */
  23621. JSONPPolling.prototype.supportsBinary = false;
  23622. /**
  23623. * Closes the socket.
  23624. *
  23625. * @api private
  23626. */
  23627. JSONPPolling.prototype.doClose = function () {
  23628. if (this.script) {
  23629. this.script.parentNode.removeChild(this.script);
  23630. this.script = null;
  23631. }
  23632. if (this.form) {
  23633. this.form.parentNode.removeChild(this.form);
  23634. this.form = null;
  23635. this.iframe = null;
  23636. }
  23637. Polling.prototype.doClose.call(this);
  23638. };
  23639. /**
  23640. * Starts a poll cycle.
  23641. *
  23642. * @api private
  23643. */
  23644. JSONPPolling.prototype.doPoll = function () {
  23645. var self = this;
  23646. var script = document.createElement('script');
  23647. if (this.script) {
  23648. this.script.parentNode.removeChild(this.script);
  23649. this.script = null;
  23650. }
  23651. script.async = true;
  23652. script.src = this.uri();
  23653. script.onerror = function(e){
  23654. self.onError('jsonp poll error',e);
  23655. };
  23656. var insertAt = document.getElementsByTagName('script')[0];
  23657. insertAt.parentNode.insertBefore(script, insertAt);
  23658. this.script = script;
  23659. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  23660. if (isUAgecko) {
  23661. setTimeout(function () {
  23662. var iframe = document.createElement('iframe');
  23663. document.body.appendChild(iframe);
  23664. document.body.removeChild(iframe);
  23665. }, 100);
  23666. }
  23667. };
  23668. /**
  23669. * Writes with a hidden iframe.
  23670. *
  23671. * @param {String} data to send
  23672. * @param {Function} called upon flush.
  23673. * @api private
  23674. */
  23675. JSONPPolling.prototype.doWrite = function (data, fn) {
  23676. var self = this;
  23677. if (!this.form) {
  23678. var form = document.createElement('form');
  23679. var area = document.createElement('textarea');
  23680. var id = this.iframeId = 'eio_iframe_' + this.index;
  23681. var iframe;
  23682. form.className = 'socketio';
  23683. form.style.position = 'absolute';
  23684. form.style.top = '-1000px';
  23685. form.style.left = '-1000px';
  23686. form.target = id;
  23687. form.method = 'POST';
  23688. form.setAttribute('accept-charset', 'utf-8');
  23689. area.name = 'd';
  23690. form.appendChild(area);
  23691. document.body.appendChild(form);
  23692. this.form = form;
  23693. this.area = area;
  23694. }
  23695. this.form.action = this.uri();
  23696. function complete () {
  23697. initIframe();
  23698. fn();
  23699. }
  23700. function initIframe () {
  23701. if (self.iframe) {
  23702. try {
  23703. self.form.removeChild(self.iframe);
  23704. } catch (e) {
  23705. self.onError('jsonp polling iframe removal error', e);
  23706. }
  23707. }
  23708. try {
  23709. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  23710. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  23711. iframe = document.createElement(html);
  23712. } catch (e) {
  23713. iframe = document.createElement('iframe');
  23714. iframe.name = self.iframeId;
  23715. iframe.src = 'javascript:0';
  23716. }
  23717. iframe.id = self.iframeId;
  23718. self.form.appendChild(iframe);
  23719. self.iframe = iframe;
  23720. }
  23721. initIframe();
  23722. // escape \n to prevent it from being converted into \r\n by some UAs
  23723. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  23724. data = data.replace(rEscapedNewline, '\\\n');
  23725. this.area.value = data.replace(rNewline, '\\n');
  23726. try {
  23727. this.form.submit();
  23728. } catch(e) {}
  23729. if (this.iframe.attachEvent) {
  23730. this.iframe.onreadystatechange = function(){
  23731. if (self.iframe.readyState == 'complete') {
  23732. complete();
  23733. }
  23734. };
  23735. } else {
  23736. this.iframe.onload = complete;
  23737. }
  23738. };
  23739. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23740. },{"./polling":98,"component-inherit":101}],97:[function(require,module,exports){
  23741. (function (global){
  23742. /**
  23743. * Module requirements.
  23744. */
  23745. var XMLHttpRequest = require('xmlhttprequest');
  23746. var Polling = require('./polling');
  23747. var Emitter = require('component-emitter');
  23748. var inherit = require('component-inherit');
  23749. var debug = require('debug')('engine.io-client:polling-xhr');
  23750. /**
  23751. * Module exports.
  23752. */
  23753. module.exports = XHR;
  23754. module.exports.Request = Request;
  23755. /**
  23756. * Empty function
  23757. */
  23758. function empty(){}
  23759. /**
  23760. * XHR Polling constructor.
  23761. *
  23762. * @param {Object} opts
  23763. * @api public
  23764. */
  23765. function XHR(opts){
  23766. Polling.call(this, opts);
  23767. if (global.location) {
  23768. var isSSL = 'https:' == location.protocol;
  23769. var port = location.port;
  23770. // some user agents have empty `location.port`
  23771. if (!port) {
  23772. port = isSSL ? 443 : 80;
  23773. }
  23774. this.xd = opts.hostname != global.location.hostname ||
  23775. port != opts.port;
  23776. this.xs = opts.secure != isSSL;
  23777. }
  23778. }
  23779. /**
  23780. * Inherits from Polling.
  23781. */
  23782. inherit(XHR, Polling);
  23783. /**
  23784. * XHR supports binary
  23785. */
  23786. XHR.prototype.supportsBinary = true;
  23787. /**
  23788. * Creates a request.
  23789. *
  23790. * @param {String} method
  23791. * @api private
  23792. */
  23793. XHR.prototype.request = function(opts){
  23794. opts = opts || {};
  23795. opts.uri = this.uri();
  23796. opts.xd = this.xd;
  23797. opts.xs = this.xs;
  23798. opts.agent = this.agent || false;
  23799. opts.supportsBinary = this.supportsBinary;
  23800. opts.enablesXDR = this.enablesXDR;
  23801. // SSL options for Node.js client
  23802. opts.pfx = this.pfx;
  23803. opts.key = this.key;
  23804. opts.passphrase = this.passphrase;
  23805. opts.cert = this.cert;
  23806. opts.ca = this.ca;
  23807. opts.ciphers = this.ciphers;
  23808. opts.rejectUnauthorized = this.rejectUnauthorized;
  23809. return new Request(opts);
  23810. };
  23811. /**
  23812. * Sends data.
  23813. *
  23814. * @param {String} data to send.
  23815. * @param {Function} called upon flush.
  23816. * @api private
  23817. */
  23818. XHR.prototype.doWrite = function(data, fn){
  23819. var isBinary = typeof data !== 'string' && data !== undefined;
  23820. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  23821. var self = this;
  23822. req.on('success', fn);
  23823. req.on('error', function(err){
  23824. self.onError('xhr post error', err);
  23825. });
  23826. this.sendXhr = req;
  23827. };
  23828. /**
  23829. * Starts a poll cycle.
  23830. *
  23831. * @api private
  23832. */
  23833. XHR.prototype.doPoll = function(){
  23834. debug('xhr poll');
  23835. var req = this.request();
  23836. var self = this;
  23837. req.on('data', function(data){
  23838. self.onData(data);
  23839. });
  23840. req.on('error', function(err){
  23841. self.onError('xhr poll error', err);
  23842. });
  23843. this.pollXhr = req;
  23844. };
  23845. /**
  23846. * Request constructor
  23847. *
  23848. * @param {Object} options
  23849. * @api public
  23850. */
  23851. function Request(opts){
  23852. this.method = opts.method || 'GET';
  23853. this.uri = opts.uri;
  23854. this.xd = !!opts.xd;
  23855. this.xs = !!opts.xs;
  23856. this.async = false !== opts.async;
  23857. this.data = undefined != opts.data ? opts.data : null;
  23858. this.agent = opts.agent;
  23859. this.isBinary = opts.isBinary;
  23860. this.supportsBinary = opts.supportsBinary;
  23861. this.enablesXDR = opts.enablesXDR;
  23862. // SSL options for Node.js client
  23863. this.pfx = opts.pfx;
  23864. this.key = opts.key;
  23865. this.passphrase = opts.passphrase;
  23866. this.cert = opts.cert;
  23867. this.ca = opts.ca;
  23868. this.ciphers = opts.ciphers;
  23869. this.rejectUnauthorized = opts.rejectUnauthorized;
  23870. this.create();
  23871. }
  23872. /**
  23873. * Mix in `Emitter`.
  23874. */
  23875. Emitter(Request.prototype);
  23876. /**
  23877. * Creates the XHR object and sends the request.
  23878. *
  23879. * @api private
  23880. */
  23881. Request.prototype.create = function(){
  23882. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  23883. // SSL options for Node.js client
  23884. opts.pfx = this.pfx;
  23885. opts.key = this.key;
  23886. opts.passphrase = this.passphrase;
  23887. opts.cert = this.cert;
  23888. opts.ca = this.ca;
  23889. opts.ciphers = this.ciphers;
  23890. opts.rejectUnauthorized = this.rejectUnauthorized;
  23891. var xhr = this.xhr = new XMLHttpRequest(opts);
  23892. var self = this;
  23893. try {
  23894. debug('xhr open %s: %s', this.method, this.uri);
  23895. xhr.open(this.method, this.uri, this.async);
  23896. if (this.supportsBinary) {
  23897. // This has to be done after open because Firefox is stupid
  23898. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  23899. xhr.responseType = 'arraybuffer';
  23900. }
  23901. if ('POST' == this.method) {
  23902. try {
  23903. if (this.isBinary) {
  23904. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  23905. } else {
  23906. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  23907. }
  23908. } catch (e) {}
  23909. }
  23910. // ie6 check
  23911. if ('withCredentials' in xhr) {
  23912. xhr.withCredentials = true;
  23913. }
  23914. if (this.hasXDR()) {
  23915. xhr.onload = function(){
  23916. self.onLoad();
  23917. };
  23918. xhr.onerror = function(){
  23919. self.onError(xhr.responseText);
  23920. };
  23921. } else {
  23922. xhr.onreadystatechange = function(){
  23923. if (4 != xhr.readyState) return;
  23924. if (200 == xhr.status || 1223 == xhr.status) {
  23925. self.onLoad();
  23926. } else {
  23927. // make sure the `error` event handler that's user-set
  23928. // does not throw in the same tick and gets caught here
  23929. setTimeout(function(){
  23930. self.onError(xhr.status);
  23931. }, 0);
  23932. }
  23933. };
  23934. }
  23935. debug('xhr data %s', this.data);
  23936. xhr.send(this.data);
  23937. } catch (e) {
  23938. // Need to defer since .create() is called directly fhrom the constructor
  23939. // and thus the 'error' event can only be only bound *after* this exception
  23940. // occurs. Therefore, also, we cannot throw here at all.
  23941. setTimeout(function() {
  23942. self.onError(e);
  23943. }, 0);
  23944. return;
  23945. }
  23946. if (global.document) {
  23947. this.index = Request.requestsCount++;
  23948. Request.requests[this.index] = this;
  23949. }
  23950. };
  23951. /**
  23952. * Called upon successful response.
  23953. *
  23954. * @api private
  23955. */
  23956. Request.prototype.onSuccess = function(){
  23957. this.emit('success');
  23958. this.cleanup();
  23959. };
  23960. /**
  23961. * Called if we have data.
  23962. *
  23963. * @api private
  23964. */
  23965. Request.prototype.onData = function(data){
  23966. this.emit('data', data);
  23967. this.onSuccess();
  23968. };
  23969. /**
  23970. * Called upon error.
  23971. *
  23972. * @api private
  23973. */
  23974. Request.prototype.onError = function(err){
  23975. this.emit('error', err);
  23976. this.cleanup(true);
  23977. };
  23978. /**
  23979. * Cleans up house.
  23980. *
  23981. * @api private
  23982. */
  23983. Request.prototype.cleanup = function(fromError){
  23984. if ('undefined' == typeof this.xhr || null === this.xhr) {
  23985. return;
  23986. }
  23987. // xmlhttprequest
  23988. if (this.hasXDR()) {
  23989. this.xhr.onload = this.xhr.onerror = empty;
  23990. } else {
  23991. this.xhr.onreadystatechange = empty;
  23992. }
  23993. if (fromError) {
  23994. try {
  23995. this.xhr.abort();
  23996. } catch(e) {}
  23997. }
  23998. if (global.document) {
  23999. delete Request.requests[this.index];
  24000. }
  24001. this.xhr = null;
  24002. };
  24003. /**
  24004. * Called upon load.
  24005. *
  24006. * @api private
  24007. */
  24008. Request.prototype.onLoad = function(){
  24009. var data;
  24010. try {
  24011. var contentType;
  24012. try {
  24013. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  24014. } catch (e) {}
  24015. if (contentType === 'application/octet-stream') {
  24016. data = this.xhr.response;
  24017. } else {
  24018. if (!this.supportsBinary) {
  24019. data = this.xhr.responseText;
  24020. } else {
  24021. data = 'ok';
  24022. }
  24023. }
  24024. } catch (e) {
  24025. this.onError(e);
  24026. }
  24027. if (null != data) {
  24028. this.onData(data);
  24029. }
  24030. };
  24031. /**
  24032. * Check if it has XDomainRequest.
  24033. *
  24034. * @api private
  24035. */
  24036. Request.prototype.hasXDR = function(){
  24037. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  24038. };
  24039. /**
  24040. * Aborts the request.
  24041. *
  24042. * @api public
  24043. */
  24044. Request.prototype.abort = function(){
  24045. this.cleanup();
  24046. };
  24047. /**
  24048. * Aborts pending requests when unloading the window. This is needed to prevent
  24049. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  24050. * emitted.
  24051. */
  24052. if (global.document) {
  24053. Request.requestsCount = 0;
  24054. Request.requests = {};
  24055. if (global.attachEvent) {
  24056. global.attachEvent('onunload', unloadHandler);
  24057. } else if (global.addEventListener) {
  24058. global.addEventListener('beforeunload', unloadHandler, false);
  24059. }
  24060. }
  24061. function unloadHandler() {
  24062. for (var i in Request.requests) {
  24063. if (Request.requests.hasOwnProperty(i)) {
  24064. Request.requests[i].abort();
  24065. }
  24066. }
  24067. }
  24068. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  24069. },{"./polling":98,"component-emitter":89,"component-inherit":101,"debug":102,"xmlhttprequest":100}],98:[function(require,module,exports){
  24070. /**
  24071. * Module dependencies.
  24072. */
  24073. var Transport = require('../transport');
  24074. var parseqs = require('parseqs');
  24075. var parser = require('engine.io-parser');
  24076. var inherit = require('component-inherit');
  24077. var debug = require('debug')('engine.io-client:polling');
  24078. /**
  24079. * Module exports.
  24080. */
  24081. module.exports = Polling;
  24082. /**
  24083. * Is XHR2 supported?
  24084. */
  24085. var hasXHR2 = (function() {
  24086. var XMLHttpRequest = require('xmlhttprequest');
  24087. var xhr = new XMLHttpRequest({ xdomain: false });
  24088. return null != xhr.responseType;
  24089. })();
  24090. /**
  24091. * Polling interface.
  24092. *
  24093. * @param {Object} opts
  24094. * @api private
  24095. */
  24096. function Polling(opts){
  24097. var forceBase64 = (opts && opts.forceBase64);
  24098. if (!hasXHR2 || forceBase64) {
  24099. this.supportsBinary = false;
  24100. }
  24101. Transport.call(this, opts);
  24102. }
  24103. /**
  24104. * Inherits from Transport.
  24105. */
  24106. inherit(Polling, Transport);
  24107. /**
  24108. * Transport name.
  24109. */
  24110. Polling.prototype.name = 'polling';
  24111. /**
  24112. * Opens the socket (triggers polling). We write a PING message to determine
  24113. * when the transport is open.
  24114. *
  24115. * @api private
  24116. */
  24117. Polling.prototype.doOpen = function(){
  24118. this.poll();
  24119. };
  24120. /**
  24121. * Pauses polling.
  24122. *
  24123. * @param {Function} callback upon buffers are flushed and transport is paused
  24124. * @api private
  24125. */
  24126. Polling.prototype.pause = function(onPause){
  24127. var pending = 0;
  24128. var self = this;
  24129. this.readyState = 'pausing';
  24130. function pause(){
  24131. debug('paused');
  24132. self.readyState = 'paused';
  24133. onPause();
  24134. }
  24135. if (this.polling || !this.writable) {
  24136. var total = 0;
  24137. if (this.polling) {
  24138. debug('we are currently polling - waiting to pause');
  24139. total++;
  24140. this.once('pollComplete', function(){
  24141. debug('pre-pause polling complete');
  24142. --total || pause();
  24143. });
  24144. }
  24145. if (!this.writable) {
  24146. debug('we are currently writing - waiting to pause');
  24147. total++;
  24148. this.once('drain', function(){
  24149. debug('pre-pause writing complete');
  24150. --total || pause();
  24151. });
  24152. }
  24153. } else {
  24154. pause();
  24155. }
  24156. };
  24157. /**
  24158. * Starts polling cycle.
  24159. *
  24160. * @api public
  24161. */
  24162. Polling.prototype.poll = function(){
  24163. debug('polling');
  24164. this.polling = true;
  24165. this.doPoll();
  24166. this.emit('poll');
  24167. };
  24168. /**
  24169. * Overloads onData to detect payloads.
  24170. *
  24171. * @api private
  24172. */
  24173. Polling.prototype.onData = function(data){
  24174. var self = this;
  24175. debug('polling got data %s', data);
  24176. var callback = function(packet, index, total) {
  24177. // if its the first message we consider the transport open
  24178. if ('opening' == self.readyState) {
  24179. self.onOpen();
  24180. }
  24181. // if its a close packet, we close the ongoing requests
  24182. if ('close' == packet.type) {
  24183. self.onClose();
  24184. return false;
  24185. }
  24186. // otherwise bypass onData and handle the message
  24187. self.onPacket(packet);
  24188. };
  24189. // decode payload
  24190. parser.decodePayload(data, this.socket.binaryType, callback);
  24191. // if an event did not trigger closing
  24192. if ('closed' != this.readyState) {
  24193. // if we got data we're not polling
  24194. this.polling = false;
  24195. this.emit('pollComplete');
  24196. if ('open' == this.readyState) {
  24197. this.poll();
  24198. } else {
  24199. debug('ignoring poll - transport state "%s"', this.readyState);
  24200. }
  24201. }
  24202. };
  24203. /**
  24204. * For polling, send a close packet.
  24205. *
  24206. * @api private
  24207. */
  24208. Polling.prototype.doClose = function(){
  24209. var self = this;
  24210. function close(){
  24211. debug('writing close packet');
  24212. self.write([{ type: 'close' }]);
  24213. }
  24214. if ('open' == this.readyState) {
  24215. debug('transport open - closing');
  24216. close();
  24217. } else {
  24218. // in case we're trying to close while
  24219. // handshaking is in progress (GH-164)
  24220. debug('transport not open - deferring close');
  24221. this.once('open', close);
  24222. }
  24223. };
  24224. /**
  24225. * Writes a packets payload.
  24226. *
  24227. * @param {Array} data packets
  24228. * @param {Function} drain callback
  24229. * @api private
  24230. */
  24231. Polling.prototype.write = function(packets){
  24232. var self = this;
  24233. this.writable = false;
  24234. var callbackfn = function() {
  24235. self.writable = true;
  24236. self.emit('drain');
  24237. };
  24238. var self = this;
  24239. parser.encodePayload(packets, this.supportsBinary, function(data) {
  24240. self.doWrite(data, callbackfn);
  24241. });
  24242. };
  24243. /**
  24244. * Generates uri for connection.
  24245. *
  24246. * @api private
  24247. */
  24248. Polling.prototype.uri = function(){
  24249. var query = this.query || {};
  24250. var schema = this.secure ? 'https' : 'http';
  24251. var port = '';
  24252. // cache busting is forced
  24253. if (false !== this.timestampRequests) {
  24254. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  24255. }
  24256. if (!this.supportsBinary && !query.sid) {
  24257. query.b64 = 1;
  24258. }
  24259. query = parseqs.encode(query);
  24260. // avoid port if default for schema
  24261. if (this.port && (('https' == schema && this.port != 443) ||
  24262. ('http' == schema && this.port != 80))) {
  24263. port = ':' + this.port;
  24264. }
  24265. // prepend ? to query
  24266. if (query.length) {
  24267. query = '?' + query;
  24268. }
  24269. return schema + '://' + this.hostname + port + this.path + query;
  24270. };
  24271. },{"../transport":94,"component-inherit":101,"debug":102,"engine.io-parser":105,"parseqs":117,"xmlhttprequest":100}],99:[function(require,module,exports){
  24272. /**
  24273. * Module dependencies.
  24274. */
  24275. var Transport = require('../transport');
  24276. var parser = require('engine.io-parser');
  24277. var parseqs = require('parseqs');
  24278. var inherit = require('component-inherit');
  24279. var debug = require('debug')('engine.io-client:websocket');
  24280. /**
  24281. * `ws` exposes a WebSocket-compatible interface in
  24282. * Node, or the `WebSocket` or `MozWebSocket` globals
  24283. * in the browser.
  24284. */
  24285. var WebSocket = require('ws');
  24286. /**
  24287. * Module exports.
  24288. */
  24289. module.exports = WS;
  24290. /**
  24291. * WebSocket transport constructor.
  24292. *
  24293. * @api {Object} connection options
  24294. * @api public
  24295. */
  24296. function WS(opts){
  24297. var forceBase64 = (opts && opts.forceBase64);
  24298. if (forceBase64) {
  24299. this.supportsBinary = false;
  24300. }
  24301. Transport.call(this, opts);
  24302. }
  24303. /**
  24304. * Inherits from Transport.
  24305. */
  24306. inherit(WS, Transport);
  24307. /**
  24308. * Transport name.
  24309. *
  24310. * @api public
  24311. */
  24312. WS.prototype.name = 'websocket';
  24313. /*
  24314. * WebSockets support binary
  24315. */
  24316. WS.prototype.supportsBinary = true;
  24317. /**
  24318. * Opens socket.
  24319. *
  24320. * @api private
  24321. */
  24322. WS.prototype.doOpen = function(){
  24323. if (!this.check()) {
  24324. // let probe timeout
  24325. return;
  24326. }
  24327. var self = this;
  24328. var uri = this.uri();
  24329. var protocols = void(0);
  24330. var opts = { agent: this.agent };
  24331. // SSL options for Node.js client
  24332. opts.pfx = this.pfx;
  24333. opts.key = this.key;
  24334. opts.passphrase = this.passphrase;
  24335. opts.cert = this.cert;
  24336. opts.ca = this.ca;
  24337. opts.ciphers = this.ciphers;
  24338. opts.rejectUnauthorized = this.rejectUnauthorized;
  24339. this.ws = new WebSocket(uri, protocols, opts);
  24340. if (this.ws.binaryType === undefined) {
  24341. this.supportsBinary = false;
  24342. }
  24343. this.ws.binaryType = 'arraybuffer';
  24344. this.addEventListeners();
  24345. };
  24346. /**
  24347. * Adds event listeners to the socket
  24348. *
  24349. * @api private
  24350. */
  24351. WS.prototype.addEventListeners = function(){
  24352. var self = this;
  24353. this.ws.onopen = function(){
  24354. self.onOpen();
  24355. };
  24356. this.ws.onclose = function(){
  24357. self.onClose();
  24358. };
  24359. this.ws.onmessage = function(ev){
  24360. self.onData(ev.data);
  24361. };
  24362. this.ws.onerror = function(e){
  24363. self.onError('websocket error', e);
  24364. };
  24365. };
  24366. /**
  24367. * Override `onData` to use a timer on iOS.
  24368. * See: https://gist.github.com/mloughran/2052006
  24369. *
  24370. * @api private
  24371. */
  24372. if ('undefined' != typeof navigator
  24373. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  24374. WS.prototype.onData = function(data){
  24375. var self = this;
  24376. setTimeout(function(){
  24377. Transport.prototype.onData.call(self, data);
  24378. }, 0);
  24379. };
  24380. }
  24381. /**
  24382. * Writes data to socket.
  24383. *
  24384. * @param {Array} array of packets.
  24385. * @api private
  24386. */
  24387. WS.prototype.write = function(packets){
  24388. var self = this;
  24389. this.writable = false;
  24390. // encodePacket efficient as it uses WS framing
  24391. // no need for encodePayload
  24392. for (var i = 0, l = packets.length; i < l; i++) {
  24393. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  24394. //Sometimes the websocket has already been closed but the browser didn't
  24395. //have a chance of informing us about it yet, in that case send will
  24396. //throw an error
  24397. try {
  24398. self.ws.send(data);
  24399. } catch (e){
  24400. debug('websocket closed before onclose event');
  24401. }
  24402. });
  24403. }
  24404. function ondrain() {
  24405. self.writable = true;
  24406. self.emit('drain');
  24407. }
  24408. // fake drain
  24409. // defer to next tick to allow Socket to clear writeBuffer
  24410. setTimeout(ondrain, 0);
  24411. };
  24412. /**
  24413. * Called upon close
  24414. *
  24415. * @api private
  24416. */
  24417. WS.prototype.onClose = function(){
  24418. Transport.prototype.onClose.call(this);
  24419. };
  24420. /**
  24421. * Closes socket.
  24422. *
  24423. * @api private
  24424. */
  24425. WS.prototype.doClose = function(){
  24426. if (typeof this.ws !== 'undefined') {
  24427. this.ws.close();
  24428. }
  24429. };
  24430. /**
  24431. * Generates uri for connection.
  24432. *
  24433. * @api private
  24434. */
  24435. WS.prototype.uri = function(){
  24436. var query = this.query || {};
  24437. var schema = this.secure ? 'wss' : 'ws';
  24438. var port = '';
  24439. // avoid port if default for schema
  24440. if (this.port && (('wss' == schema && this.port != 443)
  24441. || ('ws' == schema && this.port != 80))) {
  24442. port = ':' + this.port;
  24443. }
  24444. // append timestamp to URI
  24445. if (this.timestampRequests) {
  24446. query[this.timestampParam] = +new Date;
  24447. }
  24448. // communicate binary support capabilities
  24449. if (!this.supportsBinary) {
  24450. query.b64 = 1;
  24451. }
  24452. query = parseqs.encode(query);
  24453. // prepend ? to query
  24454. if (query.length) {
  24455. query = '?' + query;
  24456. }
  24457. return schema + '://' + this.hostname + port + this.path + query;
  24458. };
  24459. /**
  24460. * Feature detection for WebSocket.
  24461. *
  24462. * @return {Boolean} whether this transport is available.
  24463. * @api public
  24464. */
  24465. WS.prototype.check = function(){
  24466. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  24467. };
  24468. },{"../transport":94,"component-inherit":101,"debug":102,"engine.io-parser":105,"parseqs":117,"ws":119}],100:[function(require,module,exports){
  24469. // browser shim for xmlhttprequest module
  24470. var hasCORS = require('has-cors');
  24471. module.exports = function(opts) {
  24472. var xdomain = opts.xdomain;
  24473. // scheme must be same when usign XDomainRequest
  24474. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  24475. var xscheme = opts.xscheme;
  24476. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  24477. // https://github.com/Automattic/engine.io-client/pull/217
  24478. var enablesXDR = opts.enablesXDR;
  24479. // XMLHttpRequest can be disabled on IE
  24480. try {
  24481. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  24482. return new XMLHttpRequest();
  24483. }
  24484. } catch (e) { }
  24485. // Use XDomainRequest for IE8 if enablesXDR is true
  24486. // because loading bar keeps flashing when using jsonp-polling
  24487. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  24488. try {
  24489. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  24490. return new XDomainRequest();
  24491. }
  24492. } catch (e) { }
  24493. if (!xdomain) {
  24494. try {
  24495. return new ActiveXObject('Microsoft.XMLHTTP');
  24496. } catch(e) { }
  24497. }
  24498. }
  24499. },{"has-cors":114}],101:[function(require,module,exports){
  24500. module.exports = function(a, b){
  24501. var fn = function(){};
  24502. fn.prototype = b.prototype;
  24503. a.prototype = new fn;
  24504. a.prototype.constructor = a;
  24505. };
  24506. },{}],102:[function(require,module,exports){
  24507. /**
  24508. * This is the web browser implementation of `debug()`.
  24509. *
  24510. * Expose `debug()` as the module.
  24511. */
  24512. exports = module.exports = require('./debug');
  24513. exports.log = log;
  24514. exports.formatArgs = formatArgs;
  24515. exports.save = save;
  24516. exports.load = load;
  24517. exports.useColors = useColors;
  24518. /**
  24519. * Colors.
  24520. */
  24521. exports.colors = [
  24522. 'lightseagreen',
  24523. 'forestgreen',
  24524. 'goldenrod',
  24525. 'dodgerblue',
  24526. 'darkorchid',
  24527. 'crimson'
  24528. ];
  24529. /**
  24530. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  24531. * and the Firebug extension (any Firefox version) are known
  24532. * to support "%c" CSS customizations.
  24533. *
  24534. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  24535. */
  24536. function useColors() {
  24537. // is webkit? http://stackoverflow.com/a/16459606/376773
  24538. return ('WebkitAppearance' in document.documentElement.style) ||
  24539. // is firebug? http://stackoverflow.com/a/398120/376773
  24540. (window.console && (console.firebug || (console.exception && console.table))) ||
  24541. // is firefox >= v31?
  24542. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  24543. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  24544. }
  24545. /**
  24546. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  24547. */
  24548. exports.formatters.j = function(v) {
  24549. return JSON.stringify(v);
  24550. };
  24551. /**
  24552. * Colorize log arguments if enabled.
  24553. *
  24554. * @api public
  24555. */
  24556. function formatArgs() {
  24557. var args = arguments;
  24558. var useColors = this.useColors;
  24559. args[0] = (useColors ? '%c' : '')
  24560. + this.namespace
  24561. + (useColors ? ' %c' : ' ')
  24562. + args[0]
  24563. + (useColors ? '%c ' : ' ')
  24564. + '+' + exports.humanize(this.diff);
  24565. if (!useColors) return args;
  24566. var c = 'color: ' + this.color;
  24567. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  24568. // the final "%c" is somewhat tricky, because there could be other
  24569. // arguments passed either before or after the %c, so we need to
  24570. // figure out the correct index to insert the CSS into
  24571. var index = 0;
  24572. var lastC = 0;
  24573. args[0].replace(/%[a-z%]/g, function(match) {
  24574. if ('%%' === match) return;
  24575. index++;
  24576. if ('%c' === match) {
  24577. // we only are interested in the *last* %c
  24578. // (the user may have provided their own)
  24579. lastC = index;
  24580. }
  24581. });
  24582. args.splice(lastC, 0, c);
  24583. return args;
  24584. }
  24585. /**
  24586. * Invokes `console.log()` when available.
  24587. * No-op when `console.log` is not a "function".
  24588. *
  24589. * @api public
  24590. */
  24591. function log() {
  24592. // This hackery is required for IE8,
  24593. // where the `console.log` function doesn't have 'apply'
  24594. return 'object' == typeof console
  24595. && 'function' == typeof console.log
  24596. && Function.prototype.apply.call(console.log, console, arguments);
  24597. }
  24598. /**
  24599. * Save `namespaces`.
  24600. *
  24601. * @param {String} namespaces
  24602. * @api private
  24603. */
  24604. function save(namespaces) {
  24605. try {
  24606. if (null == namespaces) {
  24607. localStorage.removeItem('debug');
  24608. } else {
  24609. localStorage.debug = namespaces;
  24610. }
  24611. } catch(e) {}
  24612. }
  24613. /**
  24614. * Load `namespaces`.
  24615. *
  24616. * @return {String} returns the previously persisted debug modes
  24617. * @api private
  24618. */
  24619. function load() {
  24620. var r;
  24621. try {
  24622. r = localStorage.debug;
  24623. } catch(e) {}
  24624. return r;
  24625. }
  24626. /**
  24627. * Enable namespaces listed in `localStorage.debug` initially.
  24628. */
  24629. exports.enable(load());
  24630. },{"./debug":103}],103:[function(require,module,exports){
  24631. /**
  24632. * This is the common logic for both the Node.js and web browser
  24633. * implementations of `debug()`.
  24634. *
  24635. * Expose `debug()` as the module.
  24636. */
  24637. exports = module.exports = debug;
  24638. exports.coerce = coerce;
  24639. exports.disable = disable;
  24640. exports.enable = enable;
  24641. exports.enabled = enabled;
  24642. exports.humanize = require('ms');
  24643. /**
  24644. * The currently active debug mode names, and names to skip.
  24645. */
  24646. exports.names = [];
  24647. exports.skips = [];
  24648. /**
  24649. * Map of special "%n" handling functions, for the debug "format" argument.
  24650. *
  24651. * Valid key names are a single, lowercased letter, i.e. "n".
  24652. */
  24653. exports.formatters = {};
  24654. /**
  24655. * Previously assigned color.
  24656. */
  24657. var prevColor = 0;
  24658. /**
  24659. * Previous log timestamp.
  24660. */
  24661. var prevTime;
  24662. /**
  24663. * Select a color.
  24664. *
  24665. * @return {Number}
  24666. * @api private
  24667. */
  24668. function selectColor() {
  24669. return exports.colors[prevColor++ % exports.colors.length];
  24670. }
  24671. /**
  24672. * Create a debugger with the given `namespace`.
  24673. *
  24674. * @param {String} namespace
  24675. * @return {Function}
  24676. * @api public
  24677. */
  24678. function debug(namespace) {
  24679. // define the `disabled` version
  24680. function disabled() {
  24681. }
  24682. disabled.enabled = false;
  24683. // define the `enabled` version
  24684. function enabled() {
  24685. var self = enabled;
  24686. // set `diff` timestamp
  24687. var curr = +new Date();
  24688. var ms = curr - (prevTime || curr);
  24689. self.diff = ms;
  24690. self.prev = prevTime;
  24691. self.curr = curr;
  24692. prevTime = curr;
  24693. // add the `color` if not set
  24694. if (null == self.useColors) self.useColors = exports.useColors();
  24695. if (null == self.color && self.useColors) self.color = selectColor();
  24696. var args = Array.prototype.slice.call(arguments);
  24697. args[0] = exports.coerce(args[0]);
  24698. if ('string' !== typeof args[0]) {
  24699. // anything else let's inspect with %o
  24700. args = ['%o'].concat(args);
  24701. }
  24702. // apply any `formatters` transformations
  24703. var index = 0;
  24704. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  24705. // if we encounter an escaped % then don't increase the array index
  24706. if (match === '%%') return match;
  24707. index++;
  24708. var formatter = exports.formatters[format];
  24709. if ('function' === typeof formatter) {
  24710. var val = args[index];
  24711. match = formatter.call(self, val);
  24712. // now we need to remove `args[index]` since it's inlined in the `format`
  24713. args.splice(index, 1);
  24714. index--;
  24715. }
  24716. return match;
  24717. });
  24718. if ('function' === typeof exports.formatArgs) {
  24719. args = exports.formatArgs.apply(self, args);
  24720. }
  24721. var logFn = enabled.log || exports.log || console.log.bind(console);
  24722. logFn.apply(self, args);
  24723. }
  24724. enabled.enabled = true;
  24725. var fn = exports.enabled(namespace) ? enabled : disabled;
  24726. fn.namespace = namespace;
  24727. return fn;
  24728. }
  24729. /**
  24730. * Enables a debug mode by namespaces. This can include modes
  24731. * separated by a colon and wildcards.
  24732. *
  24733. * @param {String} namespaces
  24734. * @api public
  24735. */
  24736. function enable(namespaces) {
  24737. exports.save(namespaces);
  24738. var split = (namespaces || '').split(/[\s,]+/);
  24739. var len = split.length;
  24740. for (var i = 0; i < len; i++) {
  24741. if (!split[i]) continue; // ignore empty strings
  24742. namespaces = split[i].replace(/\*/g, '.*?');
  24743. if (namespaces[0] === '-') {
  24744. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  24745. } else {
  24746. exports.names.push(new RegExp('^' + namespaces + '$'));
  24747. }
  24748. }
  24749. }
  24750. /**
  24751. * Disable debug output.
  24752. *
  24753. * @api public
  24754. */
  24755. function disable() {
  24756. exports.enable('');
  24757. }
  24758. /**
  24759. * Returns true if the given mode name is enabled, false otherwise.
  24760. *
  24761. * @param {String} name
  24762. * @return {Boolean}
  24763. * @api public
  24764. */
  24765. function enabled(name) {
  24766. var i, len;
  24767. for (i = 0, len = exports.skips.length; i < len; i++) {
  24768. if (exports.skips[i].test(name)) {
  24769. return false;
  24770. }
  24771. }
  24772. for (i = 0, len = exports.names.length; i < len; i++) {
  24773. if (exports.names[i].test(name)) {
  24774. return true;
  24775. }
  24776. }
  24777. return false;
  24778. }
  24779. /**
  24780. * Coerce `val`.
  24781. *
  24782. * @param {Mixed} val
  24783. * @return {Mixed}
  24784. * @api private
  24785. */
  24786. function coerce(val) {
  24787. if (val instanceof Error) return val.stack || val.message;
  24788. return val;
  24789. }
  24790. },{"ms":104}],104:[function(require,module,exports){
  24791. /**
  24792. * Helpers.
  24793. */
  24794. var s = 1000;
  24795. var m = s * 60;
  24796. var h = m * 60;
  24797. var d = h * 24;
  24798. var y = d * 365.25;
  24799. /**
  24800. * Parse or format the given `val`.
  24801. *
  24802. * Options:
  24803. *
  24804. * - `long` verbose formatting [false]
  24805. *
  24806. * @param {String|Number} val
  24807. * @param {Object} options
  24808. * @return {String|Number}
  24809. * @api public
  24810. */
  24811. module.exports = function(val, options){
  24812. options = options || {};
  24813. if ('string' == typeof val) return parse(val);
  24814. return options.long
  24815. ? long(val)
  24816. : short(val);
  24817. };
  24818. /**
  24819. * Parse the given `str` and return milliseconds.
  24820. *
  24821. * @param {String} str
  24822. * @return {Number}
  24823. * @api private
  24824. */
  24825. function parse(str) {
  24826. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  24827. if (!match) return;
  24828. var n = parseFloat(match[1]);
  24829. var type = (match[2] || 'ms').toLowerCase();
  24830. switch (type) {
  24831. case 'years':
  24832. case 'year':
  24833. case 'y':
  24834. return n * y;
  24835. case 'days':
  24836. case 'day':
  24837. case 'd':
  24838. return n * d;
  24839. case 'hours':
  24840. case 'hour':
  24841. case 'h':
  24842. return n * h;
  24843. case 'minutes':
  24844. case 'minute':
  24845. case 'm':
  24846. return n * m;
  24847. case 'seconds':
  24848. case 'second':
  24849. case 's':
  24850. return n * s;
  24851. case 'ms':
  24852. return n;
  24853. }
  24854. }
  24855. /**
  24856. * Short format for `ms`.
  24857. *
  24858. * @param {Number} ms
  24859. * @return {String}
  24860. * @api private
  24861. */
  24862. function short(ms) {
  24863. if (ms >= d) return Math.round(ms / d) + 'd';
  24864. if (ms >= h) return Math.round(ms / h) + 'h';
  24865. if (ms >= m) return Math.round(ms / m) + 'm';
  24866. if (ms >= s) return Math.round(ms / s) + 's';
  24867. return ms + 'ms';
  24868. }
  24869. /**
  24870. * Long format for `ms`.
  24871. *
  24872. * @param {Number} ms
  24873. * @return {String}
  24874. * @api private
  24875. */
  24876. function long(ms) {
  24877. return plural(ms, d, 'day')
  24878. || plural(ms, h, 'hour')
  24879. || plural(ms, m, 'minute')
  24880. || plural(ms, s, 'second')
  24881. || ms + ' ms';
  24882. }
  24883. /**
  24884. * Pluralization helper.
  24885. */
  24886. function plural(ms, n, name) {
  24887. if (ms < n) return;
  24888. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  24889. return Math.ceil(ms / n) + ' ' + name + 's';
  24890. }
  24891. },{}],105:[function(require,module,exports){
  24892. (function (global){
  24893. /**
  24894. * Module dependencies.
  24895. */
  24896. var keys = require('./keys');
  24897. var hasBinary = require('has-binary');
  24898. var sliceBuffer = require('arraybuffer.slice');
  24899. var base64encoder = require('base64-arraybuffer');
  24900. var after = require('after');
  24901. var utf8 = require('utf8');
  24902. /**
  24903. * Check if we are running an android browser. That requires us to use
  24904. * ArrayBuffer with polling transports...
  24905. *
  24906. * http://ghinda.net/jpeg-blob-ajax-android/
  24907. */
  24908. var isAndroid = navigator.userAgent.match(/Android/i);
  24909. /**
  24910. * Check if we are running in PhantomJS.
  24911. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  24912. * https://github.com/ariya/phantomjs/issues/11395
  24913. * @type boolean
  24914. */
  24915. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  24916. /**
  24917. * When true, avoids using Blobs to encode payloads.
  24918. * @type boolean
  24919. */
  24920. var dontSendBlobs = isAndroid || isPhantomJS;
  24921. /**
  24922. * Current protocol version.
  24923. */
  24924. exports.protocol = 3;
  24925. /**
  24926. * Packet types.
  24927. */
  24928. var packets = exports.packets = {
  24929. open: 0 // non-ws
  24930. , close: 1 // non-ws
  24931. , ping: 2
  24932. , pong: 3
  24933. , message: 4
  24934. , upgrade: 5
  24935. , noop: 6
  24936. };
  24937. var packetslist = keys(packets);
  24938. /**
  24939. * Premade error packet.
  24940. */
  24941. var err = { type: 'error', data: 'parser error' };
  24942. /**
  24943. * Create a blob api even for blob builder when vendor prefixes exist
  24944. */
  24945. var Blob = require('blob');
  24946. /**
  24947. * Encodes a packet.
  24948. *
  24949. * <packet type id> [ <data> ]
  24950. *
  24951. * Example:
  24952. *
  24953. * 5hello world
  24954. * 3
  24955. * 4
  24956. *
  24957. * Binary is encoded in an identical principle
  24958. *
  24959. * @api private
  24960. */
  24961. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  24962. if ('function' == typeof supportsBinary) {
  24963. callback = supportsBinary;
  24964. supportsBinary = false;
  24965. }
  24966. if ('function' == typeof utf8encode) {
  24967. callback = utf8encode;
  24968. utf8encode = null;
  24969. }
  24970. var data = (packet.data === undefined)
  24971. ? undefined
  24972. : packet.data.buffer || packet.data;
  24973. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  24974. return encodeArrayBuffer(packet, supportsBinary, callback);
  24975. } else if (Blob && data instanceof global.Blob) {
  24976. return encodeBlob(packet, supportsBinary, callback);
  24977. }
  24978. // might be an object with { base64: true, data: dataAsBase64String }
  24979. if (data && data.base64) {
  24980. return encodeBase64Object(packet, callback);
  24981. }
  24982. // Sending data as a utf-8 string
  24983. var encoded = packets[packet.type];
  24984. // data fragment is optional
  24985. if (undefined !== packet.data) {
  24986. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  24987. }
  24988. return callback('' + encoded);
  24989. };
  24990. function encodeBase64Object(packet, callback) {
  24991. // packet data is an object { base64: true, data: dataAsBase64String }
  24992. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  24993. return callback(message);
  24994. }
  24995. /**
  24996. * Encode packet helpers for binary types
  24997. */
  24998. function encodeArrayBuffer(packet, supportsBinary, callback) {
  24999. if (!supportsBinary) {
  25000. return exports.encodeBase64Packet(packet, callback);
  25001. }
  25002. var data = packet.data;
  25003. var contentArray = new Uint8Array(data);
  25004. var resultBuffer = new Uint8Array(1 + data.byteLength);
  25005. resultBuffer[0] = packets[packet.type];
  25006. for (var i = 0; i < contentArray.length; i++) {
  25007. resultBuffer[i+1] = contentArray[i];
  25008. }
  25009. return callback(resultBuffer.buffer);
  25010. }
  25011. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  25012. if (!supportsBinary) {
  25013. return exports.encodeBase64Packet(packet, callback);
  25014. }
  25015. var fr = new FileReader();
  25016. fr.onload = function() {
  25017. packet.data = fr.result;
  25018. exports.encodePacket(packet, supportsBinary, true, callback);
  25019. };
  25020. return fr.readAsArrayBuffer(packet.data);
  25021. }
  25022. function encodeBlob(packet, supportsBinary, callback) {
  25023. if (!supportsBinary) {
  25024. return exports.encodeBase64Packet(packet, callback);
  25025. }
  25026. if (dontSendBlobs) {
  25027. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  25028. }
  25029. var length = new Uint8Array(1);
  25030. length[0] = packets[packet.type];
  25031. var blob = new Blob([length.buffer, packet.data]);
  25032. return callback(blob);
  25033. }
  25034. /**
  25035. * Encodes a packet with binary data in a base64 string
  25036. *
  25037. * @param {Object} packet, has `type` and `data`
  25038. * @return {String} base64 encoded message
  25039. */
  25040. exports.encodeBase64Packet = function(packet, callback) {
  25041. var message = 'b' + exports.packets[packet.type];
  25042. if (Blob && packet.data instanceof Blob) {
  25043. var fr = new FileReader();
  25044. fr.onload = function() {
  25045. var b64 = fr.result.split(',')[1];
  25046. callback(message + b64);
  25047. };
  25048. return fr.readAsDataURL(packet.data);
  25049. }
  25050. var b64data;
  25051. try {
  25052. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  25053. } catch (e) {
  25054. // iPhone Safari doesn't let you apply with typed arrays
  25055. var typed = new Uint8Array(packet.data);
  25056. var basic = new Array(typed.length);
  25057. for (var i = 0; i < typed.length; i++) {
  25058. basic[i] = typed[i];
  25059. }
  25060. b64data = String.fromCharCode.apply(null, basic);
  25061. }
  25062. message += global.btoa(b64data);
  25063. return callback(message);
  25064. };
  25065. /**
  25066. * Decodes a packet. Changes format to Blob if requested.
  25067. *
  25068. * @return {Object} with `type` and `data` (if any)
  25069. * @api private
  25070. */
  25071. exports.decodePacket = function (data, binaryType, utf8decode) {
  25072. // String data
  25073. if (typeof data == 'string' || data === undefined) {
  25074. if (data.charAt(0) == 'b') {
  25075. return exports.decodeBase64Packet(data.substr(1), binaryType);
  25076. }
  25077. if (utf8decode) {
  25078. try {
  25079. data = utf8.decode(data);
  25080. } catch (e) {
  25081. return err;
  25082. }
  25083. }
  25084. var type = data.charAt(0);
  25085. if (Number(type) != type || !packetslist[type]) {
  25086. return err;
  25087. }
  25088. if (data.length > 1) {
  25089. return { type: packetslist[type], data: data.substring(1) };
  25090. } else {
  25091. return { type: packetslist[type] };
  25092. }
  25093. }
  25094. var asArray = new Uint8Array(data);
  25095. var type = asArray[0];
  25096. var rest = sliceBuffer(data, 1);
  25097. if (Blob && binaryType === 'blob') {
  25098. rest = new Blob([rest]);
  25099. }
  25100. return { type: packetslist[type], data: rest };
  25101. };
  25102. /**
  25103. * Decodes a packet encoded in a base64 string
  25104. *
  25105. * @param {String} base64 encoded message
  25106. * @return {Object} with `type` and `data` (if any)
  25107. */
  25108. exports.decodeBase64Packet = function(msg, binaryType) {
  25109. var type = packetslist[msg.charAt(0)];
  25110. if (!global.ArrayBuffer) {
  25111. return { type: type, data: { base64: true, data: msg.substr(1) } };
  25112. }
  25113. var data = base64encoder.decode(msg.substr(1));
  25114. if (binaryType === 'blob' && Blob) {
  25115. data = new Blob([data]);
  25116. }
  25117. return { type: type, data: data };
  25118. };
  25119. /**
  25120. * Encodes multiple messages (payload).
  25121. *
  25122. * <length>:data
  25123. *
  25124. * Example:
  25125. *
  25126. * 11:hello world2:hi
  25127. *
  25128. * If any contents are binary, they will be encoded as base64 strings. Base64
  25129. * encoded strings are marked with a b before the length specifier
  25130. *
  25131. * @param {Array} packets
  25132. * @api private
  25133. */
  25134. exports.encodePayload = function (packets, supportsBinary, callback) {
  25135. if (typeof supportsBinary == 'function') {
  25136. callback = supportsBinary;
  25137. supportsBinary = null;
  25138. }
  25139. var isBinary = hasBinary(packets);
  25140. if (supportsBinary && isBinary) {
  25141. if (Blob && !dontSendBlobs) {
  25142. return exports.encodePayloadAsBlob(packets, callback);
  25143. }
  25144. return exports.encodePayloadAsArrayBuffer(packets, callback);
  25145. }
  25146. if (!packets.length) {
  25147. return callback('0:');
  25148. }
  25149. function setLengthHeader(message) {
  25150. return message.length + ':' + message;
  25151. }
  25152. function encodeOne(packet, doneCallback) {
  25153. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  25154. doneCallback(null, setLengthHeader(message));
  25155. });
  25156. }
  25157. map(packets, encodeOne, function(err, results) {
  25158. return callback(results.join(''));
  25159. });
  25160. };
  25161. /**
  25162. * Async array map using after
  25163. */
  25164. function map(ary, each, done) {
  25165. var result = new Array(ary.length);
  25166. var next = after(ary.length, done);
  25167. var eachWithIndex = function(i, el, cb) {
  25168. each(el, function(error, msg) {
  25169. result[i] = msg;
  25170. cb(error, result);
  25171. });
  25172. };
  25173. for (var i = 0; i < ary.length; i++) {
  25174. eachWithIndex(i, ary[i], next);
  25175. }
  25176. }
  25177. /*
  25178. * Decodes data when a payload is maybe expected. Possible binary contents are
  25179. * decoded from their base64 representation
  25180. *
  25181. * @param {String} data, callback method
  25182. * @api public
  25183. */
  25184. exports.decodePayload = function (data, binaryType, callback) {
  25185. if (typeof data != 'string') {
  25186. return exports.decodePayloadAsBinary(data, binaryType, callback);
  25187. }
  25188. if (typeof binaryType === 'function') {
  25189. callback = binaryType;
  25190. binaryType = null;
  25191. }
  25192. var packet;
  25193. if (data == '') {
  25194. // parser error - ignoring payload
  25195. return callback(err, 0, 1);
  25196. }
  25197. var length = ''
  25198. , n, msg;
  25199. for (var i = 0, l = data.length; i < l; i++) {
  25200. var chr = data.charAt(i);
  25201. if (':' != chr) {
  25202. length += chr;
  25203. } else {
  25204. if ('' == length || (length != (n = Number(length)))) {
  25205. // parser error - ignoring payload
  25206. return callback(err, 0, 1);
  25207. }
  25208. msg = data.substr(i + 1, n);
  25209. if (length != msg.length) {
  25210. // parser error - ignoring payload
  25211. return callback(err, 0, 1);
  25212. }
  25213. if (msg.length) {
  25214. packet = exports.decodePacket(msg, binaryType, true);
  25215. if (err.type == packet.type && err.data == packet.data) {
  25216. // parser error in individual packet - ignoring payload
  25217. return callback(err, 0, 1);
  25218. }
  25219. var ret = callback(packet, i + n, l);
  25220. if (false === ret) return;
  25221. }
  25222. // advance cursor
  25223. i += n;
  25224. length = '';
  25225. }
  25226. }
  25227. if (length != '') {
  25228. // parser error - ignoring payload
  25229. return callback(err, 0, 1);
  25230. }
  25231. };
  25232. /**
  25233. * Encodes multiple messages (payload) as binary.
  25234. *
  25235. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  25236. * 255><data>
  25237. *
  25238. * Example:
  25239. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  25240. *
  25241. * @param {Array} packets
  25242. * @return {ArrayBuffer} encoded payload
  25243. * @api private
  25244. */
  25245. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  25246. if (!packets.length) {
  25247. return callback(new ArrayBuffer(0));
  25248. }
  25249. function encodeOne(packet, doneCallback) {
  25250. exports.encodePacket(packet, true, true, function(data) {
  25251. return doneCallback(null, data);
  25252. });
  25253. }
  25254. map(packets, encodeOne, function(err, encodedPackets) {
  25255. var totalLength = encodedPackets.reduce(function(acc, p) {
  25256. var len;
  25257. if (typeof p === 'string'){
  25258. len = p.length;
  25259. } else {
  25260. len = p.byteLength;
  25261. }
  25262. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  25263. }, 0);
  25264. var resultArray = new Uint8Array(totalLength);
  25265. var bufferIndex = 0;
  25266. encodedPackets.forEach(function(p) {
  25267. var isString = typeof p === 'string';
  25268. var ab = p;
  25269. if (isString) {
  25270. var view = new Uint8Array(p.length);
  25271. for (var i = 0; i < p.length; i++) {
  25272. view[i] = p.charCodeAt(i);
  25273. }
  25274. ab = view.buffer;
  25275. }
  25276. if (isString) { // not true binary
  25277. resultArray[bufferIndex++] = 0;
  25278. } else { // true binary
  25279. resultArray[bufferIndex++] = 1;
  25280. }
  25281. var lenStr = ab.byteLength.toString();
  25282. for (var i = 0; i < lenStr.length; i++) {
  25283. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  25284. }
  25285. resultArray[bufferIndex++] = 255;
  25286. var view = new Uint8Array(ab);
  25287. for (var i = 0; i < view.length; i++) {
  25288. resultArray[bufferIndex++] = view[i];
  25289. }
  25290. });
  25291. return callback(resultArray.buffer);
  25292. });
  25293. };
  25294. /**
  25295. * Encode as Blob
  25296. */
  25297. exports.encodePayloadAsBlob = function(packets, callback) {
  25298. function encodeOne(packet, doneCallback) {
  25299. exports.encodePacket(packet, true, true, function(encoded) {
  25300. var binaryIdentifier = new Uint8Array(1);
  25301. binaryIdentifier[0] = 1;
  25302. if (typeof encoded === 'string') {
  25303. var view = new Uint8Array(encoded.length);
  25304. for (var i = 0; i < encoded.length; i++) {
  25305. view[i] = encoded.charCodeAt(i);
  25306. }
  25307. encoded = view.buffer;
  25308. binaryIdentifier[0] = 0;
  25309. }
  25310. var len = (encoded instanceof ArrayBuffer)
  25311. ? encoded.byteLength
  25312. : encoded.size;
  25313. var lenStr = len.toString();
  25314. var lengthAry = new Uint8Array(lenStr.length + 1);
  25315. for (var i = 0; i < lenStr.length; i++) {
  25316. lengthAry[i] = parseInt(lenStr[i]);
  25317. }
  25318. lengthAry[lenStr.length] = 255;
  25319. if (Blob) {
  25320. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  25321. doneCallback(null, blob);
  25322. }
  25323. });
  25324. }
  25325. map(packets, encodeOne, function(err, results) {
  25326. return callback(new Blob(results));
  25327. });
  25328. };
  25329. /*
  25330. * Decodes data when a payload is maybe expected. Strings are decoded by
  25331. * interpreting each byte as a key code for entries marked to start with 0. See
  25332. * description of encodePayloadAsBinary
  25333. *
  25334. * @param {ArrayBuffer} data, callback method
  25335. * @api public
  25336. */
  25337. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  25338. if (typeof binaryType === 'function') {
  25339. callback = binaryType;
  25340. binaryType = null;
  25341. }
  25342. var bufferTail = data;
  25343. var buffers = [];
  25344. var numberTooLong = false;
  25345. while (bufferTail.byteLength > 0) {
  25346. var tailArray = new Uint8Array(bufferTail);
  25347. var isString = tailArray[0] === 0;
  25348. var msgLength = '';
  25349. for (var i = 1; ; i++) {
  25350. if (tailArray[i] == 255) break;
  25351. if (msgLength.length > 310) {
  25352. numberTooLong = true;
  25353. break;
  25354. }
  25355. msgLength += tailArray[i];
  25356. }
  25357. if(numberTooLong) return callback(err, 0, 1);
  25358. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  25359. msgLength = parseInt(msgLength);
  25360. var msg = sliceBuffer(bufferTail, 0, msgLength);
  25361. if (isString) {
  25362. try {
  25363. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  25364. } catch (e) {
  25365. // iPhone Safari doesn't let you apply to typed arrays
  25366. var typed = new Uint8Array(msg);
  25367. msg = '';
  25368. for (var i = 0; i < typed.length; i++) {
  25369. msg += String.fromCharCode(typed[i]);
  25370. }
  25371. }
  25372. }
  25373. buffers.push(msg);
  25374. bufferTail = sliceBuffer(bufferTail, msgLength);
  25375. }
  25376. var total = buffers.length;
  25377. buffers.forEach(function(buffer, i) {
  25378. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  25379. });
  25380. };
  25381. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25382. },{"./keys":106,"after":107,"arraybuffer.slice":108,"base64-arraybuffer":109,"blob":110,"has-binary":111,"utf8":113}],106:[function(require,module,exports){
  25383. /**
  25384. * Gets the keys for an object.
  25385. *
  25386. * @return {Array} keys
  25387. * @api private
  25388. */
  25389. module.exports = Object.keys || function keys (obj){
  25390. var arr = [];
  25391. var has = Object.prototype.hasOwnProperty;
  25392. for (var i in obj) {
  25393. if (has.call(obj, i)) {
  25394. arr.push(i);
  25395. }
  25396. }
  25397. return arr;
  25398. };
  25399. },{}],107:[function(require,module,exports){
  25400. module.exports = after
  25401. function after(count, callback, err_cb) {
  25402. var bail = false
  25403. err_cb = err_cb || noop
  25404. proxy.count = count
  25405. return (count === 0) ? callback() : proxy
  25406. function proxy(err, result) {
  25407. if (proxy.count <= 0) {
  25408. throw new Error('after called too many times')
  25409. }
  25410. --proxy.count
  25411. // after first error, rest are passed to err_cb
  25412. if (err) {
  25413. bail = true
  25414. callback(err)
  25415. // future error callbacks will go to error handler
  25416. callback = err_cb
  25417. } else if (proxy.count === 0 && !bail) {
  25418. callback(null, result)
  25419. }
  25420. }
  25421. }
  25422. function noop() {}
  25423. },{}],108:[function(require,module,exports){
  25424. /**
  25425. * An abstraction for slicing an arraybuffer even when
  25426. * ArrayBuffer.prototype.slice is not supported
  25427. *
  25428. * @api public
  25429. */
  25430. module.exports = function(arraybuffer, start, end) {
  25431. var bytes = arraybuffer.byteLength;
  25432. start = start || 0;
  25433. end = end || bytes;
  25434. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  25435. if (start < 0) { start += bytes; }
  25436. if (end < 0) { end += bytes; }
  25437. if (end > bytes) { end = bytes; }
  25438. if (start >= bytes || start >= end || bytes === 0) {
  25439. return new ArrayBuffer(0);
  25440. }
  25441. var abv = new Uint8Array(arraybuffer);
  25442. var result = new Uint8Array(end - start);
  25443. for (var i = start, ii = 0; i < end; i++, ii++) {
  25444. result[ii] = abv[i];
  25445. }
  25446. return result.buffer;
  25447. };
  25448. },{}],109:[function(require,module,exports){
  25449. /*
  25450. * base64-arraybuffer
  25451. * https://github.com/niklasvh/base64-arraybuffer
  25452. *
  25453. * Copyright (c) 2012 Niklas von Hertzen
  25454. * Licensed under the MIT license.
  25455. */
  25456. (function(chars){
  25457. "use strict";
  25458. exports.encode = function(arraybuffer) {
  25459. var bytes = new Uint8Array(arraybuffer),
  25460. i, len = bytes.length, base64 = "";
  25461. for (i = 0; i < len; i+=3) {
  25462. base64 += chars[bytes[i] >> 2];
  25463. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  25464. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  25465. base64 += chars[bytes[i + 2] & 63];
  25466. }
  25467. if ((len % 3) === 2) {
  25468. base64 = base64.substring(0, base64.length - 1) + "=";
  25469. } else if (len % 3 === 1) {
  25470. base64 = base64.substring(0, base64.length - 2) + "==";
  25471. }
  25472. return base64;
  25473. };
  25474. exports.decode = function(base64) {
  25475. var bufferLength = base64.length * 0.75,
  25476. len = base64.length, i, p = 0,
  25477. encoded1, encoded2, encoded3, encoded4;
  25478. if (base64[base64.length - 1] === "=") {
  25479. bufferLength--;
  25480. if (base64[base64.length - 2] === "=") {
  25481. bufferLength--;
  25482. }
  25483. }
  25484. var arraybuffer = new ArrayBuffer(bufferLength),
  25485. bytes = new Uint8Array(arraybuffer);
  25486. for (i = 0; i < len; i+=4) {
  25487. encoded1 = chars.indexOf(base64[i]);
  25488. encoded2 = chars.indexOf(base64[i+1]);
  25489. encoded3 = chars.indexOf(base64[i+2]);
  25490. encoded4 = chars.indexOf(base64[i+3]);
  25491. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  25492. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  25493. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  25494. }
  25495. return arraybuffer;
  25496. };
  25497. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  25498. },{}],110:[function(require,module,exports){
  25499. (function (global){
  25500. /**
  25501. * Create a blob builder even when vendor prefixes exist
  25502. */
  25503. var BlobBuilder = global.BlobBuilder
  25504. || global.WebKitBlobBuilder
  25505. || global.MSBlobBuilder
  25506. || global.MozBlobBuilder;
  25507. /**
  25508. * Check if Blob constructor is supported
  25509. */
  25510. var blobSupported = (function() {
  25511. try {
  25512. var b = new Blob(['hi']);
  25513. return b.size == 2;
  25514. } catch(e) {
  25515. return false;
  25516. }
  25517. })();
  25518. /**
  25519. * Check if BlobBuilder is supported
  25520. */
  25521. var blobBuilderSupported = BlobBuilder
  25522. && BlobBuilder.prototype.append
  25523. && BlobBuilder.prototype.getBlob;
  25524. function BlobBuilderConstructor(ary, options) {
  25525. options = options || {};
  25526. var bb = new BlobBuilder();
  25527. for (var i = 0; i < ary.length; i++) {
  25528. bb.append(ary[i]);
  25529. }
  25530. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  25531. };
  25532. module.exports = (function() {
  25533. if (blobSupported) {
  25534. return global.Blob;
  25535. } else if (blobBuilderSupported) {
  25536. return BlobBuilderConstructor;
  25537. } else {
  25538. return undefined;
  25539. }
  25540. })();
  25541. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25542. },{}],111:[function(require,module,exports){
  25543. (function (global){
  25544. /*
  25545. * Module requirements.
  25546. */
  25547. var isArray = require('isarray');
  25548. /**
  25549. * Module exports.
  25550. */
  25551. module.exports = hasBinary;
  25552. /**
  25553. * Checks for binary data.
  25554. *
  25555. * Right now only Buffer and ArrayBuffer are supported..
  25556. *
  25557. * @param {Object} anything
  25558. * @api public
  25559. */
  25560. function hasBinary(data) {
  25561. function _hasBinary(obj) {
  25562. if (!obj) return false;
  25563. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  25564. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  25565. (global.Blob && obj instanceof Blob) ||
  25566. (global.File && obj instanceof File)
  25567. ) {
  25568. return true;
  25569. }
  25570. if (isArray(obj)) {
  25571. for (var i = 0; i < obj.length; i++) {
  25572. if (_hasBinary(obj[i])) {
  25573. return true;
  25574. }
  25575. }
  25576. } else if (obj && 'object' == typeof obj) {
  25577. if (obj.toJSON) {
  25578. obj = obj.toJSON();
  25579. }
  25580. for (var key in obj) {
  25581. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  25582. return true;
  25583. }
  25584. }
  25585. }
  25586. return false;
  25587. }
  25588. return _hasBinary(data);
  25589. }
  25590. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25591. },{"isarray":112}],112:[function(require,module,exports){
  25592. module.exports = Array.isArray || function (arr) {
  25593. return Object.prototype.toString.call(arr) == '[object Array]';
  25594. };
  25595. },{}],113:[function(require,module,exports){
  25596. (function (global){
  25597. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  25598. ;(function(root) {
  25599. // Detect free variables `exports`
  25600. var freeExports = typeof exports == 'object' && exports;
  25601. // Detect free variable `module`
  25602. var freeModule = typeof module == 'object' && module &&
  25603. module.exports == freeExports && module;
  25604. // Detect free variable `global`, from Node.js or Browserified code,
  25605. // and use it as `root`
  25606. var freeGlobal = typeof global == 'object' && global;
  25607. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  25608. root = freeGlobal;
  25609. }
  25610. /*--------------------------------------------------------------------------*/
  25611. var stringFromCharCode = String.fromCharCode;
  25612. // Taken from http://mths.be/punycode
  25613. function ucs2decode(string) {
  25614. var output = [];
  25615. var counter = 0;
  25616. var length = string.length;
  25617. var value;
  25618. var extra;
  25619. while (counter < length) {
  25620. value = string.charCodeAt(counter++);
  25621. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  25622. // high surrogate, and there is a next character
  25623. extra = string.charCodeAt(counter++);
  25624. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  25625. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  25626. } else {
  25627. // unmatched surrogate; only append this code unit, in case the next
  25628. // code unit is the high surrogate of a surrogate pair
  25629. output.push(value);
  25630. counter--;
  25631. }
  25632. } else {
  25633. output.push(value);
  25634. }
  25635. }
  25636. return output;
  25637. }
  25638. // Taken from http://mths.be/punycode
  25639. function ucs2encode(array) {
  25640. var length = array.length;
  25641. var index = -1;
  25642. var value;
  25643. var output = '';
  25644. while (++index < length) {
  25645. value = array[index];
  25646. if (value > 0xFFFF) {
  25647. value -= 0x10000;
  25648. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  25649. value = 0xDC00 | value & 0x3FF;
  25650. }
  25651. output += stringFromCharCode(value);
  25652. }
  25653. return output;
  25654. }
  25655. /*--------------------------------------------------------------------------*/
  25656. function createByte(codePoint, shift) {
  25657. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  25658. }
  25659. function encodeCodePoint(codePoint) {
  25660. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  25661. return stringFromCharCode(codePoint);
  25662. }
  25663. var symbol = '';
  25664. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  25665. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  25666. }
  25667. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  25668. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  25669. symbol += createByte(codePoint, 6);
  25670. }
  25671. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  25672. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  25673. symbol += createByte(codePoint, 12);
  25674. symbol += createByte(codePoint, 6);
  25675. }
  25676. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  25677. return symbol;
  25678. }
  25679. function utf8encode(string) {
  25680. var codePoints = ucs2decode(string);
  25681. // console.log(JSON.stringify(codePoints.map(function(x) {
  25682. // return 'U+' + x.toString(16).toUpperCase();
  25683. // })));
  25684. var length = codePoints.length;
  25685. var index = -1;
  25686. var codePoint;
  25687. var byteString = '';
  25688. while (++index < length) {
  25689. codePoint = codePoints[index];
  25690. byteString += encodeCodePoint(codePoint);
  25691. }
  25692. return byteString;
  25693. }
  25694. /*--------------------------------------------------------------------------*/
  25695. function readContinuationByte() {
  25696. if (byteIndex >= byteCount) {
  25697. throw Error('Invalid byte index');
  25698. }
  25699. var continuationByte = byteArray[byteIndex] & 0xFF;
  25700. byteIndex++;
  25701. if ((continuationByte & 0xC0) == 0x80) {
  25702. return continuationByte & 0x3F;
  25703. }
  25704. // If we end up here, it’s not a continuation byte
  25705. throw Error('Invalid continuation byte');
  25706. }
  25707. function decodeSymbol() {
  25708. var byte1;
  25709. var byte2;
  25710. var byte3;
  25711. var byte4;
  25712. var codePoint;
  25713. if (byteIndex > byteCount) {
  25714. throw Error('Invalid byte index');
  25715. }
  25716. if (byteIndex == byteCount) {
  25717. return false;
  25718. }
  25719. // Read first byte
  25720. byte1 = byteArray[byteIndex] & 0xFF;
  25721. byteIndex++;
  25722. // 1-byte sequence (no continuation bytes)
  25723. if ((byte1 & 0x80) == 0) {
  25724. return byte1;
  25725. }
  25726. // 2-byte sequence
  25727. if ((byte1 & 0xE0) == 0xC0) {
  25728. var byte2 = readContinuationByte();
  25729. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  25730. if (codePoint >= 0x80) {
  25731. return codePoint;
  25732. } else {
  25733. throw Error('Invalid continuation byte');
  25734. }
  25735. }
  25736. // 3-byte sequence (may include unpaired surrogates)
  25737. if ((byte1 & 0xF0) == 0xE0) {
  25738. byte2 = readContinuationByte();
  25739. byte3 = readContinuationByte();
  25740. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  25741. if (codePoint >= 0x0800) {
  25742. return codePoint;
  25743. } else {
  25744. throw Error('Invalid continuation byte');
  25745. }
  25746. }
  25747. // 4-byte sequence
  25748. if ((byte1 & 0xF8) == 0xF0) {
  25749. byte2 = readContinuationByte();
  25750. byte3 = readContinuationByte();
  25751. byte4 = readContinuationByte();
  25752. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  25753. (byte3 << 0x06) | byte4;
  25754. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  25755. return codePoint;
  25756. }
  25757. }
  25758. throw Error('Invalid UTF-8 detected');
  25759. }
  25760. var byteArray;
  25761. var byteCount;
  25762. var byteIndex;
  25763. function utf8decode(byteString) {
  25764. byteArray = ucs2decode(byteString);
  25765. byteCount = byteArray.length;
  25766. byteIndex = 0;
  25767. var codePoints = [];
  25768. var tmp;
  25769. while ((tmp = decodeSymbol()) !== false) {
  25770. codePoints.push(tmp);
  25771. }
  25772. return ucs2encode(codePoints);
  25773. }
  25774. /*--------------------------------------------------------------------------*/
  25775. var utf8 = {
  25776. 'version': '2.0.0',
  25777. 'encode': utf8encode,
  25778. 'decode': utf8decode
  25779. };
  25780. // Some AMD build optimizers, like r.js, check for specific condition patterns
  25781. // like the following:
  25782. if (
  25783. typeof define == 'function' &&
  25784. typeof define.amd == 'object' &&
  25785. define.amd
  25786. ) {
  25787. define(function() {
  25788. return utf8;
  25789. });
  25790. } else if (freeExports && !freeExports.nodeType) {
  25791. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  25792. freeModule.exports = utf8;
  25793. } else { // in Narwhal or RingoJS v0.7.0-
  25794. var object = {};
  25795. var hasOwnProperty = object.hasOwnProperty;
  25796. for (var key in utf8) {
  25797. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  25798. }
  25799. }
  25800. } else { // in Rhino or a web browser
  25801. root.utf8 = utf8;
  25802. }
  25803. }(this));
  25804. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25805. },{}],114:[function(require,module,exports){
  25806. /**
  25807. * Module dependencies.
  25808. */
  25809. var global = require('global');
  25810. /**
  25811. * Module exports.
  25812. *
  25813. * Logic borrowed from Modernizr:
  25814. *
  25815. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  25816. */
  25817. try {
  25818. module.exports = 'XMLHttpRequest' in global &&
  25819. 'withCredentials' in new global.XMLHttpRequest();
  25820. } catch (err) {
  25821. // if XMLHttp support is disabled in IE then it will throw
  25822. // when trying to create
  25823. module.exports = false;
  25824. }
  25825. },{"global":115}],115:[function(require,module,exports){
  25826. /**
  25827. * Returns `this`. Execute this without a "context" (i.e. without it being
  25828. * attached to an object of the left-hand side), and `this` points to the
  25829. * "global" scope of the current JS execution.
  25830. */
  25831. module.exports = (function () { return this; })();
  25832. },{}],116:[function(require,module,exports){
  25833. (function (global){
  25834. /**
  25835. * JSON parse.
  25836. *
  25837. * @see Based on jQuery#parseJSON (MIT) and JSON2
  25838. * @api private
  25839. */
  25840. var rvalidchars = /^[\],:{}\s]*$/;
  25841. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  25842. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  25843. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  25844. var rtrimLeft = /^\s+/;
  25845. var rtrimRight = /\s+$/;
  25846. module.exports = function parsejson(data) {
  25847. if ('string' != typeof data || !data) {
  25848. return null;
  25849. }
  25850. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  25851. // Attempt to parse using the native JSON parser first
  25852. if (global.JSON && JSON.parse) {
  25853. return JSON.parse(data);
  25854. }
  25855. if (rvalidchars.test(data.replace(rvalidescape, '@')
  25856. .replace(rvalidtokens, ']')
  25857. .replace(rvalidbraces, ''))) {
  25858. return (new Function('return ' + data))();
  25859. }
  25860. };
  25861. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25862. },{}],117:[function(require,module,exports){
  25863. /**
  25864. * Compiles a querystring
  25865. * Returns string representation of the object
  25866. *
  25867. * @param {Object}
  25868. * @api private
  25869. */
  25870. exports.encode = function (obj) {
  25871. var str = '';
  25872. for (var i in obj) {
  25873. if (obj.hasOwnProperty(i)) {
  25874. if (str.length) str += '&';
  25875. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  25876. }
  25877. }
  25878. return str;
  25879. };
  25880. /**
  25881. * Parses a simple querystring into an object
  25882. *
  25883. * @param {String} qs
  25884. * @api private
  25885. */
  25886. exports.decode = function(qs){
  25887. var qry = {};
  25888. var pairs = qs.split('&');
  25889. for (var i = 0, l = pairs.length; i < l; i++) {
  25890. var pair = pairs[i].split('=');
  25891. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  25892. }
  25893. return qry;
  25894. };
  25895. },{}],118:[function(require,module,exports){
  25896. /**
  25897. * Parses an URI
  25898. *
  25899. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  25900. * @api private
  25901. */
  25902. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  25903. var parts = [
  25904. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  25905. ];
  25906. module.exports = function parseuri(str) {
  25907. var src = str,
  25908. b = str.indexOf('['),
  25909. e = str.indexOf(']');
  25910. if (b != -1 && e != -1) {
  25911. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  25912. }
  25913. var m = re.exec(str || ''),
  25914. uri = {},
  25915. i = 14;
  25916. while (i--) {
  25917. uri[parts[i]] = m[i] || '';
  25918. }
  25919. if (b != -1 && e != -1) {
  25920. uri.source = src;
  25921. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  25922. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  25923. uri.ipv6uri = true;
  25924. }
  25925. return uri;
  25926. };
  25927. },{}],119:[function(require,module,exports){
  25928. /**
  25929. * Module dependencies.
  25930. */
  25931. var global = (function() { return this; })();
  25932. /**
  25933. * WebSocket constructor.
  25934. */
  25935. var WebSocket = global.WebSocket || global.MozWebSocket;
  25936. /**
  25937. * Module exports.
  25938. */
  25939. module.exports = WebSocket ? ws : null;
  25940. /**
  25941. * WebSocket constructor.
  25942. *
  25943. * The third `opts` options object gets ignored in web browsers, since it's
  25944. * non-standard, and throws a TypeError if passed to the constructor.
  25945. * See: https://github.com/einaros/ws/issues/227
  25946. *
  25947. * @param {String} uri
  25948. * @param {Array} protocols (optional)
  25949. * @param {Object) opts (optional)
  25950. * @api public
  25951. */
  25952. function ws(uri, protocols, opts) {
  25953. var instance;
  25954. if (protocols) {
  25955. instance = new WebSocket(uri, protocols);
  25956. } else {
  25957. instance = new WebSocket(uri);
  25958. }
  25959. return instance;
  25960. }
  25961. if (WebSocket) ws.prototype = WebSocket.prototype;
  25962. },{}],120:[function(require,module,exports){
  25963. (function (global){
  25964. /*
  25965. * Module requirements.
  25966. */
  25967. var isArray = require('isarray');
  25968. /**
  25969. * Module exports.
  25970. */
  25971. module.exports = hasBinary;
  25972. /**
  25973. * Checks for binary data.
  25974. *
  25975. * Right now only Buffer and ArrayBuffer are supported..
  25976. *
  25977. * @param {Object} anything
  25978. * @api public
  25979. */
  25980. function hasBinary(data) {
  25981. function _hasBinary(obj) {
  25982. if (!obj) return false;
  25983. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  25984. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  25985. (global.Blob && obj instanceof Blob) ||
  25986. (global.File && obj instanceof File)
  25987. ) {
  25988. return true;
  25989. }
  25990. if (isArray(obj)) {
  25991. for (var i = 0; i < obj.length; i++) {
  25992. if (_hasBinary(obj[i])) {
  25993. return true;
  25994. }
  25995. }
  25996. } else if (obj && 'object' == typeof obj) {
  25997. if (obj.toJSON) {
  25998. obj = obj.toJSON();
  25999. }
  26000. for (var key in obj) {
  26001. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  26002. return true;
  26003. }
  26004. }
  26005. }
  26006. return false;
  26007. }
  26008. return _hasBinary(data);
  26009. }
  26010. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26011. },{"isarray":121}],121:[function(require,module,exports){
  26012. arguments[4][112][0].apply(exports,arguments)
  26013. },{"dup":112}],122:[function(require,module,exports){
  26014. var indexOf = [].indexOf;
  26015. module.exports = function(arr, obj){
  26016. if (indexOf) return arr.indexOf(obj);
  26017. for (var i = 0; i < arr.length; ++i) {
  26018. if (arr[i] === obj) return i;
  26019. }
  26020. return -1;
  26021. };
  26022. },{}],123:[function(require,module,exports){
  26023. /**
  26024. * HOP ref.
  26025. */
  26026. var has = Object.prototype.hasOwnProperty;
  26027. /**
  26028. * Return own keys in `obj`.
  26029. *
  26030. * @param {Object} obj
  26031. * @return {Array}
  26032. * @api public
  26033. */
  26034. exports.keys = Object.keys || function(obj){
  26035. var keys = [];
  26036. for (var key in obj) {
  26037. if (has.call(obj, key)) {
  26038. keys.push(key);
  26039. }
  26040. }
  26041. return keys;
  26042. };
  26043. /**
  26044. * Return own values in `obj`.
  26045. *
  26046. * @param {Object} obj
  26047. * @return {Array}
  26048. * @api public
  26049. */
  26050. exports.values = function(obj){
  26051. var vals = [];
  26052. for (var key in obj) {
  26053. if (has.call(obj, key)) {
  26054. vals.push(obj[key]);
  26055. }
  26056. }
  26057. return vals;
  26058. };
  26059. /**
  26060. * Merge `b` into `a`.
  26061. *
  26062. * @param {Object} a
  26063. * @param {Object} b
  26064. * @return {Object} a
  26065. * @api public
  26066. */
  26067. exports.merge = function(a, b){
  26068. for (var key in b) {
  26069. if (has.call(b, key)) {
  26070. a[key] = b[key];
  26071. }
  26072. }
  26073. return a;
  26074. };
  26075. /**
  26076. * Return length of `obj`.
  26077. *
  26078. * @param {Object} obj
  26079. * @return {Number}
  26080. * @api public
  26081. */
  26082. exports.length = function(obj){
  26083. return exports.keys(obj).length;
  26084. };
  26085. /**
  26086. * Check if `obj` is empty.
  26087. *
  26088. * @param {Object} obj
  26089. * @return {Boolean}
  26090. * @api public
  26091. */
  26092. exports.isEmpty = function(obj){
  26093. return 0 == exports.length(obj);
  26094. };
  26095. },{}],124:[function(require,module,exports){
  26096. /**
  26097. * Parses an URI
  26098. *
  26099. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  26100. * @api private
  26101. */
  26102. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  26103. var parts = [
  26104. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  26105. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  26106. ];
  26107. module.exports = function parseuri(str) {
  26108. var m = re.exec(str || '')
  26109. , uri = {}
  26110. , i = 14;
  26111. while (i--) {
  26112. uri[parts[i]] = m[i] || '';
  26113. }
  26114. return uri;
  26115. };
  26116. },{}],125:[function(require,module,exports){
  26117. (function (global){
  26118. /*global Blob,File*/
  26119. /**
  26120. * Module requirements
  26121. */
  26122. var isArray = require('isarray');
  26123. var isBuf = require('./is-buffer');
  26124. /**
  26125. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  26126. * Anything with blobs or files should be fed through removeBlobs before coming
  26127. * here.
  26128. *
  26129. * @param {Object} packet - socket.io event packet
  26130. * @return {Object} with deconstructed packet and list of buffers
  26131. * @api public
  26132. */
  26133. exports.deconstructPacket = function(packet){
  26134. var buffers = [];
  26135. var packetData = packet.data;
  26136. function _deconstructPacket(data) {
  26137. if (!data) return data;
  26138. if (isBuf(data)) {
  26139. var placeholder = { _placeholder: true, num: buffers.length };
  26140. buffers.push(data);
  26141. return placeholder;
  26142. } else if (isArray(data)) {
  26143. var newData = new Array(data.length);
  26144. for (var i = 0; i < data.length; i++) {
  26145. newData[i] = _deconstructPacket(data[i]);
  26146. }
  26147. return newData;
  26148. } else if ('object' == typeof data && !(data instanceof Date)) {
  26149. var newData = {};
  26150. for (var key in data) {
  26151. newData[key] = _deconstructPacket(data[key]);
  26152. }
  26153. return newData;
  26154. }
  26155. return data;
  26156. }
  26157. var pack = packet;
  26158. pack.data = _deconstructPacket(packetData);
  26159. pack.attachments = buffers.length; // number of binary 'attachments'
  26160. return {packet: pack, buffers: buffers};
  26161. };
  26162. /**
  26163. * Reconstructs a binary packet from its placeholder packet and buffers
  26164. *
  26165. * @param {Object} packet - event packet with placeholders
  26166. * @param {Array} buffers - binary buffers to put in placeholder positions
  26167. * @return {Object} reconstructed packet
  26168. * @api public
  26169. */
  26170. exports.reconstructPacket = function(packet, buffers) {
  26171. var curPlaceHolder = 0;
  26172. function _reconstructPacket(data) {
  26173. if (data && data._placeholder) {
  26174. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  26175. return buf;
  26176. } else if (isArray(data)) {
  26177. for (var i = 0; i < data.length; i++) {
  26178. data[i] = _reconstructPacket(data[i]);
  26179. }
  26180. return data;
  26181. } else if (data && 'object' == typeof data) {
  26182. for (var key in data) {
  26183. data[key] = _reconstructPacket(data[key]);
  26184. }
  26185. return data;
  26186. }
  26187. return data;
  26188. }
  26189. packet.data = _reconstructPacket(packet.data);
  26190. packet.attachments = undefined; // no longer useful
  26191. return packet;
  26192. };
  26193. /**
  26194. * Asynchronously removes Blobs or Files from data via
  26195. * FileReader's readAsArrayBuffer method. Used before encoding
  26196. * data as msgpack. Calls callback with the blobless data.
  26197. *
  26198. * @param {Object} data
  26199. * @param {Function} callback
  26200. * @api private
  26201. */
  26202. exports.removeBlobs = function(data, callback) {
  26203. function _removeBlobs(obj, curKey, containingObject) {
  26204. if (!obj) return obj;
  26205. // convert any blob
  26206. if ((global.Blob && obj instanceof Blob) ||
  26207. (global.File && obj instanceof File)) {
  26208. pendingBlobs++;
  26209. // async filereader
  26210. var fileReader = new FileReader();
  26211. fileReader.onload = function() { // this.result == arraybuffer
  26212. if (containingObject) {
  26213. containingObject[curKey] = this.result;
  26214. }
  26215. else {
  26216. bloblessData = this.result;
  26217. }
  26218. // if nothing pending its callback time
  26219. if(! --pendingBlobs) {
  26220. callback(bloblessData);
  26221. }
  26222. };
  26223. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  26224. } else if (isArray(obj)) { // handle array
  26225. for (var i = 0; i < obj.length; i++) {
  26226. _removeBlobs(obj[i], i, obj);
  26227. }
  26228. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  26229. for (var key in obj) {
  26230. _removeBlobs(obj[key], key, obj);
  26231. }
  26232. }
  26233. }
  26234. var pendingBlobs = 0;
  26235. var bloblessData = data;
  26236. _removeBlobs(bloblessData);
  26237. if (!pendingBlobs) {
  26238. callback(bloblessData);
  26239. }
  26240. };
  26241. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26242. },{"./is-buffer":127,"isarray":128}],126:[function(require,module,exports){
  26243. /**
  26244. * Module dependencies.
  26245. */
  26246. var debug = require('debug')('socket.io-parser');
  26247. var json = require('json3');
  26248. var isArray = require('isarray');
  26249. var Emitter = require('component-emitter');
  26250. var binary = require('./binary');
  26251. var isBuf = require('./is-buffer');
  26252. /**
  26253. * Protocol version.
  26254. *
  26255. * @api public
  26256. */
  26257. exports.protocol = 4;
  26258. /**
  26259. * Packet types.
  26260. *
  26261. * @api public
  26262. */
  26263. exports.types = [
  26264. 'CONNECT',
  26265. 'DISCONNECT',
  26266. 'EVENT',
  26267. 'BINARY_EVENT',
  26268. 'ACK',
  26269. 'BINARY_ACK',
  26270. 'ERROR'
  26271. ];
  26272. /**
  26273. * Packet type `connect`.
  26274. *
  26275. * @api public
  26276. */
  26277. exports.CONNECT = 0;
  26278. /**
  26279. * Packet type `disconnect`.
  26280. *
  26281. * @api public
  26282. */
  26283. exports.DISCONNECT = 1;
  26284. /**
  26285. * Packet type `event`.
  26286. *
  26287. * @api public
  26288. */
  26289. exports.EVENT = 2;
  26290. /**
  26291. * Packet type `ack`.
  26292. *
  26293. * @api public
  26294. */
  26295. exports.ACK = 3;
  26296. /**
  26297. * Packet type `error`.
  26298. *
  26299. * @api public
  26300. */
  26301. exports.ERROR = 4;
  26302. /**
  26303. * Packet type 'binary event'
  26304. *
  26305. * @api public
  26306. */
  26307. exports.BINARY_EVENT = 5;
  26308. /**
  26309. * Packet type `binary ack`. For acks with binary arguments.
  26310. *
  26311. * @api public
  26312. */
  26313. exports.BINARY_ACK = 6;
  26314. /**
  26315. * Encoder constructor.
  26316. *
  26317. * @api public
  26318. */
  26319. exports.Encoder = Encoder;
  26320. /**
  26321. * Decoder constructor.
  26322. *
  26323. * @api public
  26324. */
  26325. exports.Decoder = Decoder;
  26326. /**
  26327. * A socket.io Encoder instance
  26328. *
  26329. * @api public
  26330. */
  26331. function Encoder() {}
  26332. /**
  26333. * Encode a packet as a single string if non-binary, or as a
  26334. * buffer sequence, depending on packet type.
  26335. *
  26336. * @param {Object} obj - packet object
  26337. * @param {Function} callback - function to handle encodings (likely engine.write)
  26338. * @return Calls callback with Array of encodings
  26339. * @api public
  26340. */
  26341. Encoder.prototype.encode = function(obj, callback){
  26342. debug('encoding packet %j', obj);
  26343. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26344. encodeAsBinary(obj, callback);
  26345. }
  26346. else {
  26347. var encoding = encodeAsString(obj);
  26348. callback([encoding]);
  26349. }
  26350. };
  26351. /**
  26352. * Encode packet as string.
  26353. *
  26354. * @param {Object} packet
  26355. * @return {String} encoded
  26356. * @api private
  26357. */
  26358. function encodeAsString(obj) {
  26359. var str = '';
  26360. var nsp = false;
  26361. // first is type
  26362. str += obj.type;
  26363. // attachments if we have them
  26364. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26365. str += obj.attachments;
  26366. str += '-';
  26367. }
  26368. // if we have a namespace other than `/`
  26369. // we append it followed by a comma `,`
  26370. if (obj.nsp && '/' != obj.nsp) {
  26371. nsp = true;
  26372. str += obj.nsp;
  26373. }
  26374. // immediately followed by the id
  26375. if (null != obj.id) {
  26376. if (nsp) {
  26377. str += ',';
  26378. nsp = false;
  26379. }
  26380. str += obj.id;
  26381. }
  26382. // json data
  26383. if (null != obj.data) {
  26384. if (nsp) str += ',';
  26385. str += json.stringify(obj.data);
  26386. }
  26387. debug('encoded %j as %s', obj, str);
  26388. return str;
  26389. }
  26390. /**
  26391. * Encode packet as 'buffer sequence' by removing blobs, and
  26392. * deconstructing packet into object with placeholders and
  26393. * a list of buffers.
  26394. *
  26395. * @param {Object} packet
  26396. * @return {Buffer} encoded
  26397. * @api private
  26398. */
  26399. function encodeAsBinary(obj, callback) {
  26400. function writeEncoding(bloblessData) {
  26401. var deconstruction = binary.deconstructPacket(bloblessData);
  26402. var pack = encodeAsString(deconstruction.packet);
  26403. var buffers = deconstruction.buffers;
  26404. buffers.unshift(pack); // add packet info to beginning of data list
  26405. callback(buffers); // write all the buffers
  26406. }
  26407. binary.removeBlobs(obj, writeEncoding);
  26408. }
  26409. /**
  26410. * A socket.io Decoder instance
  26411. *
  26412. * @return {Object} decoder
  26413. * @api public
  26414. */
  26415. function Decoder() {
  26416. this.reconstructor = null;
  26417. }
  26418. /**
  26419. * Mix in `Emitter` with Decoder.
  26420. */
  26421. Emitter(Decoder.prototype);
  26422. /**
  26423. * Decodes an ecoded packet string into packet JSON.
  26424. *
  26425. * @param {String} obj - encoded packet
  26426. * @return {Object} packet
  26427. * @api public
  26428. */
  26429. Decoder.prototype.add = function(obj) {
  26430. var packet;
  26431. if ('string' == typeof obj) {
  26432. packet = decodeString(obj);
  26433. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  26434. this.reconstructor = new BinaryReconstructor(packet);
  26435. // no attachments, labeled binary but no binary data to follow
  26436. if (this.reconstructor.reconPack.attachments === 0) {
  26437. this.emit('decoded', packet);
  26438. }
  26439. } else { // non-binary full packet
  26440. this.emit('decoded', packet);
  26441. }
  26442. }
  26443. else if (isBuf(obj) || obj.base64) { // raw binary data
  26444. if (!this.reconstructor) {
  26445. throw new Error('got binary data when not reconstructing a packet');
  26446. } else {
  26447. packet = this.reconstructor.takeBinaryData(obj);
  26448. if (packet) { // received final buffer
  26449. this.reconstructor = null;
  26450. this.emit('decoded', packet);
  26451. }
  26452. }
  26453. }
  26454. else {
  26455. throw new Error('Unknown type: ' + obj);
  26456. }
  26457. };
  26458. /**
  26459. * Decode a packet String (JSON data)
  26460. *
  26461. * @param {String} str
  26462. * @return {Object} packet
  26463. * @api private
  26464. */
  26465. function decodeString(str) {
  26466. var p = {};
  26467. var i = 0;
  26468. // look up type
  26469. p.type = Number(str.charAt(0));
  26470. if (null == exports.types[p.type]) return error();
  26471. // look up attachments if type binary
  26472. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  26473. var buf = '';
  26474. while (str.charAt(++i) != '-') {
  26475. buf += str.charAt(i);
  26476. if (i == str.length) break;
  26477. }
  26478. if (buf != Number(buf) || str.charAt(i) != '-') {
  26479. throw new Error('Illegal attachments');
  26480. }
  26481. p.attachments = Number(buf);
  26482. }
  26483. // look up namespace (if any)
  26484. if ('/' == str.charAt(i + 1)) {
  26485. p.nsp = '';
  26486. while (++i) {
  26487. var c = str.charAt(i);
  26488. if (',' == c) break;
  26489. p.nsp += c;
  26490. if (i == str.length) break;
  26491. }
  26492. } else {
  26493. p.nsp = '/';
  26494. }
  26495. // look up id
  26496. var next = str.charAt(i + 1);
  26497. if ('' !== next && Number(next) == next) {
  26498. p.id = '';
  26499. while (++i) {
  26500. var c = str.charAt(i);
  26501. if (null == c || Number(c) != c) {
  26502. --i;
  26503. break;
  26504. }
  26505. p.id += str.charAt(i);
  26506. if (i == str.length) break;
  26507. }
  26508. p.id = Number(p.id);
  26509. }
  26510. // look up json data
  26511. if (str.charAt(++i)) {
  26512. try {
  26513. p.data = json.parse(str.substr(i));
  26514. } catch(e){
  26515. return error();
  26516. }
  26517. }
  26518. debug('decoded %s as %j', str, p);
  26519. return p;
  26520. }
  26521. /**
  26522. * Deallocates a parser's resources
  26523. *
  26524. * @api public
  26525. */
  26526. Decoder.prototype.destroy = function() {
  26527. if (this.reconstructor) {
  26528. this.reconstructor.finishedReconstruction();
  26529. }
  26530. };
  26531. /**
  26532. * A manager of a binary event's 'buffer sequence'. Should
  26533. * be constructed whenever a packet of type BINARY_EVENT is
  26534. * decoded.
  26535. *
  26536. * @param {Object} packet
  26537. * @return {BinaryReconstructor} initialized reconstructor
  26538. * @api private
  26539. */
  26540. function BinaryReconstructor(packet) {
  26541. this.reconPack = packet;
  26542. this.buffers = [];
  26543. }
  26544. /**
  26545. * Method to be called when binary data received from connection
  26546. * after a BINARY_EVENT packet.
  26547. *
  26548. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  26549. * @return {null | Object} returns null if more binary data is expected or
  26550. * a reconstructed packet object if all buffers have been received.
  26551. * @api private
  26552. */
  26553. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  26554. this.buffers.push(binData);
  26555. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  26556. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  26557. this.finishedReconstruction();
  26558. return packet;
  26559. }
  26560. return null;
  26561. };
  26562. /**
  26563. * Cleans up binary packet reconstruction variables.
  26564. *
  26565. * @api private
  26566. */
  26567. BinaryReconstructor.prototype.finishedReconstruction = function() {
  26568. this.reconPack = null;
  26569. this.buffers = [];
  26570. };
  26571. function error(data){
  26572. return {
  26573. type: exports.ERROR,
  26574. data: 'parser error'
  26575. };
  26576. }
  26577. },{"./binary":125,"./is-buffer":127,"component-emitter":89,"debug":90,"isarray":128,"json3":129}],127:[function(require,module,exports){
  26578. (function (global){
  26579. module.exports = isBuf;
  26580. /**
  26581. * Returns true if obj is a buffer or an arraybuffer.
  26582. *
  26583. * @api private
  26584. */
  26585. function isBuf(obj) {
  26586. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  26587. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  26588. }
  26589. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26590. },{}],128:[function(require,module,exports){
  26591. arguments[4][112][0].apply(exports,arguments)
  26592. },{"dup":112}],129:[function(require,module,exports){
  26593. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  26594. ;(function (window) {
  26595. // Convenience aliases.
  26596. var getClass = {}.toString, isProperty, forEach, undef;
  26597. // Detect the `define` function exposed by asynchronous module loaders. The
  26598. // strict `define` check is necessary for compatibility with `r.js`.
  26599. var isLoader = typeof define === "function" && define.amd;
  26600. // Detect native implementations.
  26601. var nativeJSON = typeof JSON == "object" && JSON;
  26602. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  26603. // available.
  26604. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  26605. if (JSON3 && nativeJSON) {
  26606. // Explicitly delegate to the native `stringify` and `parse`
  26607. // implementations in CommonJS environments.
  26608. JSON3.stringify = nativeJSON.stringify;
  26609. JSON3.parse = nativeJSON.parse;
  26610. } else {
  26611. // Export for web browsers, JavaScript engines, and asynchronous module
  26612. // loaders, using the global `JSON` object if available.
  26613. JSON3 = window.JSON = nativeJSON || {};
  26614. }
  26615. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  26616. var isExtended = new Date(-3509827334573292);
  26617. try {
  26618. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  26619. // results for certain dates in Opera >= 10.53.
  26620. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  26621. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  26622. // but clips the values returned by the date methods to the range of
  26623. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  26624. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  26625. } catch (exception) {}
  26626. // Internal: Determines whether the native `JSON.stringify` and `parse`
  26627. // implementations are spec-compliant. Based on work by Ken Snyder.
  26628. function has(name) {
  26629. if (has[name] !== undef) {
  26630. // Return cached feature test result.
  26631. return has[name];
  26632. }
  26633. var isSupported;
  26634. if (name == "bug-string-char-index") {
  26635. // IE <= 7 doesn't support accessing string characters using square
  26636. // bracket notation. IE 8 only supports this for primitives.
  26637. isSupported = "a"[0] != "a";
  26638. } else if (name == "json") {
  26639. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  26640. // supported.
  26641. isSupported = has("json-stringify") && has("json-parse");
  26642. } else {
  26643. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  26644. // Test `JSON.stringify`.
  26645. if (name == "json-stringify") {
  26646. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  26647. if (stringifySupported) {
  26648. // A test function object with a custom `toJSON` method.
  26649. (value = function () {
  26650. return 1;
  26651. }).toJSON = value;
  26652. try {
  26653. stringifySupported =
  26654. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  26655. // primitives as object literals.
  26656. stringify(0) === "0" &&
  26657. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  26658. // literals.
  26659. stringify(new Number()) === "0" &&
  26660. stringify(new String()) == '""' &&
  26661. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  26662. // does not define a canonical JSON representation (this applies to
  26663. // objects with `toJSON` properties as well, *unless* they are nested
  26664. // within an object or array).
  26665. stringify(getClass) === undef &&
  26666. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  26667. // FF 3.1b3 pass this test.
  26668. stringify(undef) === undef &&
  26669. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  26670. // respectively, if the value is omitted entirely.
  26671. stringify() === undef &&
  26672. // FF 3.1b1, 2 throw an error if the given value is not a number,
  26673. // string, array, object, Boolean, or `null` literal. This applies to
  26674. // objects with custom `toJSON` methods as well, unless they are nested
  26675. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  26676. // methods entirely.
  26677. stringify(value) === "1" &&
  26678. stringify([value]) == "[1]" &&
  26679. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  26680. // `"[null]"`.
  26681. stringify([undef]) == "[null]" &&
  26682. // YUI 3.0.0b1 fails to serialize `null` literals.
  26683. stringify(null) == "null" &&
  26684. // FF 3.1b1, 2 halts serialization if an array contains a function:
  26685. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  26686. // elides non-JSON values from objects and arrays, unless they
  26687. // define custom `toJSON` methods.
  26688. stringify([undef, getClass, null]) == "[null,null,null]" &&
  26689. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  26690. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  26691. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  26692. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  26693. stringify(null, value) === "1" &&
  26694. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  26695. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  26696. // serialize extended years.
  26697. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  26698. // The milliseconds are optional in ES 5, but required in 5.1.
  26699. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  26700. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  26701. // four-digit years instead of six-digit years. Credits: @Yaffle.
  26702. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  26703. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  26704. // values less than 1000. Credits: @Yaffle.
  26705. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  26706. } catch (exception) {
  26707. stringifySupported = false;
  26708. }
  26709. }
  26710. isSupported = stringifySupported;
  26711. }
  26712. // Test `JSON.parse`.
  26713. if (name == "json-parse") {
  26714. var parse = JSON3.parse;
  26715. if (typeof parse == "function") {
  26716. try {
  26717. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  26718. // Conforming implementations should also coerce the initial argument to
  26719. // a string prior to parsing.
  26720. if (parse("0") === 0 && !parse(false)) {
  26721. // Simple parsing test.
  26722. value = parse(serialized);
  26723. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  26724. if (parseSupported) {
  26725. try {
  26726. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  26727. parseSupported = !parse('"\t"');
  26728. } catch (exception) {}
  26729. if (parseSupported) {
  26730. try {
  26731. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  26732. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  26733. // certain octal literals.
  26734. parseSupported = parse("01") !== 1;
  26735. } catch (exception) {}
  26736. }
  26737. if (parseSupported) {
  26738. try {
  26739. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  26740. // points. These environments, along with FF 3.1b1 and 2,
  26741. // also allow trailing commas in JSON objects and arrays.
  26742. parseSupported = parse("1.") !== 1;
  26743. } catch (exception) {}
  26744. }
  26745. }
  26746. }
  26747. } catch (exception) {
  26748. parseSupported = false;
  26749. }
  26750. }
  26751. isSupported = parseSupported;
  26752. }
  26753. }
  26754. return has[name] = !!isSupported;
  26755. }
  26756. if (!has("json")) {
  26757. // Common `[[Class]]` name aliases.
  26758. var functionClass = "[object Function]";
  26759. var dateClass = "[object Date]";
  26760. var numberClass = "[object Number]";
  26761. var stringClass = "[object String]";
  26762. var arrayClass = "[object Array]";
  26763. var booleanClass = "[object Boolean]";
  26764. // Detect incomplete support for accessing string characters by index.
  26765. var charIndexBuggy = has("bug-string-char-index");
  26766. // Define additional utility methods if the `Date` methods are buggy.
  26767. if (!isExtended) {
  26768. var floor = Math.floor;
  26769. // A mapping between the months of the year and the number of days between
  26770. // January 1st and the first of the respective month.
  26771. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  26772. // Internal: Calculates the number of days between the Unix epoch and the
  26773. // first day of the given month.
  26774. var getDay = function (year, month) {
  26775. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  26776. };
  26777. }
  26778. // Internal: Determines if a property is a direct property of the given
  26779. // object. Delegates to the native `Object#hasOwnProperty` method.
  26780. if (!(isProperty = {}.hasOwnProperty)) {
  26781. isProperty = function (property) {
  26782. var members = {}, constructor;
  26783. if ((members.__proto__ = null, members.__proto__ = {
  26784. // The *proto* property cannot be set multiple times in recent
  26785. // versions of Firefox and SeaMonkey.
  26786. "toString": 1
  26787. }, members).toString != getClass) {
  26788. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  26789. // supports the mutable *proto* property.
  26790. isProperty = function (property) {
  26791. // Capture and break the object's prototype chain (see section 8.6.2
  26792. // of the ES 5.1 spec). The parenthesized expression prevents an
  26793. // unsafe transformation by the Closure Compiler.
  26794. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  26795. // Restore the original prototype chain.
  26796. this.__proto__ = original;
  26797. return result;
  26798. };
  26799. } else {
  26800. // Capture a reference to the top-level `Object` constructor.
  26801. constructor = members.constructor;
  26802. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  26803. // other environments.
  26804. isProperty = function (property) {
  26805. var parent = (this.constructor || constructor).prototype;
  26806. return property in this && !(property in parent && this[property] === parent[property]);
  26807. };
  26808. }
  26809. members = null;
  26810. return isProperty.call(this, property);
  26811. };
  26812. }
  26813. // Internal: A set of primitive types used by `isHostType`.
  26814. var PrimitiveTypes = {
  26815. 'boolean': 1,
  26816. 'number': 1,
  26817. 'string': 1,
  26818. 'undefined': 1
  26819. };
  26820. // Internal: Determines if the given object `property` value is a
  26821. // non-primitive.
  26822. var isHostType = function (object, property) {
  26823. var type = typeof object[property];
  26824. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  26825. };
  26826. // Internal: Normalizes the `for...in` iteration algorithm across
  26827. // environments. Each enumerated key is yielded to a `callback` function.
  26828. forEach = function (object, callback) {
  26829. var size = 0, Properties, members, property;
  26830. // Tests for bugs in the current environment's `for...in` algorithm. The
  26831. // `valueOf` property inherits the non-enumerable flag from
  26832. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  26833. (Properties = function () {
  26834. this.valueOf = 0;
  26835. }).prototype.valueOf = 0;
  26836. // Iterate over a new instance of the `Properties` class.
  26837. members = new Properties();
  26838. for (property in members) {
  26839. // Ignore all properties inherited from `Object.prototype`.
  26840. if (isProperty.call(members, property)) {
  26841. size++;
  26842. }
  26843. }
  26844. Properties = members = null;
  26845. // Normalize the iteration algorithm.
  26846. if (!size) {
  26847. // A list of non-enumerable properties inherited from `Object.prototype`.
  26848. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  26849. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  26850. // properties.
  26851. forEach = function (object, callback) {
  26852. var isFunction = getClass.call(object) == functionClass, property, length;
  26853. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  26854. for (property in object) {
  26855. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  26856. // certain conditions; IE does not.
  26857. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  26858. callback(property);
  26859. }
  26860. }
  26861. // Manually invoke the callback for each non-enumerable property.
  26862. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  26863. };
  26864. } else if (size == 2) {
  26865. // Safari <= 2.0.4 enumerates shadowed properties twice.
  26866. forEach = function (object, callback) {
  26867. // Create a set of iterated properties.
  26868. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  26869. for (property in object) {
  26870. // Store each property name to prevent double enumeration. The
  26871. // `prototype` property of functions is not enumerated due to cross-
  26872. // environment inconsistencies.
  26873. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  26874. callback(property);
  26875. }
  26876. }
  26877. };
  26878. } else {
  26879. // No bugs detected; use the standard `for...in` algorithm.
  26880. forEach = function (object, callback) {
  26881. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  26882. for (property in object) {
  26883. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  26884. callback(property);
  26885. }
  26886. }
  26887. // Manually invoke the callback for the `constructor` property due to
  26888. // cross-environment inconsistencies.
  26889. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  26890. callback(property);
  26891. }
  26892. };
  26893. }
  26894. return forEach(object, callback);
  26895. };
  26896. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  26897. // `filter` argument may specify either a function that alters how object and
  26898. // array members are serialized, or an array of strings and numbers that
  26899. // indicates which properties should be serialized. The optional `width`
  26900. // argument may be either a string or number that specifies the indentation
  26901. // level of the output.
  26902. if (!has("json-stringify")) {
  26903. // Internal: A map of control characters and their escaped equivalents.
  26904. var Escapes = {
  26905. 92: "\\\\",
  26906. 34: '\\"',
  26907. 8: "\\b",
  26908. 12: "\\f",
  26909. 10: "\\n",
  26910. 13: "\\r",
  26911. 9: "\\t"
  26912. };
  26913. // Internal: Converts `value` into a zero-padded string such that its
  26914. // length is at least equal to `width`. The `width` must be <= 6.
  26915. var leadingZeroes = "000000";
  26916. var toPaddedString = function (width, value) {
  26917. // The `|| 0` expression is necessary to work around a bug in
  26918. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  26919. return (leadingZeroes + (value || 0)).slice(-width);
  26920. };
  26921. // Internal: Double-quotes a string `value`, replacing all ASCII control
  26922. // characters (characters with code unit values between 0 and 31) with
  26923. // their escaped equivalents. This is an implementation of the
  26924. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  26925. var unicodePrefix = "\\u00";
  26926. var quote = function (value) {
  26927. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  26928. if (isLarge) {
  26929. symbols = value.split("");
  26930. }
  26931. for (; index < length; index++) {
  26932. var charCode = value.charCodeAt(index);
  26933. // If the character is a control character, append its Unicode or
  26934. // shorthand escape sequence; otherwise, append the character as-is.
  26935. switch (charCode) {
  26936. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  26937. result += Escapes[charCode];
  26938. break;
  26939. default:
  26940. if (charCode < 32) {
  26941. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  26942. break;
  26943. }
  26944. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  26945. }
  26946. }
  26947. return result + '"';
  26948. };
  26949. // Internal: Recursively serializes an object. Implements the
  26950. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  26951. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  26952. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  26953. try {
  26954. // Necessary for host object support.
  26955. value = object[property];
  26956. } catch (exception) {}
  26957. if (typeof value == "object" && value) {
  26958. className = getClass.call(value);
  26959. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  26960. if (value > -1 / 0 && value < 1 / 0) {
  26961. // Dates are serialized according to the `Date#toJSON` method
  26962. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  26963. // for the ISO 8601 date time string format.
  26964. if (getDay) {
  26965. // Manually compute the year, month, date, hours, minutes,
  26966. // seconds, and milliseconds if the `getUTC*` methods are
  26967. // buggy. Adapted from @Yaffle's `date-shim` project.
  26968. date = floor(value / 864e5);
  26969. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  26970. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  26971. date = 1 + date - getDay(year, month);
  26972. // The `time` value specifies the time within the day (see ES
  26973. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  26974. // to compute `A modulo B`, as the `%` operator does not
  26975. // correspond to the `modulo` operation for negative numbers.
  26976. time = (value % 864e5 + 864e5) % 864e5;
  26977. // The hours, minutes, seconds, and milliseconds are obtained by
  26978. // decomposing the time within the day. See section 15.9.1.10.
  26979. hours = floor(time / 36e5) % 24;
  26980. minutes = floor(time / 6e4) % 60;
  26981. seconds = floor(time / 1e3) % 60;
  26982. milliseconds = time % 1e3;
  26983. } else {
  26984. year = value.getUTCFullYear();
  26985. month = value.getUTCMonth();
  26986. date = value.getUTCDate();
  26987. hours = value.getUTCHours();
  26988. minutes = value.getUTCMinutes();
  26989. seconds = value.getUTCSeconds();
  26990. milliseconds = value.getUTCMilliseconds();
  26991. }
  26992. // Serialize extended years correctly.
  26993. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  26994. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  26995. // Months, dates, hours, minutes, and seconds should have two
  26996. // digits; milliseconds should have three.
  26997. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  26998. // Milliseconds are optional in ES 5.0, but required in 5.1.
  26999. "." + toPaddedString(3, milliseconds) + "Z";
  27000. } else {
  27001. value = null;
  27002. }
  27003. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  27004. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  27005. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  27006. // ignores all `toJSON` methods on these objects unless they are
  27007. // defined directly on an instance.
  27008. value = value.toJSON(property);
  27009. }
  27010. }
  27011. if (callback) {
  27012. // If a replacement function was provided, call it to obtain the value
  27013. // for serialization.
  27014. value = callback.call(object, property, value);
  27015. }
  27016. if (value === null) {
  27017. return "null";
  27018. }
  27019. className = getClass.call(value);
  27020. if (className == booleanClass) {
  27021. // Booleans are represented literally.
  27022. return "" + value;
  27023. } else if (className == numberClass) {
  27024. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  27025. // `"null"`.
  27026. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  27027. } else if (className == stringClass) {
  27028. // Strings are double-quoted and escaped.
  27029. return quote("" + value);
  27030. }
  27031. // Recursively serialize objects and arrays.
  27032. if (typeof value == "object") {
  27033. // Check for cyclic structures. This is a linear search; performance
  27034. // is inversely proportional to the number of unique nested objects.
  27035. for (length = stack.length; length--;) {
  27036. if (stack[length] === value) {
  27037. // Cyclic structures cannot be serialized by `JSON.stringify`.
  27038. throw TypeError();
  27039. }
  27040. }
  27041. // Add the object to the stack of traversed objects.
  27042. stack.push(value);
  27043. results = [];
  27044. // Save the current indentation level and indent one additional level.
  27045. prefix = indentation;
  27046. indentation += whitespace;
  27047. if (className == arrayClass) {
  27048. // Recursively serialize array elements.
  27049. for (index = 0, length = value.length; index < length; index++) {
  27050. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  27051. results.push(element === undef ? "null" : element);
  27052. }
  27053. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  27054. } else {
  27055. // Recursively serialize object members. Members are selected from
  27056. // either a user-specified list of property names, or the object
  27057. // itself.
  27058. forEach(properties || value, function (property) {
  27059. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  27060. if (element !== undef) {
  27061. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  27062. // is not the empty string, let `member` {quote(property) + ":"}
  27063. // be the concatenation of `member` and the `space` character."
  27064. // The "`space` character" refers to the literal space
  27065. // character, not the `space` {width} argument provided to
  27066. // `JSON.stringify`.
  27067. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  27068. }
  27069. });
  27070. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  27071. }
  27072. // Remove the object from the traversed object stack.
  27073. stack.pop();
  27074. return result;
  27075. }
  27076. };
  27077. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  27078. JSON3.stringify = function (source, filter, width) {
  27079. var whitespace, callback, properties, className;
  27080. if (typeof filter == "function" || typeof filter == "object" && filter) {
  27081. if ((className = getClass.call(filter)) == functionClass) {
  27082. callback = filter;
  27083. } else if (className == arrayClass) {
  27084. // Convert the property names array into a makeshift set.
  27085. properties = {};
  27086. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  27087. }
  27088. }
  27089. if (width) {
  27090. if ((className = getClass.call(width)) == numberClass) {
  27091. // Convert the `width` to an integer and create a string containing
  27092. // `width` number of space characters.
  27093. if ((width -= width % 1) > 0) {
  27094. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  27095. }
  27096. } else if (className == stringClass) {
  27097. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  27098. }
  27099. }
  27100. // Opera <= 7.54u2 discards the values associated with empty string keys
  27101. // (`""`) only if they are used directly within an object member list
  27102. // (e.g., `!("" in { "": 1})`).
  27103. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  27104. };
  27105. }
  27106. // Public: Parses a JSON source string.
  27107. if (!has("json-parse")) {
  27108. var fromCharCode = String.fromCharCode;
  27109. // Internal: A map of escaped control characters and their unescaped
  27110. // equivalents.
  27111. var Unescapes = {
  27112. 92: "\\",
  27113. 34: '"',
  27114. 47: "/",
  27115. 98: "\b",
  27116. 116: "\t",
  27117. 110: "\n",
  27118. 102: "\f",
  27119. 114: "\r"
  27120. };
  27121. // Internal: Stores the parser state.
  27122. var Index, Source;
  27123. // Internal: Resets the parser state and throws a `SyntaxError`.
  27124. var abort = function() {
  27125. Index = Source = null;
  27126. throw SyntaxError();
  27127. };
  27128. // Internal: Returns the next token, or `"$"` if the parser has reached
  27129. // the end of the source string. A token may be a string, number, `null`
  27130. // literal, or Boolean literal.
  27131. var lex = function () {
  27132. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  27133. while (Index < length) {
  27134. charCode = source.charCodeAt(Index);
  27135. switch (charCode) {
  27136. case 9: case 10: case 13: case 32:
  27137. // Skip whitespace tokens, including tabs, carriage returns, line
  27138. // feeds, and space characters.
  27139. Index++;
  27140. break;
  27141. case 123: case 125: case 91: case 93: case 58: case 44:
  27142. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  27143. // the current position.
  27144. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  27145. Index++;
  27146. return value;
  27147. case 34:
  27148. // `"` delimits a JSON string; advance to the next character and
  27149. // begin parsing the string. String tokens are prefixed with the
  27150. // sentinel `@` character to distinguish them from punctuators and
  27151. // end-of-string tokens.
  27152. for (value = "@", Index++; Index < length;) {
  27153. charCode = source.charCodeAt(Index);
  27154. if (charCode < 32) {
  27155. // Unescaped ASCII control characters (those with a code unit
  27156. // less than the space character) are not permitted.
  27157. abort();
  27158. } else if (charCode == 92) {
  27159. // A reverse solidus (`\`) marks the beginning of an escaped
  27160. // control character (including `"`, `\`, and `/`) or Unicode
  27161. // escape sequence.
  27162. charCode = source.charCodeAt(++Index);
  27163. switch (charCode) {
  27164. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  27165. // Revive escaped control characters.
  27166. value += Unescapes[charCode];
  27167. Index++;
  27168. break;
  27169. case 117:
  27170. // `\u` marks the beginning of a Unicode escape sequence.
  27171. // Advance to the first character and validate the
  27172. // four-digit code point.
  27173. begin = ++Index;
  27174. for (position = Index + 4; Index < position; Index++) {
  27175. charCode = source.charCodeAt(Index);
  27176. // A valid sequence comprises four hexdigits (case-
  27177. // insensitive) that form a single hexadecimal value.
  27178. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  27179. // Invalid Unicode escape sequence.
  27180. abort();
  27181. }
  27182. }
  27183. // Revive the escaped character.
  27184. value += fromCharCode("0x" + source.slice(begin, Index));
  27185. break;
  27186. default:
  27187. // Invalid escape sequence.
  27188. abort();
  27189. }
  27190. } else {
  27191. if (charCode == 34) {
  27192. // An unescaped double-quote character marks the end of the
  27193. // string.
  27194. break;
  27195. }
  27196. charCode = source.charCodeAt(Index);
  27197. begin = Index;
  27198. // Optimize for the common case where a string is valid.
  27199. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  27200. charCode = source.charCodeAt(++Index);
  27201. }
  27202. // Append the string as-is.
  27203. value += source.slice(begin, Index);
  27204. }
  27205. }
  27206. if (source.charCodeAt(Index) == 34) {
  27207. // Advance to the next character and return the revived string.
  27208. Index++;
  27209. return value;
  27210. }
  27211. // Unterminated string.
  27212. abort();
  27213. default:
  27214. // Parse numbers and literals.
  27215. begin = Index;
  27216. // Advance past the negative sign, if one is specified.
  27217. if (charCode == 45) {
  27218. isSigned = true;
  27219. charCode = source.charCodeAt(++Index);
  27220. }
  27221. // Parse an integer or floating-point value.
  27222. if (charCode >= 48 && charCode <= 57) {
  27223. // Leading zeroes are interpreted as octal literals.
  27224. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  27225. // Illegal octal literal.
  27226. abort();
  27227. }
  27228. isSigned = false;
  27229. // Parse the integer component.
  27230. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  27231. // Floats cannot contain a leading decimal point; however, this
  27232. // case is already accounted for by the parser.
  27233. if (source.charCodeAt(Index) == 46) {
  27234. position = ++Index;
  27235. // Parse the decimal component.
  27236. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27237. if (position == Index) {
  27238. // Illegal trailing decimal.
  27239. abort();
  27240. }
  27241. Index = position;
  27242. }
  27243. // Parse exponents. The `e` denoting the exponent is
  27244. // case-insensitive.
  27245. charCode = source.charCodeAt(Index);
  27246. if (charCode == 101 || charCode == 69) {
  27247. charCode = source.charCodeAt(++Index);
  27248. // Skip past the sign following the exponent, if one is
  27249. // specified.
  27250. if (charCode == 43 || charCode == 45) {
  27251. Index++;
  27252. }
  27253. // Parse the exponential component.
  27254. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27255. if (position == Index) {
  27256. // Illegal empty exponent.
  27257. abort();
  27258. }
  27259. Index = position;
  27260. }
  27261. // Coerce the parsed value to a JavaScript number.
  27262. return +source.slice(begin, Index);
  27263. }
  27264. // A negative sign may only precede numbers.
  27265. if (isSigned) {
  27266. abort();
  27267. }
  27268. // `true`, `false`, and `null` literals.
  27269. if (source.slice(Index, Index + 4) == "true") {
  27270. Index += 4;
  27271. return true;
  27272. } else if (source.slice(Index, Index + 5) == "false") {
  27273. Index += 5;
  27274. return false;
  27275. } else if (source.slice(Index, Index + 4) == "null") {
  27276. Index += 4;
  27277. return null;
  27278. }
  27279. // Unrecognized token.
  27280. abort();
  27281. }
  27282. }
  27283. // Return the sentinel `$` character if the parser has reached the end
  27284. // of the source string.
  27285. return "$";
  27286. };
  27287. // Internal: Parses a JSON `value` token.
  27288. var get = function (value) {
  27289. var results, hasMembers;
  27290. if (value == "$") {
  27291. // Unexpected end of input.
  27292. abort();
  27293. }
  27294. if (typeof value == "string") {
  27295. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  27296. // Remove the sentinel `@` character.
  27297. return value.slice(1);
  27298. }
  27299. // Parse object and array literals.
  27300. if (value == "[") {
  27301. // Parses a JSON array, returning a new JavaScript array.
  27302. results = [];
  27303. for (;; hasMembers || (hasMembers = true)) {
  27304. value = lex();
  27305. // A closing square bracket marks the end of the array literal.
  27306. if (value == "]") {
  27307. break;
  27308. }
  27309. // If the array literal contains elements, the current token
  27310. // should be a comma separating the previous element from the
  27311. // next.
  27312. if (hasMembers) {
  27313. if (value == ",") {
  27314. value = lex();
  27315. if (value == "]") {
  27316. // Unexpected trailing `,` in array literal.
  27317. abort();
  27318. }
  27319. } else {
  27320. // A `,` must separate each array element.
  27321. abort();
  27322. }
  27323. }
  27324. // Elisions and leading commas are not permitted.
  27325. if (value == ",") {
  27326. abort();
  27327. }
  27328. results.push(get(value));
  27329. }
  27330. return results;
  27331. } else if (value == "{") {
  27332. // Parses a JSON object, returning a new JavaScript object.
  27333. results = {};
  27334. for (;; hasMembers || (hasMembers = true)) {
  27335. value = lex();
  27336. // A closing curly brace marks the end of the object literal.
  27337. if (value == "}") {
  27338. break;
  27339. }
  27340. // If the object literal contains members, the current token
  27341. // should be a comma separator.
  27342. if (hasMembers) {
  27343. if (value == ",") {
  27344. value = lex();
  27345. if (value == "}") {
  27346. // Unexpected trailing `,` in object literal.
  27347. abort();
  27348. }
  27349. } else {
  27350. // A `,` must separate each object member.
  27351. abort();
  27352. }
  27353. }
  27354. // Leading commas are not permitted, object property names must be
  27355. // double-quoted strings, and a `:` must separate each property
  27356. // name and value.
  27357. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  27358. abort();
  27359. }
  27360. results[value.slice(1)] = get(lex());
  27361. }
  27362. return results;
  27363. }
  27364. // Unexpected token encountered.
  27365. abort();
  27366. }
  27367. return value;
  27368. };
  27369. // Internal: Updates a traversed object member.
  27370. var update = function(source, property, callback) {
  27371. var element = walk(source, property, callback);
  27372. if (element === undef) {
  27373. delete source[property];
  27374. } else {
  27375. source[property] = element;
  27376. }
  27377. };
  27378. // Internal: Recursively traverses a parsed JSON object, invoking the
  27379. // `callback` function for each value. This is an implementation of the
  27380. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  27381. var walk = function (source, property, callback) {
  27382. var value = source[property], length;
  27383. if (typeof value == "object" && value) {
  27384. // `forEach` can't be used to traverse an array in Opera <= 8.54
  27385. // because its `Object#hasOwnProperty` implementation returns `false`
  27386. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  27387. if (getClass.call(value) == arrayClass) {
  27388. for (length = value.length; length--;) {
  27389. update(value, length, callback);
  27390. }
  27391. } else {
  27392. forEach(value, function (property) {
  27393. update(value, property, callback);
  27394. });
  27395. }
  27396. }
  27397. return callback.call(source, property, value);
  27398. };
  27399. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  27400. JSON3.parse = function (source, callback) {
  27401. var result, value;
  27402. Index = 0;
  27403. Source = "" + source;
  27404. result = get(lex());
  27405. // If a JSON string contains multiple tokens, it is invalid.
  27406. if (lex() != "$") {
  27407. abort();
  27408. }
  27409. // Reset the parser state.
  27410. Index = Source = null;
  27411. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  27412. };
  27413. }
  27414. }
  27415. // Export for asynchronous module loaders.
  27416. if (isLoader) {
  27417. define(function () {
  27418. return JSON3;
  27419. });
  27420. }
  27421. }(this));
  27422. },{}],130:[function(require,module,exports){
  27423. module.exports = toArray
  27424. function toArray(list, index) {
  27425. var array = []
  27426. index = index || 0
  27427. for (var i = index || 0; i < list.length; i++) {
  27428. array[i - index] = list[i]
  27429. }
  27430. return array
  27431. }
  27432. },{}],131:[function(require,module,exports){
  27433. var MediaStreamType = {
  27434. VIDEO_TYPE: "Video",
  27435. AUDIO_TYPE: "Audio"
  27436. };
  27437. module.exports = MediaStreamType;
  27438. },{}],132:[function(require,module,exports){
  27439. var RTCEvents = {
  27440. RTC_READY: "rtc.ready",
  27441. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  27442. LASTN_CHANGED: "rtc.lastn_changed",
  27443. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  27444. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  27445. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  27446. };
  27447. module.exports = RTCEvents;
  27448. },{}],133:[function(require,module,exports){
  27449. var Resolutions = {
  27450. "1080": {
  27451. width: 1920,
  27452. height: 1080,
  27453. order: 7
  27454. },
  27455. "fullhd": {
  27456. width: 1920,
  27457. height: 1080,
  27458. order: 7
  27459. },
  27460. "720": {
  27461. width: 1280,
  27462. height: 720,
  27463. order: 6
  27464. },
  27465. "hd": {
  27466. width: 1280,
  27467. height: 720,
  27468. order: 6
  27469. },
  27470. "960": {
  27471. width: 960,
  27472. height: 720,
  27473. order: 5
  27474. },
  27475. "640": {
  27476. width: 640,
  27477. height: 480,
  27478. order: 4
  27479. },
  27480. "vga": {
  27481. width: 640,
  27482. height: 480,
  27483. order: 4
  27484. },
  27485. "360": {
  27486. width: 640,
  27487. height: 360,
  27488. order: 3
  27489. },
  27490. "320": {
  27491. width: 320,
  27492. height: 240,
  27493. order: 2
  27494. },
  27495. "180": {
  27496. width: 320,
  27497. height: 180,
  27498. order: 1
  27499. }
  27500. };
  27501. module.exports = Resolutions;
  27502. },{}],134:[function(require,module,exports){
  27503. var AuthenticationEvents = {
  27504. /**
  27505. * Event callback arguments:
  27506. * function(authenticationEnabled, userIdentity)
  27507. * authenticationEnabled - indicates whether authentication has been enabled
  27508. * in this session
  27509. * userIdentity - if user has been logged in then it contains user name. If
  27510. * contains 'null' or 'undefined' then user is not logged in.
  27511. */
  27512. IDENTITY_UPDATED: "authentication.identity_updated"
  27513. };
  27514. module.exports = AuthenticationEvents;
  27515. },{}],135:[function(require,module,exports){
  27516. var DesktopSharingEventTypes = {
  27517. /**
  27518. * An event which indicates that the jidesha extension for Firefox is
  27519. * needed to proceed with screen sharing, and that it is not installed.
  27520. */
  27521. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  27522. };
  27523. module.exports = DesktopSharingEventTypes;
  27524. },{}],136:[function(require,module,exports){
  27525. module.exports = {
  27526. /**
  27527. * An event carrying connection statistics.
  27528. */
  27529. CONNECTION_STATS: "statistics.connectionstats",
  27530. /**
  27531. * FIXME: needs documentation.
  27532. */
  27533. AUDIO_LEVEL: "statistics.audioLevel",
  27534. /**
  27535. * FIXME: needs documentation.
  27536. */
  27537. STOP: "statistics.stop"
  27538. };
  27539. },{}],137:[function(require,module,exports){
  27540. var Constants = {
  27541. LOCAL_JID: 'local'
  27542. };
  27543. module.exports = Constants;
  27544. },{}],138:[function(require,module,exports){
  27545. var XMPPEvents = {
  27546. // Designates an event indicating that the connection to the XMPP server
  27547. // failed.
  27548. CONNECTION_FAILED: "xmpp.connection.failed",
  27549. // Designates an event indicating that the media (ICE) connection was
  27550. // interrupted. This should go to the RTC module.
  27551. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  27552. // Designates an event indicating that the media (ICE) connection was
  27553. // restored. This should go to the RTC module.
  27554. CONNECTION_RESTORED: "xmpp.connection.restored",
  27555. // Designates an event indicating that an offer (e.g. Jingle
  27556. // session-initiate) was received.
  27557. CALL_INCOMING: "xmpp.callincoming.jingle",
  27558. // Designates an event indicating that we were kicked from the XMPP MUC.
  27559. KICKED: "xmpp.kicked",
  27560. // Designates an event indicating that the userID for a specific JID has
  27561. // changed.
  27562. // Note: currently this event fires every time we receive presence from
  27563. // someone (regardless of whether or not the "userID" changed).
  27564. USER_ID_CHANGED: "xmpp.user_id_changed",
  27565. // Designates an event indicating that we have joined the XMPP MUC.
  27566. MUC_JOINED: "xmpp.muc_joined",
  27567. // Designates an event indicating that a participant joined the XMPP MUC.
  27568. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  27569. // Designates an event indicating that a participant left the XMPP MUC.
  27570. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  27571. // Designates an event indicating that the MUC role of a participant has
  27572. // changed.
  27573. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  27574. // Designates an event indicating that the XMPP MUC was destroyed.
  27575. MUC_DESTROYED: "xmpp.muc_destroyed",
  27576. // Designates an event indicating that the display name of a participant
  27577. // has changed.
  27578. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  27579. // Designates an event indicating that we received statistics from a
  27580. // participant in the MUC.
  27581. REMOTE_STATS: "xmpp.remote_stats",
  27582. // Designates an event indicating that our role in the XMPP MUC has changed.
  27583. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  27584. // Designates an event indicating that the subject of the XMPP MUC has
  27585. // changed.
  27586. SUBJECT_CHANGED: "xmpp.subject_changed",
  27587. // Designates an event indicating that an XMPP message in the MUC was
  27588. // received.
  27589. MESSAGE_RECEIVED: "xmpp.message_received",
  27590. // Designates an event indicating that we sent an XMPP message to the MUC.
  27591. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  27592. // Designates an event indicating that the video type (e.g. 'camera' or
  27593. // 'screen') for a participant has changed.
  27594. // Note: currently this event fires every time we receive presence from
  27595. // someone (regardless of whether or not the "video type" changed).
  27596. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  27597. // Designates an event indicating that a participant in the XMPP MUC has
  27598. // advertised that they have audio muted (or unmuted).
  27599. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  27600. // Designates an event indicating that a participant in the XMPP MUC has
  27601. // advertised that they have video muted (or unmuted).
  27602. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  27603. // Designates an event indicating that the focus has asked us to mute our
  27604. // audio.
  27605. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  27606. // Designates an event indicating that we should join the conference with
  27607. // audio and/or video muted.
  27608. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  27609. // Designates an event indicating that a remote participant's available
  27610. // devices (whether he supports a audio and/or video) changed.
  27611. // Note: currently this event fires every time we receive presence from
  27612. // someone (regardless of whether or not the devices changed).
  27613. DEVICE_AVAILABLE: "xmpp.device_available",
  27614. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  27615. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  27616. PASSWORD_REQUIRED: "xmpp.password_required",
  27617. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  27618. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  27619. ETHERPAD: "xmpp.etherpad",
  27620. BRIDGE_DOWN: "xmpp.bridge_down",
  27621. PRESENCE_STATUS: "xmpp.presence_status",
  27622. RESERVATION_ERROR: "xmpp.room_reservation_error",
  27623. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  27624. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  27625. // TODO: only used in a hack, should probably be removed.
  27626. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  27627. // TODO: only used in a hack, should probably be removed.
  27628. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  27629. // TODO: only used in a hack, should probably be removed.
  27630. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  27631. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  27632. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  27633. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  27634. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  27635. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  27636. // xmpp is connected and obtained user media
  27637. READY_TO_JOIN: 'xmpp.ready_to_join',
  27638. FOCUS_LEFT: "xmpp.focus_left",
  27639. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  27640. /**
  27641. * Indicates that recording state changed.
  27642. */
  27643. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  27644. /**
  27645. * Indicates that phone number changed.
  27646. */
  27647. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged",
  27648. /**
  27649. * Indicates error while create offer call.
  27650. */
  27651. CREATE_OFFER_FAILED: "xmpp.create_offer_failed",
  27652. /**
  27653. * Indicates error while create answer call.
  27654. */
  27655. CREATE_ANSWER_FAILED: "xmpp.create_answer_failed",
  27656. /**
  27657. * Indicates error while set local description.
  27658. */
  27659. SET_LOCAL_DESCRIPTION_FAILED: "xmpp.set_local_description_failed",
  27660. /**
  27661. * Indicates error while set remote description.
  27662. */
  27663. SET_REMOTE_DESCRIPTION_FAILED: "xmpp.set_remote_description_failed",
  27664. /**
  27665. * Indicates error while adding ice candidate.
  27666. */
  27667. ADD_ICE_CANDIDATE_FAILED: "xmpp.add_ice_candidate_failed"
  27668. };
  27669. module.exports = XMPPEvents;
  27670. },{}]},{},[7])(7)
  27671. });