You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.bundle.js 1.2MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853
  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.APP = 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. // Copyright Joyent, Inc. and other Node contributors.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a
  5. // copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9. // persons to whom the Software is furnished to do so, subject to the
  10. // following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included
  13. // in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. function EventEmitter() {
  23. this._events = this._events || {};
  24. this._maxListeners = this._maxListeners || undefined;
  25. }
  26. module.exports = EventEmitter;
  27. // Backwards-compat with node 0.10.x
  28. EventEmitter.EventEmitter = EventEmitter;
  29. EventEmitter.prototype._events = undefined;
  30. EventEmitter.prototype._maxListeners = undefined;
  31. // By default EventEmitters will print a warning if more than 10 listeners are
  32. // added to it. This is a useful default which helps finding memory leaks.
  33. EventEmitter.defaultMaxListeners = 10;
  34. // Obviously not all Emitters should be limited to 10. This function allows
  35. // that to be increased. Set to zero for unlimited.
  36. EventEmitter.prototype.setMaxListeners = function(n) {
  37. if (!isNumber(n) || n < 0 || isNaN(n))
  38. throw TypeError('n must be a positive number');
  39. this._maxListeners = n;
  40. return this;
  41. };
  42. EventEmitter.prototype.emit = function(type) {
  43. var er, handler, len, args, i, listeners;
  44. if (!this._events)
  45. this._events = {};
  46. // If there is no 'error' event listener then throw.
  47. if (type === 'error') {
  48. if (!this._events.error ||
  49. (isObject(this._events.error) && !this._events.error.length)) {
  50. er = arguments[1];
  51. if (er instanceof Error) {
  52. throw er; // Unhandled 'error' event
  53. }
  54. throw TypeError('Uncaught, unspecified "error" event.');
  55. }
  56. }
  57. handler = this._events[type];
  58. if (isUndefined(handler))
  59. return false;
  60. if (isFunction(handler)) {
  61. switch (arguments.length) {
  62. // fast cases
  63. case 1:
  64. handler.call(this);
  65. break;
  66. case 2:
  67. handler.call(this, arguments[1]);
  68. break;
  69. case 3:
  70. handler.call(this, arguments[1], arguments[2]);
  71. break;
  72. // slower
  73. default:
  74. len = arguments.length;
  75. args = new Array(len - 1);
  76. for (i = 1; i < len; i++)
  77. args[i - 1] = arguments[i];
  78. handler.apply(this, args);
  79. }
  80. } else if (isObject(handler)) {
  81. len = arguments.length;
  82. args = new Array(len - 1);
  83. for (i = 1; i < len; i++)
  84. args[i - 1] = arguments[i];
  85. listeners = handler.slice();
  86. len = listeners.length;
  87. for (i = 0; i < len; i++)
  88. listeners[i].apply(this, args);
  89. }
  90. return true;
  91. };
  92. EventEmitter.prototype.addListener = function(type, listener) {
  93. var m;
  94. if (!isFunction(listener))
  95. throw TypeError('listener must be a function');
  96. if (!this._events)
  97. this._events = {};
  98. // To avoid recursion in the case that type === "newListener"! Before
  99. // adding it to the listeners, first emit "newListener".
  100. if (this._events.newListener)
  101. this.emit('newListener', type,
  102. isFunction(listener.listener) ?
  103. listener.listener : listener);
  104. if (!this._events[type])
  105. // Optimize the case of one listener. Don't need the extra array object.
  106. this._events[type] = listener;
  107. else if (isObject(this._events[type]))
  108. // If we've already got an array, just append.
  109. this._events[type].push(listener);
  110. else
  111. // Adding the second element, need to change to array.
  112. this._events[type] = [this._events[type], listener];
  113. // Check for listener leak
  114. if (isObject(this._events[type]) && !this._events[type].warned) {
  115. var m;
  116. if (!isUndefined(this._maxListeners)) {
  117. m = this._maxListeners;
  118. } else {
  119. m = EventEmitter.defaultMaxListeners;
  120. }
  121. if (m && m > 0 && this._events[type].length > m) {
  122. this._events[type].warned = true;
  123. console.error('(node) warning: possible EventEmitter memory ' +
  124. 'leak detected. %d listeners added. ' +
  125. 'Use emitter.setMaxListeners() to increase limit.',
  126. this._events[type].length);
  127. if (typeof console.trace === 'function') {
  128. // not supported in IE 10
  129. console.trace();
  130. }
  131. }
  132. }
  133. return this;
  134. };
  135. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  136. EventEmitter.prototype.once = function(type, listener) {
  137. if (!isFunction(listener))
  138. throw TypeError('listener must be a function');
  139. var fired = false;
  140. function g() {
  141. this.removeListener(type, g);
  142. if (!fired) {
  143. fired = true;
  144. listener.apply(this, arguments);
  145. }
  146. }
  147. g.listener = listener;
  148. this.on(type, g);
  149. return this;
  150. };
  151. // emits a 'removeListener' event iff the listener was removed
  152. EventEmitter.prototype.removeListener = function(type, listener) {
  153. var list, position, length, i;
  154. if (!isFunction(listener))
  155. throw TypeError('listener must be a function');
  156. if (!this._events || !this._events[type])
  157. return this;
  158. list = this._events[type];
  159. length = list.length;
  160. position = -1;
  161. if (list === listener ||
  162. (isFunction(list.listener) && list.listener === listener)) {
  163. delete this._events[type];
  164. if (this._events.removeListener)
  165. this.emit('removeListener', type, listener);
  166. } else if (isObject(list)) {
  167. for (i = length; i-- > 0;) {
  168. if (list[i] === listener ||
  169. (list[i].listener && list[i].listener === listener)) {
  170. position = i;
  171. break;
  172. }
  173. }
  174. if (position < 0)
  175. return this;
  176. if (list.length === 1) {
  177. list.length = 0;
  178. delete this._events[type];
  179. } else {
  180. list.splice(position, 1);
  181. }
  182. if (this._events.removeListener)
  183. this.emit('removeListener', type, listener);
  184. }
  185. return this;
  186. };
  187. EventEmitter.prototype.removeAllListeners = function(type) {
  188. var key, listeners;
  189. if (!this._events)
  190. return this;
  191. // not listening for removeListener, no need to emit
  192. if (!this._events.removeListener) {
  193. if (arguments.length === 0)
  194. this._events = {};
  195. else if (this._events[type])
  196. delete this._events[type];
  197. return this;
  198. }
  199. // emit removeListener for all listeners on all events
  200. if (arguments.length === 0) {
  201. for (key in this._events) {
  202. if (key === 'removeListener') continue;
  203. this.removeAllListeners(key);
  204. }
  205. this.removeAllListeners('removeListener');
  206. this._events = {};
  207. return this;
  208. }
  209. listeners = this._events[type];
  210. if (isFunction(listeners)) {
  211. this.removeListener(type, listeners);
  212. } else {
  213. // LIFO order
  214. while (listeners.length)
  215. this.removeListener(type, listeners[listeners.length - 1]);
  216. }
  217. delete this._events[type];
  218. return this;
  219. };
  220. EventEmitter.prototype.listeners = function(type) {
  221. var ret;
  222. if (!this._events || !this._events[type])
  223. ret = [];
  224. else if (isFunction(this._events[type]))
  225. ret = [this._events[type]];
  226. else
  227. ret = this._events[type].slice();
  228. return ret;
  229. };
  230. EventEmitter.listenerCount = function(emitter, type) {
  231. var ret;
  232. if (!emitter._events || !emitter._events[type])
  233. ret = 0;
  234. else if (isFunction(emitter._events[type]))
  235. ret = 1;
  236. else
  237. ret = emitter._events[type].length;
  238. return ret;
  239. };
  240. function isFunction(arg) {
  241. return typeof arg === 'function';
  242. }
  243. function isNumber(arg) {
  244. return typeof arg === 'number';
  245. }
  246. function isObject(arg) {
  247. return typeof arg === 'object' && arg !== null;
  248. }
  249. function isUndefined(arg) {
  250. return arg === void 0;
  251. }
  252. },{}],2:[function(require,module,exports){
  253. // shim for using process in browser
  254. var process = module.exports = {};
  255. var queue = [];
  256. var draining = false;
  257. var currentQueue;
  258. var queueIndex = -1;
  259. function cleanUpNextTick() {
  260. draining = false;
  261. if (currentQueue.length) {
  262. queue = currentQueue.concat(queue);
  263. } else {
  264. queueIndex = -1;
  265. }
  266. if (queue.length) {
  267. drainQueue();
  268. }
  269. }
  270. function drainQueue() {
  271. if (draining) {
  272. return;
  273. }
  274. var timeout = setTimeout(cleanUpNextTick);
  275. draining = true;
  276. var len = queue.length;
  277. while(len) {
  278. currentQueue = queue;
  279. queue = [];
  280. while (++queueIndex < len) {
  281. currentQueue[queueIndex].run();
  282. }
  283. queueIndex = -1;
  284. len = queue.length;
  285. }
  286. currentQueue = null;
  287. draining = false;
  288. clearTimeout(timeout);
  289. }
  290. process.nextTick = function (fun) {
  291. var args = new Array(arguments.length - 1);
  292. if (arguments.length > 1) {
  293. for (var i = 1; i < arguments.length; i++) {
  294. args[i - 1] = arguments[i];
  295. }
  296. }
  297. queue.push(new Item(fun, args));
  298. if (queue.length === 1 && !draining) {
  299. setTimeout(drainQueue, 0);
  300. }
  301. };
  302. // v8 likes predictible objects
  303. function Item(fun, array) {
  304. this.fun = fun;
  305. this.array = array;
  306. }
  307. Item.prototype.run = function () {
  308. this.fun.apply(null, this.array);
  309. };
  310. process.title = 'browser';
  311. process.browser = true;
  312. process.env = {};
  313. process.argv = [];
  314. process.version = ''; // empty string to avoid regexp issues
  315. process.versions = {};
  316. function noop() {}
  317. process.on = noop;
  318. process.addListener = noop;
  319. process.once = noop;
  320. process.off = noop;
  321. process.removeListener = noop;
  322. process.removeAllListeners = noop;
  323. process.emit = noop;
  324. process.binding = function (name) {
  325. throw new Error('process.binding is not supported');
  326. };
  327. // TODO(shtylman)
  328. process.cwd = function () { return '/' };
  329. process.chdir = function (dir) {
  330. throw new Error('process.chdir is not supported');
  331. };
  332. process.umask = function() { return 0; };
  333. },{}],3:[function(require,module,exports){
  334. /* jshint -W117 */
  335. /* application specific logic */
  336. var APP =
  337. {
  338. init: function () {
  339. this.UI = require("./modules/UI/UI");
  340. this.API = require("./modules/API/API");
  341. this.connectionquality = require("./modules/connectionquality/connectionquality");
  342. this.statistics = require("./modules/statistics/statistics");
  343. this.RTC = require("./modules/RTC/RTC");
  344. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  345. this.xmpp = require("./modules/xmpp/xmpp");
  346. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  347. this.translation = require("./modules/translation/translation");
  348. this.settings = require("./modules/settings/Settings");
  349. this.DTMF = require("./modules/DTMF/DTMF");
  350. this.members = require("./modules/members/MemberList");
  351. this.configFetch = require("./modules/config/HttpConfigFetch");
  352. }
  353. };
  354. function init() {
  355. APP.desktopsharing.init();
  356. APP.RTC.start();
  357. APP.xmpp.start();
  358. APP.statistics.start();
  359. APP.connectionquality.init();
  360. APP.keyboardshortcut.init();
  361. APP.members.start();
  362. }
  363. /**
  364. * If we have HTTP endpoint for getting confgi.json configured we're going to
  365. * read it and override properties from config.js and interfaceConfig.js.
  366. * If there is no endpoint we'll just continue with initialization.
  367. * Keep in mind that if the endpoint has been configured and we fail to obtain
  368. * the config for any reason then the conference won't start and error message
  369. * will be displayed to the user.
  370. */
  371. function obtainConfigAndInit() {
  372. if (config.configLocation) {
  373. APP.configFetch.obtainConfig(
  374. config.configLocation, APP.UI.getRoomNode(),
  375. // Get config result callback
  376. function(success, error) {
  377. if (success) {
  378. init();
  379. } else {
  380. // Show obtain config error,
  381. // pass the error object for report
  382. APP.UI.messageHandler.openReportDialog(
  383. null, "dialog.connectError", error);
  384. }
  385. });
  386. } else {
  387. init();
  388. }
  389. }
  390. $(document).ready(function () {
  391. var URLProcessor = require("./modules/config/URLProcessor");
  392. URLProcessor.setConfigParametersFromUrl();
  393. APP.init();
  394. APP.translation.init();
  395. if(APP.API.isEnabled())
  396. APP.API.init();
  397. APP.UI.start(obtainConfigAndInit);
  398. });
  399. $(window).bind('beforeunload', function () {
  400. if(APP.API.isEnabled())
  401. APP.API.dispose();
  402. });
  403. module.exports = APP;
  404. },{"./modules/API/API":4,"./modules/DTMF/DTMF":5,"./modules/RTC/RTC":9,"./modules/UI/UI":13,"./modules/config/HttpConfigFetch":44,"./modules/config/URLProcessor":45,"./modules/connectionquality/connectionquality":47,"./modules/desktopsharing/desktopsharing":48,"./modules/keyboardshortcut/keyboardshortcut":49,"./modules/members/MemberList":50,"./modules/settings/Settings":51,"./modules/statistics/statistics":55,"./modules/translation/translation":56,"./modules/xmpp/xmpp":73}],4:[function(require,module,exports){
  405. /* global APP */
  406. /**
  407. * Implements API class that communicates with external api class
  408. * and provides interface to access Jitsi Meet features by external
  409. * applications that embed Jitsi Meet
  410. */
  411. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  412. /**
  413. * List of the available commands.
  414. * @type {{
  415. * displayName: inputDisplayNameHandler,
  416. * toggleAudio: toggleAudio,
  417. * toggleVideo: toggleVideo,
  418. * toggleFilmStrip: toggleFilmStrip,
  419. * toggleChat: toggleChat,
  420. * toggleContactList: toggleContactList
  421. * }}
  422. */
  423. var commands = {};
  424. function initCommands() {
  425. commands = {
  426. displayName: APP.UI.inputDisplayNameHandler,
  427. toggleAudio: APP.UI.toggleAudio,
  428. toggleVideo: APP.UI.toggleVideo,
  429. toggleFilmStrip: APP.UI.toggleFilmStrip,
  430. toggleChat: APP.UI.toggleChat,
  431. toggleContactList: APP.UI.toggleContactList
  432. };
  433. }
  434. /**
  435. * Maps the supported events and their status
  436. * (true it the event is enabled and false if it is disabled)
  437. * @type {{
  438. * incomingMessage: boolean,
  439. * outgoingMessage: boolean,
  440. * displayNameChange: boolean,
  441. * participantJoined: boolean,
  442. * participantLeft: boolean
  443. * }}
  444. */
  445. var events = {
  446. incomingMessage: false,
  447. outgoingMessage:false,
  448. displayNameChange: false,
  449. participantJoined: false,
  450. participantLeft: false
  451. };
  452. var displayName = {};
  453. /**
  454. * Processes commands from external application.
  455. * @param message the object with the command
  456. */
  457. function processCommand(message) {
  458. if (message.action != "execute") {
  459. console.error("Unknown action of the message");
  460. return;
  461. }
  462. for (var key in message) {
  463. if(commands[key])
  464. commands[key].apply(null, message[key]);
  465. }
  466. }
  467. /**
  468. * Processes events objects from external applications
  469. * @param event the event
  470. */
  471. function processEvent(event) {
  472. if (!event.action) {
  473. console.error("Event with no action is received.");
  474. return;
  475. }
  476. var i = 0;
  477. switch(event.action) {
  478. case "add":
  479. for (; i < event.events.length; i++) {
  480. events[event.events[i]] = true;
  481. }
  482. break;
  483. case "remove":
  484. for (; i < event.events.length; i++) {
  485. events[event.events[i]] = false;
  486. }
  487. break;
  488. default:
  489. console.error("Unknown action for event.");
  490. }
  491. }
  492. /**
  493. * Sends message to the external application.
  494. * @param object
  495. */
  496. function sendMessage(object) {
  497. window.parent.postMessage(JSON.stringify(object), "*");
  498. }
  499. /**
  500. * Processes a message event from the external application
  501. * @param event the message event
  502. */
  503. function processMessage(event) {
  504. var message;
  505. try {
  506. message = JSON.parse(event.data);
  507. } catch (e) {}
  508. if(!message.type)
  509. return;
  510. switch (message.type) {
  511. case "command":
  512. processCommand(message);
  513. break;
  514. case "event":
  515. processEvent(message);
  516. break;
  517. default:
  518. console.error("Unknown type of the message");
  519. return;
  520. }
  521. }
  522. function setupListeners() {
  523. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  524. API.triggerEvent("participantJoined", {jid: from});
  525. });
  526. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  527. if (from != myjid)
  528. API.triggerEvent("incomingMessage",
  529. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  530. });
  531. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  532. API.triggerEvent("participantLeft", {jid: jid});
  533. });
  534. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  535. var name = displayName[jid];
  536. if(!name || name != newDisplayName) {
  537. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  538. displayName[jid] = newDisplayName;
  539. }
  540. });
  541. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  542. APP.API.triggerEvent("outgoingMessage", {"message": body});
  543. });
  544. }
  545. var API = {
  546. /**
  547. * Check whether the API should be enabled or not.
  548. * @returns {boolean}
  549. */
  550. isEnabled: function () {
  551. var hash = location.hash;
  552. if (hash && hash.indexOf("external") > -1 && window.postMessage)
  553. return true;
  554. return false;
  555. },
  556. /**
  557. * Initializes the APIConnector. Setups message event listeners that will
  558. * receive information from external applications that embed Jitsi Meet.
  559. * It also sends a message to the external application that APIConnector
  560. * is initialized.
  561. */
  562. init: function () {
  563. initCommands();
  564. if (window.addEventListener) {
  565. window.addEventListener('message',
  566. processMessage, false);
  567. }
  568. else {
  569. window.attachEvent('onmessage', processMessage);
  570. }
  571. sendMessage({type: "system", loaded: true});
  572. setupListeners();
  573. },
  574. /**
  575. * Checks whether the event is enabled ot not.
  576. * @param name the name of the event.
  577. * @returns {*}
  578. */
  579. isEventEnabled: function (name) {
  580. return events[name];
  581. },
  582. /**
  583. * Sends event object to the external application that has been subscribed
  584. * for that event.
  585. * @param name the name event
  586. * @param object data associated with the event
  587. */
  588. triggerEvent: function (name, object) {
  589. if(this.isEnabled() && this.isEventEnabled(name))
  590. sendMessage({
  591. type: "event", action: "result", event: name, result: object});
  592. },
  593. /**
  594. * Removes the listeners.
  595. */
  596. dispose: function () {
  597. if(window.removeEventListener) {
  598. window.removeEventListener("message",
  599. processMessage, false);
  600. }
  601. else {
  602. window.detachEvent('onmessage', processMessage);
  603. }
  604. }
  605. };
  606. module.exports = API;
  607. },{"../../service/xmpp/XMPPEvents":174}],5:[function(require,module,exports){
  608. /* global APP */
  609. /**
  610. * A module for sending DTMF tones.
  611. */
  612. var DTMFSender;
  613. var initDtmfSender = function() {
  614. // TODO: This needs to reset this if the peerconnection changes
  615. // (e.g. the call is re-made)
  616. if (DTMFSender)
  617. return;
  618. var localAudio = APP.RTC.localAudio;
  619. if (localAudio && localAudio.getTracks().length > 0)
  620. {
  621. var peerconnection
  622. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  623. if (peerconnection) {
  624. DTMFSender =
  625. peerconnection.peerconnection
  626. .createDTMFSender(localAudio.getTracks()[0]);
  627. console.log("Initialized DTMFSender");
  628. }
  629. else {
  630. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  631. }
  632. }
  633. else {
  634. console.log("Failed to initialize DTMFSender: no audio track.");
  635. }
  636. };
  637. var DTMF = {
  638. sendTones: function (tones, duration, pause) {
  639. if (!DTMFSender)
  640. initDtmfSender();
  641. if (DTMFSender){
  642. DTMFSender.insertDTMF(tones,
  643. (duration || 200),
  644. (pause || 200));
  645. }
  646. }
  647. };
  648. module.exports = DTMF;
  649. },{}],6:[function(require,module,exports){
  650. /* global config, APP, Strophe */
  651. // cache datachannels to avoid garbage collection
  652. // https://code.google.com/p/chromium/issues/detail?id=405545
  653. var RTCEvents = require("../../service/RTC/RTCEvents");
  654. var _dataChannels = [];
  655. var eventEmitter = null;
  656. var DataChannels = {
  657. /**
  658. * Callback triggered by PeerConnection when new data channel is opened
  659. * on the bridge.
  660. * @param event the event info object.
  661. */
  662. onDataChannel: function (event) {
  663. var dataChannel = event.channel;
  664. dataChannel.onopen = function () {
  665. console.info("Data channel opened by the Videobridge!", dataChannel);
  666. // Code sample for sending string and/or binary data
  667. // Sends String message to the bridge
  668. //dataChannel.send("Hello bridge!");
  669. // Sends 12 bytes binary message to the bridge
  670. //dataChannel.send(new ArrayBuffer(12));
  671. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  672. };
  673. dataChannel.onerror = function (error) {
  674. console.error("Data Channel Error:", error, dataChannel);
  675. };
  676. dataChannel.onmessage = function (event) {
  677. var data = event.data;
  678. // JSON
  679. var obj;
  680. try {
  681. obj = JSON.parse(data);
  682. }
  683. catch (e) {
  684. console.error(
  685. "Failed to parse data channel message as JSON: ",
  686. data,
  687. dataChannel);
  688. }
  689. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  690. var colibriClass = obj.colibriClass;
  691. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  692. // Endpoint ID from the Videobridge.
  693. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  694. console.info(
  695. "Data channel new dominant speaker event: ",
  696. dominantSpeakerEndpoint);
  697. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  698. }
  699. else if ("InLastNChangeEvent" === colibriClass) {
  700. var oldValue = obj.oldValue;
  701. var newValue = obj.newValue;
  702. // Make sure that oldValue and newValue are of type boolean.
  703. var type;
  704. if ((type = typeof oldValue) !== 'boolean') {
  705. if (type === 'string') {
  706. oldValue = (oldValue == "true");
  707. } else {
  708. oldValue = new Boolean(oldValue).valueOf();
  709. }
  710. }
  711. if ((type = typeof newValue) !== 'boolean') {
  712. if (type === 'string') {
  713. newValue = (newValue == "true");
  714. } else {
  715. newValue = new Boolean(newValue).valueOf();
  716. }
  717. }
  718. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  719. }
  720. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  721. // The new/latest list of last-n endpoint IDs.
  722. var lastNEndpoints = obj.lastNEndpoints;
  723. // The list of endpoint IDs which are entering the list of
  724. // last-n at this time i.e. were not in the old list of last-n
  725. // endpoint IDs.
  726. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  727. console.log(
  728. "Data channel new last-n event: ",
  729. lastNEndpoints, endpointsEnteringLastN, obj);
  730. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  731. lastNEndpoints, endpointsEnteringLastN, obj);
  732. }
  733. else {
  734. console.debug("Data channel JSON-formatted message: ", obj);
  735. }
  736. }
  737. };
  738. dataChannel.onclose = function () {
  739. console.info("The Data Channel closed", dataChannel);
  740. var idx = _dataChannels.indexOf(dataChannel);
  741. if (idx > -1)
  742. _dataChannels = _dataChannels.splice(idx, 1);
  743. };
  744. _dataChannels.push(dataChannel);
  745. },
  746. /**
  747. * Binds "ondatachannel" event listener to given PeerConnection instance.
  748. * @param peerConnection WebRTC peer connection instance.
  749. */
  750. init: function (peerConnection, emitter) {
  751. if(!config.openSctp)
  752. return;
  753. peerConnection.ondatachannel = this.onDataChannel;
  754. eventEmitter = emitter;
  755. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  756. // Although it's not a requirement to open separate channels from both bridge
  757. // and peer as single channel can be used for sending and receiving data.
  758. // So either channel opened by the bridge or the one opened here is enough
  759. // for communication with the bridge.
  760. /*var dataChannelOptions =
  761. {
  762. reliable: true
  763. };
  764. var dataChannel
  765. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  766. // Can be used only when is in open state
  767. dataChannel.onopen = function ()
  768. {
  769. dataChannel.send("My channel !!!");
  770. };
  771. dataChannel.onmessage = function (event)
  772. {
  773. var msgData = event.data;
  774. console.info("Got My Data Channel Message:", msgData, dataChannel);
  775. };*/
  776. },
  777. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  778. handlePinnedEndpointEvent: onPinnedEndpointChanged
  779. };
  780. function onSelectedEndpointChanged(userResource) {
  781. console.log('selected endpoint changed: ', userResource);
  782. if (_dataChannels && _dataChannels.length != 0) {
  783. _dataChannels.some(function (dataChannel) {
  784. if (dataChannel.readyState == 'open') {
  785. console.log('sending selected endpoint changed ' +
  786. 'notification to the bridge: ', userResource);
  787. dataChannel.send(JSON.stringify({
  788. 'colibriClass': 'SelectedEndpointChangedEvent',
  789. 'selectedEndpoint':
  790. (!userResource || userResource === null)?
  791. null : userResource
  792. }));
  793. return true;
  794. }
  795. });
  796. }
  797. }
  798. function onPinnedEndpointChanged(userResource) {
  799. console.log('pinned endpoint changed: ', userResource);
  800. if (_dataChannels && _dataChannels.length != 0) {
  801. _dataChannels.some(function (dataChannel) {
  802. if (dataChannel.readyState == 'open') {
  803. dataChannel.send(JSON.stringify({
  804. 'colibriClass': 'PinnedEndpointChangedEvent',
  805. 'pinnedEndpoint':
  806. (!userResource || userResource == null)?
  807. null : userResource
  808. }));
  809. return true;
  810. }
  811. });
  812. }
  813. }
  814. module.exports = DataChannels;
  815. },{"../../service/RTC/RTCEvents":165}],7:[function(require,module,exports){
  816. /* global APP */
  817. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  818. var RTCEvents = require("../../service/RTC/RTCEvents");
  819. var RTCBrowserType = require("./RTCBrowserType");
  820. /**
  821. * This implements 'onended' callback normally fired by WebRTC after the stream
  822. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  823. * @param stream original WebRTC stream object to which 'onended' handling
  824. * will be added.
  825. */
  826. function implementOnEndedHandling(stream) {
  827. var originalStop = stream.stop;
  828. stream.stop = function () {
  829. originalStop.apply(stream);
  830. if (!stream.ended) {
  831. stream.ended = true;
  832. stream.onended();
  833. }
  834. };
  835. }
  836. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  837. this.stream = stream;
  838. this.eventEmitter = eventEmitter;
  839. this.type = type;
  840. this.videoType = videoType;
  841. this.isGUMStream = true;
  842. if(isGUMStream === false)
  843. this.isGUMStream = isGUMStream;
  844. var self = this;
  845. if(type == "audio") {
  846. this.getTracks = function () {
  847. return self.stream.getAudioTracks();
  848. };
  849. } else {
  850. this.getTracks = function () {
  851. return self.stream.getVideoTracks();
  852. };
  853. }
  854. this.stream.onended = function () {
  855. self.streamEnded();
  856. };
  857. if (RTCBrowserType.isFirefox()) {
  858. implementOnEndedHandling(this.stream);
  859. }
  860. }
  861. LocalStream.prototype.streamEnded = function () {
  862. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  863. };
  864. LocalStream.prototype.getOriginalStream = function()
  865. {
  866. return this.stream;
  867. };
  868. LocalStream.prototype.isAudioStream = function () {
  869. return this.type === "audio";
  870. };
  871. LocalStream.prototype.setMute = function (mute)
  872. {
  873. var isAudio = this.isAudioStream();
  874. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  875. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  876. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  877. // FIXME FF does not support 'removeStream' method used to mute
  878. RTCBrowserType.isFirefox()) {
  879. var tracks = this.getTracks();
  880. for (var idx = 0; idx < tracks.length; idx++) {
  881. tracks[idx].enabled = !mute;
  882. }
  883. this.eventEmitter.emit(eventType, mute);
  884. } else {
  885. if (mute) {
  886. APP.xmpp.removeStream(this.stream);
  887. this.stream.stop();
  888. this.eventEmitter.emit(eventType, true);
  889. } else {
  890. var self = this;
  891. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  892. (this.isAudioStream() ? ["audio"] : ["video"]),
  893. function (stream) {
  894. if (isAudio) {
  895. APP.RTC.changeLocalAudio(stream,
  896. function () {
  897. self.eventEmitter.emit(eventType, false);
  898. });
  899. } else {
  900. APP.RTC.changeLocalVideo(stream, false,
  901. function () {
  902. self.eventEmitter.emit(eventType, false);
  903. });
  904. }
  905. });
  906. }
  907. }
  908. };
  909. LocalStream.prototype.isMuted = function () {
  910. var tracks = [];
  911. if (this.isAudioStream()) {
  912. tracks = this.stream.getAudioTracks();
  913. } else {
  914. if (this.stream.ended)
  915. return true;
  916. tracks = this.stream.getVideoTracks();
  917. }
  918. for (var idx = 0; idx < tracks.length; idx++) {
  919. if(tracks[idx].enabled)
  920. return false;
  921. }
  922. return true;
  923. };
  924. LocalStream.prototype.getId = function () {
  925. return this.stream.getTracks()[0].id;
  926. };
  927. module.exports = LocalStream;
  928. },{"../../service/RTC/RTCEvents":165,"../../service/RTC/StreamEventTypes.js":167,"./RTCBrowserType":10}],8:[function(require,module,exports){
  929. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  930. /**
  931. * Creates a MediaStream object for the given data, session id and ssrc.
  932. * It is a wrapper class for the MediaStream.
  933. *
  934. * @param data the data object from which we obtain the stream,
  935. * the peerjid, etc.
  936. * @param sid the session id
  937. * @param ssrc the ssrc corresponding to this MediaStream
  938. *
  939. * @constructor
  940. */
  941. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  942. // XXX(gp) to minimize headaches in the future, we should build our
  943. // abstractions around tracks and not streams. ORTC is track based API.
  944. // Mozilla expects m-lines to represent media tracks.
  945. //
  946. // Practically, what I'm saying is that we should have a MediaTrack class
  947. // and not a MediaStream class.
  948. //
  949. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  950. // a track might have an associated RTX and FEC sources.
  951. this.sid = sid;
  952. this.stream = data.stream;
  953. this.peerjid = data.peerjid;
  954. this.videoType = data.videoType;
  955. this.ssrc = ssrc;
  956. this.type = (this.stream.getVideoTracks().length > 0)?
  957. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  958. this.muted = false;
  959. this.eventEmitter = eventEmitter;
  960. }
  961. MediaStream.prototype.getOriginalStream = function() {
  962. return this.stream;
  963. };
  964. MediaStream.prototype.setMute = function (value) {
  965. this.stream.muted = value;
  966. this.muted = value;
  967. };
  968. module.exports = MediaStream;
  969. },{"../../service/RTC/MediaStreamTypes":164}],9:[function(require,module,exports){
  970. /* global APP */
  971. var EventEmitter = require("events");
  972. var RTCBrowserType = require("./RTCBrowserType");
  973. var RTCUtils = require("./RTCUtils.js");
  974. var LocalStream = require("./LocalStream.js");
  975. var DataChannels = require("./DataChannels");
  976. var MediaStream = require("./MediaStream.js");
  977. var DesktopSharingEventTypes
  978. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  979. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  980. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  981. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  982. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  983. var UIEvents = require("../../service/UI/UIEvents");
  984. var eventEmitter = new EventEmitter();
  985. function getMediaStreamUsage()
  986. {
  987. var result = {
  988. audio: true,
  989. video: true
  990. };
  991. /** There are some issues with the desktop sharing
  992. * when this property is enabled.
  993. * WARNING: We must change the implementation to start video/audio if we
  994. * receive from the focus that the peer is not muted.
  995. var isSecureConnection = window.location.protocol == "https:";
  996. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  997. {
  998. result = {
  999. audio: false,
  1000. video: false
  1001. };
  1002. }
  1003. **/
  1004. return result;
  1005. }
  1006. var RTC = {
  1007. rtcUtils: null,
  1008. devices: {
  1009. audio: true,
  1010. video: true
  1011. },
  1012. localStreams: [],
  1013. remoteStreams: {},
  1014. localAudio: null,
  1015. localVideo: null,
  1016. addStreamListener: function (listener, eventType) {
  1017. eventEmitter.on(eventType, listener);
  1018. },
  1019. addListener: function (type, listener) {
  1020. eventEmitter.on(type, listener);
  1021. },
  1022. removeStreamListener: function (listener, eventType) {
  1023. if(!(eventType instanceof StreamEventTypes))
  1024. throw "Illegal argument";
  1025. eventEmitter.removeListener(eventType, listener);
  1026. },
  1027. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  1028. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  1029. //in firefox we have only one stream object
  1030. if(this.localStreams.length == 0 ||
  1031. this.localStreams[0].getOriginalStream() != stream)
  1032. this.localStreams.push(localStream);
  1033. if(isMuted === true)
  1034. localStream.setMute(true);
  1035. if(type == "audio") {
  1036. this.localAudio = localStream;
  1037. } else {
  1038. this.localVideo = localStream;
  1039. }
  1040. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1041. if(change)
  1042. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  1043. eventEmitter.emit(eventType, localStream, isMuted);
  1044. return localStream;
  1045. },
  1046. removeLocalStream: function (stream) {
  1047. for(var i = 0; i < this.localStreams.length; i++) {
  1048. if(this.localStreams[i].getOriginalStream() === stream) {
  1049. delete this.localStreams[i];
  1050. return;
  1051. }
  1052. }
  1053. },
  1054. createRemoteStream: function (data, sid, thessrc) {
  1055. var remoteStream = new MediaStream(data, sid, thessrc,
  1056. RTCBrowserType.getBrowserType(), eventEmitter);
  1057. var jid = data.peerjid || APP.xmpp.myJid();
  1058. if(!this.remoteStreams[jid]) {
  1059. this.remoteStreams[jid] = {};
  1060. }
  1061. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1062. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1063. return remoteStream;
  1064. },
  1065. getPCConstraints: function () {
  1066. return this.rtcUtils.pc_constraints;
  1067. },
  1068. getUserMediaWithConstraints:function(um, success_callback,
  1069. failure_callback, resolution,
  1070. bandwidth, fps, desktopStream)
  1071. {
  1072. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  1073. failure_callback, resolution, bandwidth, fps, desktopStream);
  1074. },
  1075. attachMediaStream: function (elSelector, stream) {
  1076. this.rtcUtils.attachMediaStream(elSelector, stream);
  1077. },
  1078. getStreamID: function (stream) {
  1079. return this.rtcUtils.getStreamID(stream);
  1080. },
  1081. getVideoSrc: function (element) {
  1082. return this.rtcUtils.getVideoSrc(element);
  1083. },
  1084. setVideoSrc: function (element, src) {
  1085. this.rtcUtils.setVideoSrc(element, src);
  1086. },
  1087. getVideoElementName: function () {
  1088. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1089. },
  1090. dispose: function() {
  1091. if (this.rtcUtils) {
  1092. this.rtcUtils = null;
  1093. }
  1094. },
  1095. stop: function () {
  1096. this.dispose();
  1097. },
  1098. start: function () {
  1099. var self = this;
  1100. APP.desktopsharing.addListener(
  1101. function (stream, isUsingScreenStream, callback) {
  1102. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1103. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1104. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  1105. DataChannels.init(event.peerconnection, eventEmitter);
  1106. });
  1107. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  1108. DataChannels.handleSelectedEndpointEvent);
  1109. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1110. DataChannels.handlePinnedEndpointEvent);
  1111. // In case of IE we continue from 'onReady' callback
  1112. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1113. // once it is initialized.
  1114. var onReady = function () {
  1115. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1116. self.rtcUtils.obtainAudioAndVideoPermissions(
  1117. null, null, getMediaStreamUsage());
  1118. };
  1119. this.rtcUtils = new RTCUtils(this, onReady);
  1120. // Call onReady() if Temasys plugin is not used
  1121. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1122. onReady();
  1123. }
  1124. },
  1125. muteRemoteVideoStream: function (jid, value) {
  1126. var stream;
  1127. if(this.remoteStreams[jid] &&
  1128. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1129. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1130. }
  1131. if(!stream)
  1132. return true;
  1133. if (value != stream.muted) {
  1134. stream.setMute(value);
  1135. return true;
  1136. }
  1137. return false;
  1138. },
  1139. switchVideoStreams: function (new_stream) {
  1140. this.localVideo.stream = new_stream;
  1141. this.localStreams = [];
  1142. //in firefox we have only one stream object
  1143. if (this.localAudio.getOriginalStream() != new_stream)
  1144. this.localStreams.push(this.localAudio);
  1145. this.localStreams.push(this.localVideo);
  1146. },
  1147. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  1148. var oldStream = this.localVideo.getOriginalStream();
  1149. var type = (isUsingScreenStream ? "screen" : "camera");
  1150. var localCallback = callback;
  1151. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1152. localCallback = function() {
  1153. APP.xmpp.setVideoMute(false, function(mute) {
  1154. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1155. });
  1156. callback();
  1157. };
  1158. }
  1159. // FIXME: Workaround for FF/IE/Safari
  1160. if (stream && stream.videoStream) {
  1161. stream = stream.videoStream;
  1162. }
  1163. var videoStream = this.rtcUtils.createStream(stream, true);
  1164. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1165. // Stop the stream to trigger onended event for old stream
  1166. oldStream.stop();
  1167. this.switchVideoStreams(videoStream, oldStream);
  1168. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  1169. },
  1170. changeLocalAudio: function (stream, callback) {
  1171. var oldStream = this.localAudio.getOriginalStream();
  1172. var newStream = this.rtcUtils.createStream(stream);
  1173. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1174. // Stop the stream to trigger onended event for old stream
  1175. oldStream.stop();
  1176. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  1177. },
  1178. isVideoMuted: function (jid) {
  1179. if (jid === APP.xmpp.myJid()) {
  1180. var localVideo = APP.RTC.localVideo;
  1181. return (!localVideo || localVideo.isMuted());
  1182. } else {
  1183. if (!APP.RTC.remoteStreams[jid] ||
  1184. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1185. return null;
  1186. }
  1187. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1188. }
  1189. },
  1190. setVideoMute: function (mute, callback, options) {
  1191. if (!this.localVideo)
  1192. return;
  1193. if (mute == APP.RTC.localVideo.isMuted())
  1194. {
  1195. APP.xmpp.sendVideoInfoPresence(mute);
  1196. if (callback)
  1197. callback(mute);
  1198. }
  1199. else
  1200. {
  1201. APP.RTC.localVideo.setMute(mute);
  1202. APP.xmpp.setVideoMute(
  1203. mute,
  1204. callback,
  1205. options);
  1206. }
  1207. },
  1208. setDeviceAvailability: function (devices) {
  1209. if(!devices)
  1210. return;
  1211. if(devices.audio === true || devices.audio === false)
  1212. this.devices.audio = devices.audio;
  1213. if(devices.video === true || devices.video === false)
  1214. this.devices.video = devices.video;
  1215. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1216. }
  1217. };
  1218. module.exports = RTC;
  1219. },{"../../service/RTC/MediaStreamTypes":164,"../../service/RTC/RTCEvents.js":165,"../../service/RTC/StreamEventTypes.js":167,"../../service/UI/UIEvents":168,"../../service/desktopsharing/DesktopSharingEventTypes":171,"../../service/xmpp/XMPPEvents":174,"./DataChannels":6,"./LocalStream.js":7,"./MediaStream.js":8,"./RTCBrowserType":10,"./RTCUtils.js":11,"events":1}],10:[function(require,module,exports){
  1220. var currentBrowser;
  1221. var browserVersion;
  1222. var isAndroid;
  1223. var RTCBrowserType = {
  1224. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1225. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1226. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1227. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1228. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1229. getBrowserType: function () {
  1230. return currentBrowser;
  1231. },
  1232. isChrome: function () {
  1233. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1234. },
  1235. isOpera: function () {
  1236. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1237. },
  1238. isFirefox: function () {
  1239. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1240. },
  1241. isIExplorer: function () {
  1242. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1243. },
  1244. isSafari: function () {
  1245. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1246. },
  1247. isTemasysPluginUsed: function () {
  1248. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1249. },
  1250. getFirefoxVersion: function () {
  1251. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1252. },
  1253. getChromeVersion: function () {
  1254. return RTCBrowserType.isChrome() ? browserVersion : null;
  1255. },
  1256. usesPlanB: function() {
  1257. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1258. RTCBrowserType.isTemasysPluginUsed();
  1259. },
  1260. usesUnifiedPlan: function() {
  1261. return RTCBrowserType.isFirefox();
  1262. },
  1263. /**
  1264. * Whether the browser is running on an android device.
  1265. */
  1266. isAndroid: function() {
  1267. return isAndroid;
  1268. }
  1269. // Add version getters for other browsers when needed
  1270. };
  1271. // detectOpera() must be called before detectChrome() !!!
  1272. // otherwise Opera wil be detected as Chrome
  1273. function detectChrome() {
  1274. if (navigator.webkitGetUserMedia) {
  1275. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1276. var userAgent = navigator.userAgent.toLowerCase();
  1277. // We can assume that user agent is chrome, because it's
  1278. // enforced when 'ext' streaming method is set
  1279. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1280. console.log("This appears to be Chrome, ver: " + ver);
  1281. return ver;
  1282. }
  1283. return null;
  1284. }
  1285. function detectOpera() {
  1286. var userAgent = navigator.userAgent;
  1287. if (userAgent.match(/Opera|OPR/)) {
  1288. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1289. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1290. console.info("This appears to be Opera, ver: " + version);
  1291. return version;
  1292. }
  1293. return null;
  1294. }
  1295. function detectFirefox() {
  1296. if (navigator.mozGetUserMedia) {
  1297. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1298. var version = parseInt(
  1299. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1300. console.log('This appears to be Firefox, ver: ' + version);
  1301. return version;
  1302. }
  1303. return null;
  1304. }
  1305. function detectSafari() {
  1306. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1307. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1308. console.info("This appears to be Safari");
  1309. // FIXME detect Safari version when needed
  1310. return 1;
  1311. }
  1312. return null;
  1313. }
  1314. function detectIE() {
  1315. var version;
  1316. var ua = window.navigator.userAgent;
  1317. var msie = ua.indexOf('MSIE ');
  1318. if (msie > 0) {
  1319. // IE 10 or older => return version number
  1320. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1321. }
  1322. var trident = ua.indexOf('Trident/');
  1323. if (!version && trident > 0) {
  1324. // IE 11 => return version number
  1325. var rv = ua.indexOf('rv:');
  1326. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1327. }
  1328. var edge = ua.indexOf('Edge/');
  1329. if (!version && edge > 0) {
  1330. // IE 12 => return version number
  1331. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1332. }
  1333. if (version) {
  1334. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1335. console.info("This appears to be IExplorer, ver: " + version);
  1336. }
  1337. return version;
  1338. }
  1339. function detectBrowser() {
  1340. var version;
  1341. var detectors = [
  1342. detectOpera,
  1343. detectChrome,
  1344. detectFirefox,
  1345. detectIE,
  1346. detectSafari
  1347. ];
  1348. // Try all browser detectors
  1349. for (var i = 0; i < detectors.length; i++) {
  1350. version = detectors[i]();
  1351. if (version)
  1352. return version;
  1353. }
  1354. console.error("Failed to detect browser type");
  1355. return undefined;
  1356. }
  1357. browserVersion = detectBrowser();
  1358. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1359. module.exports = RTCBrowserType;
  1360. },{}],11:[function(require,module,exports){
  1361. /* global config, require, attachMediaStream, getUserMedia */
  1362. var RTCBrowserType = require("./RTCBrowserType");
  1363. var Resolutions = require("../../service/RTC/Resolutions");
  1364. var AdapterJS = require("./adapter.screenshare");
  1365. var SDPUtil = require("../xmpp/SDPUtil");
  1366. var currentResolution = null;
  1367. function getPreviousResolution(resolution) {
  1368. if(!Resolutions[resolution])
  1369. return null;
  1370. var order = Resolutions[resolution].order;
  1371. var res = null;
  1372. var resName = null;
  1373. for(var i in Resolutions) {
  1374. var tmp = Resolutions[i];
  1375. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1376. resName = i;
  1377. res = tmp;
  1378. }
  1379. }
  1380. return resName;
  1381. }
  1382. function setResolutionConstraints(constraints, resolution) {
  1383. var isAndroid = RTCBrowserType.isAndroid();
  1384. if (Resolutions[resolution]) {
  1385. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1386. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1387. }
  1388. else if (isAndroid) {
  1389. // FIXME can't remember if the purpose of this was to always request
  1390. // low resolution on Android ? if yes it should be moved up front
  1391. constraints.video.mandatory.minWidth = 320;
  1392. constraints.video.mandatory.minHeight = 240;
  1393. constraints.video.mandatory.maxFrameRate = 15;
  1394. }
  1395. if (constraints.video.mandatory.minWidth)
  1396. constraints.video.mandatory.maxWidth =
  1397. constraints.video.mandatory.minWidth;
  1398. if (constraints.video.mandatory.minHeight)
  1399. constraints.video.mandatory.maxHeight =
  1400. constraints.video.mandatory.minHeight;
  1401. }
  1402. function getConstraints(um, resolution, bandwidth, fps, desktopStream) {
  1403. var constraints = {audio: false, video: false};
  1404. if (um.indexOf('video') >= 0) {
  1405. // same behaviour as true
  1406. constraints.video = { mandatory: {}, optional: [] };
  1407. constraints.video.optional.push({ googLeakyBucket: true });
  1408. setResolutionConstraints(constraints, resolution);
  1409. }
  1410. if (um.indexOf('audio') >= 0) {
  1411. if (!RTCBrowserType.isFirefox()) {
  1412. // same behaviour as true
  1413. constraints.audio = { mandatory: {}, optional: []};
  1414. // if it is good enough for hangouts...
  1415. constraints.audio.optional.push(
  1416. {googEchoCancellation: true},
  1417. {googAutoGainControl: true},
  1418. {googNoiseSupression: true},
  1419. {googHighpassFilter: true},
  1420. {googNoisesuppression2: true},
  1421. {googEchoCancellation2: true},
  1422. {googAutoGainControl2: true}
  1423. );
  1424. } else {
  1425. constraints.audio = true;
  1426. }
  1427. }
  1428. if (um.indexOf('screen') >= 0) {
  1429. if (RTCBrowserType.isChrome()) {
  1430. constraints.video = {
  1431. mandatory: {
  1432. chromeMediaSource: "screen",
  1433. googLeakyBucket: true,
  1434. maxWidth: window.screen.width,
  1435. maxHeight: window.screen.height,
  1436. maxFrameRate: 3
  1437. },
  1438. optional: []
  1439. };
  1440. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1441. constraints.video = {
  1442. optional: [
  1443. {
  1444. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1445. }
  1446. ]
  1447. };
  1448. } else {
  1449. console.error(
  1450. "'screen' WebRTC media source is supported only in Chrome" +
  1451. " and with Temasys plugin");
  1452. }
  1453. }
  1454. if (um.indexOf('desktop') >= 0) {
  1455. constraints.video = {
  1456. mandatory: {
  1457. chromeMediaSource: "desktop",
  1458. chromeMediaSourceId: desktopStream,
  1459. googLeakyBucket: true,
  1460. maxWidth: window.screen.width,
  1461. maxHeight: window.screen.height,
  1462. maxFrameRate: 3
  1463. },
  1464. optional: []
  1465. };
  1466. }
  1467. if (bandwidth) {
  1468. if (!constraints.video) {
  1469. //same behaviour as true
  1470. constraints.video = {mandatory: {}, optional: []};
  1471. }
  1472. constraints.video.optional.push({bandwidth: bandwidth});
  1473. }
  1474. if (fps) {
  1475. // for some cameras it might be necessary to request 30fps
  1476. // so they choose 30fps mjpg over 10fps yuy2
  1477. if (!constraints.video) {
  1478. // same behaviour as true;
  1479. constraints.video = {mandatory: {}, optional: []};
  1480. }
  1481. constraints.video.mandatory.minFrameRate = fps;
  1482. }
  1483. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  1484. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  1485. // this later can be a problem with some of the tests
  1486. if(RTCBrowserType.isFirefox() && config.firefox_fake_device)
  1487. {
  1488. constraints.audio = true;
  1489. constraints.fake = true;
  1490. }
  1491. return constraints;
  1492. }
  1493. function RTCUtils(RTCService, onTemasysPluginReady)
  1494. {
  1495. var self = this;
  1496. this.service = RTCService;
  1497. if (RTCBrowserType.isFirefox()) {
  1498. var FFversion = RTCBrowserType.getFirefoxVersion();
  1499. if (FFversion >= 40) {
  1500. this.peerconnection = mozRTCPeerConnection;
  1501. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1502. this.pc_constraints = {};
  1503. this.attachMediaStream = function (element, stream) {
  1504. // srcObject is being standardized and FF will eventually
  1505. // support that unprefixed. FF also supports the
  1506. // "element.src = URL.createObjectURL(...)" combo, but that
  1507. // will be deprecated in favour of srcObject.
  1508. //
  1509. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1510. // https://github.com/webrtc/samples/issues/302
  1511. if(!element[0])
  1512. return;
  1513. element[0].mozSrcObject = stream;
  1514. element[0].play();
  1515. };
  1516. this.getStreamID = function (stream) {
  1517. var id = stream.id;
  1518. if (!id) {
  1519. var tracks = stream.getVideoTracks();
  1520. if (!tracks || tracks.length === 0) {
  1521. tracks = stream.getAudioTracks();
  1522. }
  1523. id = tracks[0].id;
  1524. }
  1525. return SDPUtil.filter_special_chars(id);
  1526. };
  1527. this.getVideoSrc = function (element) {
  1528. if(!element)
  1529. return null;
  1530. return element.mozSrcObject;
  1531. };
  1532. this.setVideoSrc = function (element, src) {
  1533. if(element)
  1534. element.mozSrcObject = src;
  1535. };
  1536. RTCSessionDescription = mozRTCSessionDescription;
  1537. RTCIceCandidate = mozRTCIceCandidate;
  1538. } else {
  1539. console.error(
  1540. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1541. window.location.href = 'unsupported_browser.html';
  1542. return;
  1543. }
  1544. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1545. this.peerconnection = webkitRTCPeerConnection;
  1546. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1547. this.attachMediaStream = function (element, stream) {
  1548. element.attr('src', webkitURL.createObjectURL(stream));
  1549. };
  1550. this.getStreamID = function (stream) {
  1551. // streams from FF endpoints have the characters '{' and '}'
  1552. // that make jQuery choke.
  1553. return SDPUtil.filter_special_chars(stream.id);
  1554. };
  1555. this.getVideoSrc = function (element) {
  1556. if(!element)
  1557. return null;
  1558. return element.getAttribute("src");
  1559. };
  1560. this.setVideoSrc = function (element, src) {
  1561. if(element)
  1562. element.setAttribute("src", src);
  1563. };
  1564. // DTLS should now be enabled by default but..
  1565. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1566. if (RTCBrowserType.isAndroid()) {
  1567. this.pc_constraints = {}; // disable DTLS on Android
  1568. }
  1569. if (!webkitMediaStream.prototype.getVideoTracks) {
  1570. webkitMediaStream.prototype.getVideoTracks = function () {
  1571. return this.videoTracks;
  1572. };
  1573. }
  1574. if (!webkitMediaStream.prototype.getAudioTracks) {
  1575. webkitMediaStream.prototype.getAudioTracks = function () {
  1576. return this.audioTracks;
  1577. };
  1578. }
  1579. }
  1580. // Detect IE/Safari
  1581. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1582. //AdapterJS.WebRTCPlugin.setLogLevel(
  1583. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1584. AdapterJS.webRTCReady(function (isPlugin) {
  1585. self.peerconnection = RTCPeerConnection;
  1586. self.getUserMedia = getUserMedia;
  1587. self.attachMediaStream = function (elSel, stream) {
  1588. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1589. return;
  1590. }
  1591. attachMediaStream(elSel[0], stream);
  1592. };
  1593. self.getStreamID = function (stream) {
  1594. var id = SDPUtil.filter_special_chars(stream.label);
  1595. return id;
  1596. };
  1597. self.getVideoSrc = function (element) {
  1598. if (!element) {
  1599. console.warn("Attempt to get video SRC of null element");
  1600. return null;
  1601. }
  1602. var children = element.children;
  1603. for (var i = 0; i !== children.length; ++i) {
  1604. if (children[i].name === 'streamId') {
  1605. return children[i].value;
  1606. }
  1607. }
  1608. //console.info(element.id + " SRC: " + src);
  1609. return null;
  1610. };
  1611. self.setVideoSrc = function (element, src) {
  1612. //console.info("Set video src: ", element, src);
  1613. if (!src) {
  1614. console.warn("Not attaching video stream, 'src' is null");
  1615. return;
  1616. }
  1617. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1618. var stream = AdapterJS.WebRTCPlugin.plugin
  1619. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1620. attachMediaStream(element, stream);
  1621. };
  1622. onTemasysPluginReady(isPlugin);
  1623. });
  1624. } else {
  1625. try {
  1626. console.log('Browser does not appear to be WebRTC-capable');
  1627. } catch (e) { }
  1628. window.location.href = 'unsupported_browser.html';
  1629. }
  1630. }
  1631. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1632. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1633. desktopStream) {
  1634. currentResolution = resolution;
  1635. var constraints = getConstraints(
  1636. um, resolution, bandwidth, fps, desktopStream);
  1637. console.info("Get media constraints", constraints);
  1638. var self = this;
  1639. try {
  1640. this.getUserMedia(constraints,
  1641. function (stream) {
  1642. console.log('onUserMediaSuccess');
  1643. self.setAvailableDevices(um, true);
  1644. success_callback(stream);
  1645. },
  1646. function (error) {
  1647. self.setAvailableDevices(um, false);
  1648. console.warn('Failed to get access to local media. Error ',
  1649. error, constraints);
  1650. if (failure_callback) {
  1651. failure_callback(error);
  1652. }
  1653. });
  1654. } catch (e) {
  1655. console.error('GUM failed: ', e);
  1656. if(failure_callback) {
  1657. failure_callback(e);
  1658. }
  1659. }
  1660. };
  1661. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1662. var devices = {};
  1663. if(um.indexOf("video") != -1) {
  1664. devices.video = available;
  1665. }
  1666. if(um.indexOf("audio") != -1) {
  1667. devices.audio = available;
  1668. }
  1669. this.service.setDeviceAvailability(devices);
  1670. };
  1671. /**
  1672. * We ask for audio and video combined stream in order to get permissions and
  1673. * not to ask twice.
  1674. */
  1675. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1676. function(devices, callback, usageOptions)
  1677. {
  1678. var self = this;
  1679. // Get AV
  1680. var successCallback = function (stream) {
  1681. if(callback)
  1682. callback(stream, usageOptions);
  1683. else
  1684. self.successCallback(stream, usageOptions);
  1685. };
  1686. if(!devices)
  1687. devices = ['audio', 'video'];
  1688. var newDevices = [];
  1689. if(usageOptions)
  1690. for(var i = 0; i < devices.length; i++) {
  1691. var device = devices[i];
  1692. if(usageOptions[device] === true)
  1693. newDevices.push(device);
  1694. }
  1695. else
  1696. newDevices = devices;
  1697. if(newDevices.length === 0) {
  1698. successCallback();
  1699. return;
  1700. }
  1701. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1702. // With FF/IE we can't split the stream into audio and video because FF
  1703. // doesn't support media stream constructors. So, we need to get the
  1704. // audio stream separately from the video stream using two distinct GUM
  1705. // calls. Not very user friendly :-( but we don't have many other
  1706. // options neither.
  1707. //
  1708. // Note that we pack those 2 streams in a single object and pass it to
  1709. // the successCallback method.
  1710. var obtainVideo = function (audioStream) {
  1711. self.getUserMediaWithConstraints(
  1712. ['video'],
  1713. function (videoStream) {
  1714. return successCallback({
  1715. audioStream: audioStream,
  1716. videoStream: videoStream
  1717. });
  1718. },
  1719. function (error) {
  1720. console.error(
  1721. 'failed to obtain video stream - stop', error);
  1722. self.errorCallback(error);
  1723. },
  1724. config.resolution || '360');
  1725. };
  1726. var obtainAudio = function () {
  1727. self.getUserMediaWithConstraints(
  1728. ['audio'],
  1729. function (audioStream) {
  1730. if (newDevices.indexOf('video') !== -1)
  1731. obtainVideo(audioStream);
  1732. },
  1733. function (error) {
  1734. console.error(
  1735. 'failed to obtain audio stream - stop', error);
  1736. self.errorCallback(error);
  1737. }
  1738. );
  1739. };
  1740. if (newDevices.indexOf('audio') !== -1) {
  1741. obtainAudio();
  1742. } else {
  1743. obtainVideo(null);
  1744. }
  1745. } else {
  1746. this.getUserMediaWithConstraints(
  1747. newDevices,
  1748. function (stream) {
  1749. successCallback(stream);
  1750. },
  1751. function (error) {
  1752. self.errorCallback(error);
  1753. },
  1754. config.resolution || '360');
  1755. }
  1756. };
  1757. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1758. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1759. // it's an object with two properties: audioStream, videoStream.
  1760. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1761. console.log('got', stream, stream.getAudioTracks().length,
  1762. stream.getVideoTracks().length);
  1763. this.handleLocalStream(stream, usageOptions);
  1764. };
  1765. RTCUtils.prototype.errorCallback = function (error) {
  1766. var self = this;
  1767. console.error('failed to obtain audio/video stream - trying audio only', error);
  1768. var resolution = getPreviousResolution(currentResolution);
  1769. if(typeof error == "object" && error.constraintName && error.name
  1770. && (error.name == "ConstraintNotSatisfiedError" ||
  1771. error.name == "OverconstrainedError") &&
  1772. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1773. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1774. && resolution != null)
  1775. {
  1776. self.getUserMediaWithConstraints(['audio', 'video'],
  1777. function (stream) {
  1778. return self.successCallback(stream);
  1779. }, function (error) {
  1780. return self.errorCallback(error);
  1781. }, resolution);
  1782. }
  1783. else {
  1784. self.getUserMediaWithConstraints(
  1785. ['audio'],
  1786. function (stream) {
  1787. return self.successCallback(stream);
  1788. },
  1789. function (error) {
  1790. console.error('failed to obtain audio/video stream - stop',
  1791. error);
  1792. return self.successCallback(null);
  1793. }
  1794. );
  1795. }
  1796. };
  1797. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1798. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1799. // an object with two properties: audioStream, videoStream.
  1800. var audioStream, videoStream;
  1801. if(window.webkitMediaStream)
  1802. {
  1803. audioStream = new webkitMediaStream();
  1804. videoStream = new webkitMediaStream();
  1805. if(stream) {
  1806. var audioTracks = stream.getAudioTracks();
  1807. for (var i = 0; i < audioTracks.length; i++) {
  1808. audioStream.addTrack(audioTracks[i]);
  1809. }
  1810. var videoTracks = stream.getVideoTracks();
  1811. for (i = 0; i < videoTracks.length; i++) {
  1812. videoStream.addTrack(videoTracks[i]);
  1813. }
  1814. }
  1815. }
  1816. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1817. { // Firefox and Temasys plugin
  1818. if (stream && stream.audioStream)
  1819. audioStream = stream.audioStream;
  1820. else
  1821. audioStream = new DummyMediaStream("dummyAudio");
  1822. if (stream && stream.videoStream)
  1823. videoStream = stream.videoStream;
  1824. else
  1825. videoStream = new DummyMediaStream("dummyVideo");
  1826. }
  1827. var audioMuted = (usageOptions && usageOptions.audio === false),
  1828. videoMuted = (usageOptions && usageOptions.video === false);
  1829. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1830. videoGUM = (!usageOptions || usageOptions.video !== false);
  1831. this.service.createLocalStream(audioStream, "audio", null, null,
  1832. audioMuted, audioGUM);
  1833. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1834. videoMuted, videoGUM);
  1835. };
  1836. function DummyMediaStream(id) {
  1837. this.id = id;
  1838. this.label = id;
  1839. this.stop = function() { };
  1840. this.getAudioTracks = function() { return []; };
  1841. this.getVideoTracks = function() { return []; };
  1842. }
  1843. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1844. var newStream = null;
  1845. if (window.webkitMediaStream) {
  1846. newStream = new webkitMediaStream();
  1847. if (newStream) {
  1848. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1849. for (var i = 0; i < tracks.length; i++) {
  1850. newStream.addTrack(tracks[i]);
  1851. }
  1852. }
  1853. }
  1854. else {
  1855. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1856. if (stream) {
  1857. newStream = stream;
  1858. } else {
  1859. newStream =
  1860. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1861. }
  1862. }
  1863. return newStream;
  1864. };
  1865. module.exports = RTCUtils;
  1866. },{"../../service/RTC/Resolutions":166,"../xmpp/SDPUtil":62,"./RTCBrowserType":10,"./adapter.screenshare":12}],12:[function(require,module,exports){
  1867. /*! adapterjs - custom version from - 2015-08-19 */
  1868. // Adapter's interface.
  1869. var AdapterJS = AdapterJS || {};
  1870. // Browserify compatibility
  1871. if(typeof exports !== 'undefined') {
  1872. module.exports = AdapterJS;
  1873. }
  1874. AdapterJS.options = AdapterJS.options || {};
  1875. // uncomment to get virtual webcams
  1876. // AdapterJS.options.getAllCams = true;
  1877. // uncomment to prevent the install prompt when the plugin in not yet installed
  1878. // AdapterJS.options.hidePluginInstallPrompt = true;
  1879. // AdapterJS version
  1880. AdapterJS.VERSION = '0.12.0';
  1881. // This function will be called when the WebRTC API is ready to be used
  1882. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1883. // the plugin
  1884. // You may Override this function to synchronise the start of your application
  1885. // with the WebRTC API being ready.
  1886. // If you decide not to override use this synchronisation, it may result in
  1887. // an extensive CPU usage on the plugin start (once per tab loaded)
  1888. // Params:
  1889. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1890. //
  1891. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1892. // The WebRTC API is ready.
  1893. // Override me and do whatever you want here
  1894. };
  1895. // Sets a callback function to be called when the WebRTC interface is ready.
  1896. // The first argument is the function to callback.\
  1897. // Throws an error if the first argument is not a function
  1898. AdapterJS.webRTCReady = function (callback) {
  1899. if (typeof callback !== 'function') {
  1900. throw new Error('Callback provided is not a function');
  1901. }
  1902. if (true === AdapterJS.onwebrtcreadyDone) {
  1903. // All WebRTC interfaces are ready, just call the callback
  1904. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1905. } else {
  1906. // will be triggered automatically when your browser/plugin is ready.
  1907. AdapterJS.onwebrtcready = callback;
  1908. }
  1909. };
  1910. // Plugin namespace
  1911. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1912. // The object to store plugin information
  1913. AdapterJS.WebRTCPlugin.pluginInfo = {
  1914. prefix : 'Tem',
  1915. plugName : 'TemWebRTCPlugin',
  1916. pluginId : 'plugin0',
  1917. type : 'application/x-temwebrtcplugin',
  1918. onload : '__TemWebRTCReady0',
  1919. portalLink : 'http://skylink.io/plugin/',
  1920. downloadLink : null, //set below
  1921. companyName: 'Temasys'
  1922. };
  1923. if(!!navigator.platform.match(/^Mac/i)) {
  1924. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1925. }
  1926. else if(!!navigator.platform.match(/^Win/i)) {
  1927. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1928. }
  1929. AdapterJS.WebRTCPlugin.TAGS = {
  1930. NONE : 'none',
  1931. AUDIO : 'audio',
  1932. VIDEO : 'video'
  1933. };
  1934. // Unique identifier of each opened page
  1935. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1936. // Use this whenever you want to call the plugin.
  1937. AdapterJS.WebRTCPlugin.plugin = null;
  1938. // Set log level for the plugin once it is ready.
  1939. // The different values are
  1940. // This is an asynchronous function that will run when the plugin is ready
  1941. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1942. // Defines webrtc's JS interface according to the plugin's implementation.
  1943. // Define plugin Browsers as WebRTC Interface.
  1944. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1945. // This function detects whether or not a plugin is installed.
  1946. // Checks if Not IE (firefox, for example), else if it's IE,
  1947. // we're running IE and do something. If not it is not supported.
  1948. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1949. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1950. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1951. // Inject the HTML DOM object element into the page.
  1952. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1953. // States of readiness that the plugin goes through when
  1954. // being injected and stated
  1955. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1956. NONE : 0, // no plugin use
  1957. INITIALIZING : 1, // Detected need for plugin
  1958. INJECTING : 2, // Injecting plugin
  1959. INJECTED: 3, // Plugin element injected but not usable yet
  1960. READY: 4 // Plugin ready to be used
  1961. };
  1962. // Current state of the plugin. You cannot use the plugin before this is
  1963. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1964. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1965. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1966. // Used to make sure AdapterJS.onwebrtcready is only called once
  1967. AdapterJS.onwebrtcreadyDone = false;
  1968. // Log levels for the plugin.
  1969. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1970. /*
  1971. Log outputs are prefixed in some cases.
  1972. INFO: Information reported by the plugin.
  1973. ERROR: Errors originating from within the plugin.
  1974. WEBRTC: Error originating from within the libWebRTC library
  1975. */
  1976. // From the least verbose to the most verbose
  1977. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1978. NONE : 'NONE',
  1979. ERROR : 'ERROR',
  1980. WARNING : 'WARNING',
  1981. INFO: 'INFO',
  1982. VERBOSE: 'VERBOSE',
  1983. SENSITIVE: 'SENSITIVE'
  1984. };
  1985. // Does a waiting check before proceeding to load the plugin.
  1986. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1987. // This methid will use an interval to wait for the plugin to be ready.
  1988. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1989. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1990. // This function will be called when plugin is ready. It sends necessary
  1991. // details to the plugin.
  1992. // The function will wait for the document to be ready and the set the
  1993. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1994. // indicating that it can start being requested.
  1995. // This function is not in the IE/Safari condition brackets so that
  1996. // TemPluginLoaded function might be called on Chrome/Firefox.
  1997. // This function is the only private function that is not encapsulated to
  1998. // allow the plugin method to be called.
  1999. __TemWebRTCReady0 = function () {
  2000. if (document.readyState === 'complete') {
  2001. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2002. AdapterJS.maybeThroughWebRTCReady();
  2003. } else {
  2004. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  2005. if (document.readyState === 'complete') {
  2006. // TODO: update comments, we wait for the document to be ready
  2007. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  2008. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2009. AdapterJS.maybeThroughWebRTCReady();
  2010. }
  2011. }, 100);
  2012. }
  2013. };
  2014. AdapterJS.maybeThroughWebRTCReady = function() {
  2015. if (!AdapterJS.onwebrtcreadyDone) {
  2016. AdapterJS.onwebrtcreadyDone = true;
  2017. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  2018. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  2019. }
  2020. }
  2021. };
  2022. // Text namespace
  2023. AdapterJS.TEXT = {
  2024. PLUGIN: {
  2025. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  2026. 'to work on this browser.',
  2027. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  2028. BUTTON: 'Install Now'
  2029. },
  2030. REFRESH: {
  2031. REQUIRE_REFRESH: 'Please refresh page',
  2032. BUTTON: 'Refresh Page'
  2033. }
  2034. };
  2035. // The result of ice connection states.
  2036. // - starting: Ice connection is starting.
  2037. // - checking: Ice connection is checking.
  2038. // - connected Ice connection is connected.
  2039. // - completed Ice connection is connected.
  2040. // - done Ice connection has been completed.
  2041. // - disconnected Ice connection has been disconnected.
  2042. // - failed Ice connection has failed.
  2043. // - closed Ice connection is closed.
  2044. AdapterJS._iceConnectionStates = {
  2045. starting : 'starting',
  2046. checking : 'checking',
  2047. connected : 'connected',
  2048. completed : 'connected',
  2049. done : 'completed',
  2050. disconnected : 'disconnected',
  2051. failed : 'failed',
  2052. closed : 'closed'
  2053. };
  2054. //The IceConnection states that has been fired for each peer.
  2055. AdapterJS._iceConnectionFiredStates = [];
  2056. // Check if WebRTC Interface is defined.
  2057. AdapterJS.isDefined = null;
  2058. // This function helps to retrieve the webrtc detected browser information.
  2059. // This sets:
  2060. // - webrtcDetectedBrowser: The browser agent name.
  2061. // - webrtcDetectedVersion: The browser version.
  2062. // - webrtcDetectedType: The types of webRTC support.
  2063. // - 'moz': Mozilla implementation of webRTC.
  2064. // - 'webkit': WebKit implementation of webRTC.
  2065. // - 'plugin': Using the plugin implementation.
  2066. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2067. var hasMatch, checkMatch = navigator.userAgent.match(
  2068. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2069. if (/trident/i.test(checkMatch[1])) {
  2070. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2071. webrtcDetectedBrowser = 'IE';
  2072. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2073. } else if (checkMatch[1] === 'Chrome') {
  2074. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2075. if (hasMatch !== null) {
  2076. webrtcDetectedBrowser = 'opera';
  2077. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2078. }
  2079. }
  2080. if (navigator.userAgent.indexOf('Safari')) {
  2081. if (typeof InstallTrigger !== 'undefined') {
  2082. webrtcDetectedBrowser = 'firefox';
  2083. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2084. webrtcDetectedBrowser = 'IE';
  2085. } else if (
  2086. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2087. webrtcDetectedBrowser = 'safari';
  2088. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2089. webrtcDetectedBrowser = 'opera';
  2090. } else if (!!window.chrome) {
  2091. webrtcDetectedBrowser = 'chrome';
  2092. }
  2093. }
  2094. if (!webrtcDetectedBrowser) {
  2095. webrtcDetectedVersion = checkMatch[1];
  2096. }
  2097. if (!webrtcDetectedVersion) {
  2098. try {
  2099. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2100. [navigator.appName, navigator.appVersion, '-?'];
  2101. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2102. checkMatch.splice(1, 1, hasMatch[1]);
  2103. }
  2104. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2105. } catch (error) { }
  2106. }
  2107. };
  2108. // To fix configuration as some browsers does not support
  2109. // the 'urls' attribute.
  2110. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2111. if (pcConfig === null) {
  2112. return;
  2113. }
  2114. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2115. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2116. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2117. delete pcConfig.iceServers[i].urls;
  2118. }
  2119. }
  2120. };
  2121. AdapterJS.addEvent = function(elem, evnt, func) {
  2122. if (elem.addEventListener) { // W3C DOM
  2123. elem.addEventListener(evnt, func, false);
  2124. } else if (elem.attachEvent) {// OLD IE DOM
  2125. elem.attachEvent('on'+evnt, func);
  2126. } else { // No much to do
  2127. elem[evnt] = func;
  2128. }
  2129. };
  2130. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2131. // only inject once the page is ready
  2132. if (document.readyState !== 'complete') {
  2133. return;
  2134. }
  2135. var w = window;
  2136. var i = document.createElement('iframe');
  2137. i.style.position = 'fixed';
  2138. i.style.top = '-41px';
  2139. i.style.left = 0;
  2140. i.style.right = 0;
  2141. i.style.width = '100%';
  2142. i.style.height = '40px';
  2143. i.style.backgroundColor = '#ffffe1';
  2144. i.style.border = 'none';
  2145. i.style.borderBottom = '1px solid #888888';
  2146. i.style.zIndex = '9999999';
  2147. if(typeof i.style.webkitTransition === 'string') {
  2148. i.style.webkitTransition = 'all .5s ease-out';
  2149. } else if(typeof i.style.transition === 'string') {
  2150. i.style.transition = 'all .5s ease-out';
  2151. }
  2152. document.body.appendChild(i);
  2153. c = (i.contentWindow) ? i.contentWindow :
  2154. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2155. c.document.open();
  2156. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2157. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2158. 'middle; cursor: default;">' + text + '</span>');
  2159. if(buttonText && buttonLink) {
  2160. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  2161. c.document.close();
  2162. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2163. if (!!displayRefreshBar) {
  2164. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2165. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2166. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2167. }
  2168. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2169. e.preventDefault();
  2170. try {
  2171. event.cancelBubble = true;
  2172. } catch(error) { }
  2173. var pluginInstallInterval = setInterval(function(){
  2174. if(! isIE) {
  2175. navigator.plugins.refresh(false);
  2176. }
  2177. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2178. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2179. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2180. function() { // plugin now installed
  2181. clearInterval(pluginInstallInterval);
  2182. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  2183. },
  2184. function() {
  2185. // still no plugin detected, nothing to do
  2186. });
  2187. } , 500);
  2188. });
  2189. } else {
  2190. c.document.close();
  2191. }
  2192. AdapterJS.addEvent(c.document, 'click', function() {
  2193. w.document.body.removeChild(i);
  2194. });
  2195. setTimeout(function() {
  2196. if(typeof i.style.webkitTransform === 'string') {
  2197. i.style.webkitTransform = 'translateY(40px)';
  2198. } else if(typeof i.style.transform === 'string') {
  2199. i.style.transform = 'translateY(40px)';
  2200. } else {
  2201. i.style.top = '0px';
  2202. }
  2203. }, 300);
  2204. };
  2205. // -----------------------------------------------------------
  2206. // Detected webrtc implementation. Types are:
  2207. // - 'moz': Mozilla implementation of webRTC.
  2208. // - 'webkit': WebKit implementation of webRTC.
  2209. // - 'plugin': Using the plugin implementation.
  2210. webrtcDetectedType = null;
  2211. // Detected webrtc datachannel support. Types are:
  2212. // - 'SCTP': SCTP datachannel support.
  2213. // - 'RTP': RTP datachannel support.
  2214. webrtcDetectedDCSupport = null;
  2215. // Set the settings for creating DataChannels, MediaStream for
  2216. // Cross-browser compability.
  2217. // - This is only for SCTP based support browsers.
  2218. // the 'urls' attribute.
  2219. checkMediaDataChannelSettings =
  2220. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2221. if (typeof callback !== 'function') {
  2222. return;
  2223. }
  2224. var beOfferer = true;
  2225. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2226. // Nightly version does not require MozDontOfferDataChannel for interop
  2227. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2228. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2229. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2230. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2231. // Resends an updated version of constraints for MozDataChannel to work
  2232. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2233. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2234. try {
  2235. delete constraints.mandatory.MozDontOfferDataChannel;
  2236. } catch (error) {
  2237. console.error('Failed deleting MozDontOfferDataChannel');
  2238. console.error(error);
  2239. }
  2240. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2241. constraints.mandatory.MozDontOfferDataChannel = true;
  2242. }
  2243. if (!isLocalFirefox) {
  2244. // temporary measure to remove Moz* constraints in non Firefox browsers
  2245. for (var prop in constraints.mandatory) {
  2246. if (constraints.mandatory.hasOwnProperty(prop)) {
  2247. if (prop.indexOf('Moz') !== -1) {
  2248. delete constraints.mandatory[prop];
  2249. }
  2250. }
  2251. }
  2252. }
  2253. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2254. // interopability of the media stream
  2255. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2256. beOfferer = false;
  2257. }
  2258. callback(beOfferer, constraints);
  2259. };
  2260. // Handles the differences for all browsers ice connection state output.
  2261. // - Tested outcomes are:
  2262. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2263. // - Chrome (answerer) : 'checking' > 'connected'
  2264. // - Firefox (offerer) : 'checking' > 'connected'
  2265. // - Firefox (answerer): 'checking' > 'connected'
  2266. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2267. if (typeof callback !== 'function') {
  2268. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2269. return;
  2270. }
  2271. peerId = (peerId) ? peerId : 'peer';
  2272. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2273. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2274. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2275. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2276. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2277. }
  2278. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2279. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2280. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2281. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2282. setTimeout(function () {
  2283. AdapterJS._iceConnectionFiredStates[peerId]
  2284. .push(AdapterJS._iceConnectionStates.done);
  2285. callback(AdapterJS._iceConnectionStates.done);
  2286. }, 1000);
  2287. }
  2288. callback(iceConnectionState);
  2289. }
  2290. return;
  2291. };
  2292. // Firefox:
  2293. // - Creates iceServer from the url for Firefox.
  2294. // - Create iceServer with stun url.
  2295. // - Create iceServer with turn url.
  2296. // - Ignore the transport parameter from TURN url for FF version <=27.
  2297. // - Return null for createIceServer if transport=tcp.
  2298. // - FF 27 and above supports transport parameters in TURN url,
  2299. // - So passing in the full url to create iceServer.
  2300. // Chrome:
  2301. // - Creates iceServer from the url for Chrome M33 and earlier.
  2302. // - Create iceServer with stun url.
  2303. // - Chrome M28 & above uses below TURN format.
  2304. // Plugin:
  2305. // - Creates Ice Server for Plugin Browsers
  2306. // - If Stun - Create iceServer with stun url.
  2307. // - Else - Create iceServer with turn url
  2308. // - This is a WebRTC Function
  2309. createIceServer = null;
  2310. // Firefox:
  2311. // - Creates IceServers for Firefox
  2312. // - Use .url for FireFox.
  2313. // - Multiple Urls support
  2314. // Chrome:
  2315. // - Creates iceServers from the urls for Chrome M34 and above.
  2316. // - .urls is supported since Chrome M34.
  2317. // - Multiple Urls support
  2318. // Plugin:
  2319. // - Creates Ice Servers for Plugin Browsers
  2320. // - Multiple Urls support
  2321. // - This is a WebRTC Function
  2322. createIceServers = null;
  2323. //------------------------------------------------------------
  2324. //The RTCPeerConnection object.
  2325. RTCPeerConnection = null;
  2326. // Creates RTCSessionDescription object for Plugin Browsers
  2327. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2328. RTCSessionDescription : null;
  2329. // Creates RTCIceCandidate object for Plugin Browsers
  2330. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2331. RTCIceCandidate : null;
  2332. // Get UserMedia (only difference is the prefix).
  2333. // Code from Adam Barth.
  2334. getUserMedia = null;
  2335. // Attach a media stream to an element.
  2336. attachMediaStream = null;
  2337. // Re-attach a media stream to an element.
  2338. reattachMediaStream = null;
  2339. // Detected browser agent name. Types are:
  2340. // - 'firefox': Firefox browser.
  2341. // - 'chrome': Chrome browser.
  2342. // - 'opera': Opera browser.
  2343. // - 'safari': Safari browser.
  2344. // - 'IE' - Internet Explorer browser.
  2345. webrtcDetectedBrowser = null;
  2346. // Detected browser version.
  2347. webrtcDetectedVersion = null;
  2348. // Check for browser types and react accordingly
  2349. if (navigator.mozGetUserMedia) {
  2350. webrtcDetectedBrowser = 'firefox';
  2351. webrtcDetectedVersion = parseInt(navigator
  2352. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2353. webrtcDetectedType = 'moz';
  2354. webrtcDetectedDCSupport = 'SCTP';
  2355. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2356. AdapterJS.maybeFixConfiguration(pcConfig);
  2357. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2358. };
  2359. // The RTCSessionDescription object.
  2360. RTCSessionDescription = mozRTCSessionDescription;
  2361. window.RTCSessionDescription = RTCSessionDescription;
  2362. // The RTCIceCandidate object.
  2363. RTCIceCandidate = mozRTCIceCandidate;
  2364. window.RTCIceCandidate = RTCIceCandidate;
  2365. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2366. navigator.getUserMedia = window.getUserMedia;
  2367. // Shim for MediaStreamTrack.getSources.
  2368. MediaStreamTrack.getSources = function(successCb) {
  2369. setTimeout(function() {
  2370. var infos = [
  2371. { kind: 'audio', id: 'default', label:'', facing:'' },
  2372. { kind: 'video', id: 'default', label:'', facing:'' }
  2373. ];
  2374. successCb(infos);
  2375. }, 0);
  2376. };
  2377. createIceServer = function (url, username, password) {
  2378. var iceServer = null;
  2379. var url_parts = url.split(':');
  2380. if (url_parts[0].indexOf('stun') === 0) {
  2381. iceServer = { url : url };
  2382. } else if (url_parts[0].indexOf('turn') === 0) {
  2383. if (webrtcDetectedVersion < 27) {
  2384. var turn_url_parts = url.split('?');
  2385. if (turn_url_parts.length === 1 ||
  2386. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2387. iceServer = {
  2388. url : turn_url_parts[0],
  2389. credential : password,
  2390. username : username
  2391. };
  2392. }
  2393. } else {
  2394. iceServer = {
  2395. url : url,
  2396. credential : password,
  2397. username : username
  2398. };
  2399. }
  2400. }
  2401. return iceServer;
  2402. };
  2403. createIceServers = function (urls, username, password) {
  2404. var iceServers = [];
  2405. for (i = 0; i < urls.length; i++) {
  2406. var iceServer = createIceServer(urls[i], username, password);
  2407. if (iceServer !== null) {
  2408. iceServers.push(iceServer);
  2409. }
  2410. }
  2411. return iceServers;
  2412. };
  2413. attachMediaStream = function (element, stream) {
  2414. element.mozSrcObject = stream;
  2415. if (stream !== null)
  2416. element.play();
  2417. return element;
  2418. };
  2419. reattachMediaStream = function (to, from) {
  2420. to.mozSrcObject = from.mozSrcObject;
  2421. to.play();
  2422. return to;
  2423. };
  2424. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2425. if (!callback) {
  2426. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2427. ': 1 argument required, but only 0 present.');
  2428. }
  2429. return callback([]);
  2430. };
  2431. // Fake get{Video,Audio}Tracks
  2432. if (!MediaStream.prototype.getVideoTracks) {
  2433. MediaStream.prototype.getVideoTracks = function () {
  2434. return [];
  2435. };
  2436. }
  2437. if (!MediaStream.prototype.getAudioTracks) {
  2438. MediaStream.prototype.getAudioTracks = function () {
  2439. return [];
  2440. };
  2441. }
  2442. AdapterJS.maybeThroughWebRTCReady();
  2443. } else if (navigator.webkitGetUserMedia) {
  2444. webrtcDetectedBrowser = 'chrome';
  2445. webrtcDetectedType = 'webkit';
  2446. webrtcDetectedVersion = parseInt(navigator
  2447. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2448. // check if browser is opera 20+
  2449. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2450. if (checkIfOpera !== null) {
  2451. webrtcDetectedBrowser = 'opera';
  2452. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2453. }
  2454. // check browser datachannel support
  2455. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2456. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2457. webrtcDetectedDCSupport = 'SCTP';
  2458. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2459. webrtcDetectedVersion > 24) {
  2460. webrtcDetectedDCSupport = 'RTP';
  2461. } else {
  2462. webrtcDetectedDCSupport = '';
  2463. }
  2464. createIceServer = function (url, username, password) {
  2465. var iceServer = null;
  2466. var url_parts = url.split(':');
  2467. if (url_parts[0].indexOf('stun') === 0) {
  2468. iceServer = { 'url' : url };
  2469. } else if (url_parts[0].indexOf('turn') === 0) {
  2470. iceServer = {
  2471. 'url' : url,
  2472. 'credential' : password,
  2473. 'username' : username
  2474. };
  2475. }
  2476. return iceServer;
  2477. };
  2478. createIceServers = function (urls, username, password) {
  2479. var iceServers = [];
  2480. if (webrtcDetectedVersion >= 34) {
  2481. iceServers = {
  2482. 'urls' : urls,
  2483. 'credential' : password,
  2484. 'username' : username
  2485. };
  2486. } else {
  2487. for (i = 0; i < urls.length; i++) {
  2488. var iceServer = createIceServer(urls[i], username, password);
  2489. if (iceServer !== null) {
  2490. iceServers.push(iceServer);
  2491. }
  2492. }
  2493. }
  2494. return iceServers;
  2495. };
  2496. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2497. if (webrtcDetectedVersion < 34) {
  2498. AdapterJS.maybeFixConfiguration(pcConfig);
  2499. }
  2500. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2501. };
  2502. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2503. navigator.getUserMedia = window.getUserMedia;
  2504. attachMediaStream = function (element, stream) {
  2505. if (typeof element.srcObject !== 'undefined') {
  2506. element.srcObject = stream;
  2507. } else if (typeof element.mozSrcObject !== 'undefined') {
  2508. element.mozSrcObject = stream;
  2509. } else if (typeof element.src !== 'undefined') {
  2510. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2511. } else {
  2512. console.log('Error attaching stream to element.');
  2513. }
  2514. return element;
  2515. };
  2516. reattachMediaStream = function (to, from) {
  2517. to.src = from.src;
  2518. return to;
  2519. };
  2520. AdapterJS.maybeThroughWebRTCReady();
  2521. } else if (navigator.mediaDevices && navigator.userAgent.match(
  2522. /Edge\/(\d+).(\d+)$/)) {
  2523. webrtcDetectedBrowser = 'edge';
  2524. webrtcDetectedVersion =
  2525. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  2526. // the minimum version still supported by adapter.
  2527. webrtcMinimumVersion = 12;
  2528. getUserMedia = navigator.getUserMedia;
  2529. attachMediaStream = function(element, stream) {
  2530. element.srcObject = stream;
  2531. return element;
  2532. };
  2533. reattachMediaStream = function(to, from) {
  2534. to.srcObject = from.srcObject;
  2535. return to;
  2536. };
  2537. AdapterJS.maybeThroughWebRTCReady();
  2538. } else { // TRY TO USE PLUGIN
  2539. // IE 9 is not offering an implementation of console.log until you open a console
  2540. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2541. /* jshint -W020 */
  2542. console = {} || console;
  2543. // Implemented based on console specs from MDN
  2544. // You may override these functions
  2545. console.log = function (arg) {};
  2546. console.info = function (arg) {};
  2547. console.error = function (arg) {};
  2548. console.dir = function (arg) {};
  2549. console.exception = function (arg) {};
  2550. console.trace = function (arg) {};
  2551. console.warn = function (arg) {};
  2552. console.count = function (arg) {};
  2553. console.debug = function (arg) {};
  2554. console.count = function (arg) {};
  2555. console.time = function (arg) {};
  2556. console.timeEnd = function (arg) {};
  2557. console.group = function (arg) {};
  2558. console.groupCollapsed = function (arg) {};
  2559. console.groupEnd = function (arg) {};
  2560. /* jshint +W020 */
  2561. }
  2562. webrtcDetectedType = 'plugin';
  2563. webrtcDetectedDCSupport = 'plugin';
  2564. AdapterJS.parseWebrtcDetectedBrowser();
  2565. isIE = webrtcDetectedBrowser === 'IE';
  2566. /* jshint -W035 */
  2567. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2568. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2569. /* empty because it needs to prevent the function from running. */
  2570. }
  2571. };
  2572. /* jshint +W035 */
  2573. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2574. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2575. // Call immediately if possible
  2576. // Once the plugin is set, the code will always take this path
  2577. callback();
  2578. } else {
  2579. // otherwise start a 100ms interval
  2580. var checkPluginReadyState = setInterval(function () {
  2581. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2582. clearInterval(checkPluginReadyState);
  2583. callback();
  2584. }
  2585. }, 100);
  2586. }
  2587. };
  2588. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2589. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2590. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2591. });
  2592. };
  2593. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2594. // only inject once the page is ready
  2595. if (document.readyState !== 'complete') {
  2596. return;
  2597. }
  2598. // Prevent multiple injections
  2599. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2600. return;
  2601. }
  2602. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2603. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2604. var frag = document.createDocumentFragment();
  2605. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2606. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2607. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2608. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2609. '<param name="pluginId" value="' +
  2610. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2611. '<param name="windowless" value="false" /> ' +
  2612. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2613. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  2614. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  2615. // uncomment to be able to use virtual cams
  2616. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2617. '</object>';
  2618. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2619. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2620. }
  2621. document.body.appendChild(frag);
  2622. // Need to re-fetch the plugin
  2623. AdapterJS.WebRTCPlugin.plugin =
  2624. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2625. } else {
  2626. // Load Plugin
  2627. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2628. AdapterJS.WebRTCPlugin.plugin.id =
  2629. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2630. // IE will only start the plugin if it's ACTUALLY visible
  2631. if (isIE) {
  2632. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2633. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2634. } else { // The size of the plugin on Safari should be 0x0px
  2635. // so that the autorisation prompt is at the top
  2636. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2637. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2638. }
  2639. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2640. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2641. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2642. '<param name="pluginId" value="' +
  2643. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2644. '<param name="windowless" value="false" /> ' +
  2645. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2646. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  2647. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  2648. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2649. }
  2650. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2651. };
  2652. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2653. function (comName, plugName, installedCb, notInstalledCb) {
  2654. if (!isIE) {
  2655. var pluginArray = navigator.plugins;
  2656. for (var i = 0; i < pluginArray.length; i++) {
  2657. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2658. installedCb();
  2659. return;
  2660. }
  2661. }
  2662. notInstalledCb();
  2663. } else {
  2664. try {
  2665. var axo = new ActiveXObject(comName + '.' + plugName);
  2666. } catch (e) {
  2667. notInstalledCb();
  2668. return;
  2669. }
  2670. installedCb();
  2671. }
  2672. };
  2673. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2674. if (AdapterJS.WebRTCPlugin.pluginState ===
  2675. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2676. console.error("AdapterJS - WebRTC interface has already been defined");
  2677. return;
  2678. }
  2679. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2680. AdapterJS.isDefined = function (variable) {
  2681. return variable !== null && variable !== undefined;
  2682. };
  2683. createIceServer = function (url, username, password) {
  2684. var iceServer = null;
  2685. var url_parts = url.split(':');
  2686. if (url_parts[0].indexOf('stun') === 0) {
  2687. iceServer = {
  2688. 'url' : url,
  2689. 'hasCredentials' : false
  2690. };
  2691. } else if (url_parts[0].indexOf('turn') === 0) {
  2692. iceServer = {
  2693. 'url' : url,
  2694. 'hasCredentials' : true,
  2695. 'credential' : password,
  2696. 'username' : username
  2697. };
  2698. }
  2699. return iceServer;
  2700. };
  2701. createIceServers = function (urls, username, password) {
  2702. var iceServers = [];
  2703. for (var i = 0; i < urls.length; ++i) {
  2704. iceServers.push(createIceServer(urls[i], username, password));
  2705. }
  2706. return iceServers;
  2707. };
  2708. RTCSessionDescription = function (info) {
  2709. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2710. return AdapterJS.WebRTCPlugin.plugin.
  2711. ConstructSessionDescription(info.type, info.sdp);
  2712. };
  2713. RTCPeerConnection = function (servers, constraints) {
  2714. var iceServers = null;
  2715. if (servers) {
  2716. iceServers = servers.iceServers;
  2717. for (var i = 0; i < iceServers.length; i++) {
  2718. if (iceServers[i].urls && !iceServers[i].url) {
  2719. iceServers[i].url = iceServers[i].urls;
  2720. }
  2721. iceServers[i].hasCredentials = AdapterJS.
  2722. isDefined(iceServers[i].username) &&
  2723. AdapterJS.isDefined(iceServers[i].credential);
  2724. }
  2725. }
  2726. var mandatory = (constraints && constraints.mandatory) ?
  2727. constraints.mandatory : null;
  2728. var optional = (constraints && constraints.optional) ?
  2729. constraints.optional : null;
  2730. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2731. return AdapterJS.WebRTCPlugin.plugin.
  2732. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2733. iceServers, mandatory, optional);
  2734. };
  2735. MediaStreamTrack = {};
  2736. MediaStreamTrack.getSources = function (callback) {
  2737. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2738. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2739. });
  2740. };
  2741. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2742. constraints.audio = constraints.audio || false;
  2743. constraints.video = constraints.video || false;
  2744. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2745. AdapterJS.WebRTCPlugin.plugin.
  2746. getUserMedia(constraints, successCallback, failureCallback);
  2747. });
  2748. };
  2749. window.navigator.getUserMedia = window.getUserMedia;
  2750. attachMediaStream = function (element, stream) {
  2751. if (!element || !element.parentNode) {
  2752. return;
  2753. }
  2754. var streamId
  2755. if (stream === null) {
  2756. streamId = '';
  2757. }
  2758. else {
  2759. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  2760. streamId = stream.id;
  2761. }
  2762. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2763. var nodeName = element.nodeName.toLowerCase();
  2764. if (nodeName !== 'object') { // not a plugin <object> tag yet
  2765. var tag;
  2766. switch(nodeName) {
  2767. case 'audio':
  2768. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  2769. break;
  2770. case 'video':
  2771. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  2772. break;
  2773. default:
  2774. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  2775. }
  2776. var frag = document.createDocumentFragment();
  2777. var temp = document.createElement('div');
  2778. var classHTML = '';
  2779. if (element.className) {
  2780. classHTML = 'class="' + element.className + '" ';
  2781. } else if (element.attributes && element.attributes['class']) {
  2782. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2783. }
  2784. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2785. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2786. '<param name="pluginId" value="' + elementId + '" /> ' +
  2787. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2788. '<param name="windowless" value="true" /> ' +
  2789. '<param name="streamId" value="' + streamId + '" /> ' +
  2790. '<param name="tag" value="' + tag + '" /> ' +
  2791. '</object>';
  2792. while (temp.firstChild) {
  2793. frag.appendChild(temp.firstChild);
  2794. }
  2795. var height = '';
  2796. var width = '';
  2797. if (element.getBoundingClientRect) {
  2798. var rectObject = element.getBoundingClientRect();
  2799. width = rectObject.width + 'px';
  2800. height = rectObject.height + 'px';
  2801. }
  2802. else if (element.width) {
  2803. width = element.width;
  2804. height = element.height;
  2805. } else {
  2806. // TODO: What scenario could bring us here?
  2807. }
  2808. element.parentNode.insertBefore(frag, element);
  2809. frag = document.getElementById(elementId);
  2810. frag.width = width;
  2811. frag.height = height;
  2812. element.parentNode.removeChild(element);
  2813. } else { // already an <object> tag, just change the stream id
  2814. var children = element.children;
  2815. for (var i = 0; i !== children.length; ++i) {
  2816. if (children[i].name === 'streamId') {
  2817. children[i].value = streamId;
  2818. break;
  2819. }
  2820. }
  2821. element.setStreamId(streamId);
  2822. }
  2823. var newElement = document.getElementById(elementId);
  2824. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2825. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2826. if (isIE) { // on IE the event needs to be plugged manually
  2827. newElement.attachEvent('onplaying', newElement.onplaying);
  2828. newElement._TemOnClick = function (id) {
  2829. var arg = {
  2830. srcElement : document.getElementById(id)
  2831. };
  2832. newElement.onclick(arg);
  2833. };
  2834. }
  2835. return newElement;
  2836. };
  2837. reattachMediaStream = function (to, from) {
  2838. var stream = null;
  2839. var children = from.children;
  2840. for (var i = 0; i !== children.length; ++i) {
  2841. if (children[i].name === 'streamId') {
  2842. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2843. stream = AdapterJS.WebRTCPlugin.plugin
  2844. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2845. break;
  2846. }
  2847. }
  2848. if (stream !== null) {
  2849. return attachMediaStream(to, stream);
  2850. } else {
  2851. console.log('Could not find the stream associated with this element');
  2852. }
  2853. };
  2854. RTCIceCandidate = function (candidate) {
  2855. if (!candidate.sdpMid) {
  2856. candidate.sdpMid = '';
  2857. }
  2858. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2859. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2860. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2861. );
  2862. };
  2863. // inject plugin
  2864. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2865. AdapterJS.WebRTCPlugin.injectPlugin();
  2866. };
  2867. // This function will be called if the plugin is needed (browser different
  2868. // from Chrome or Firefox), but the plugin is not installed.
  2869. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2870. function() {
  2871. AdapterJS.addEvent(document,
  2872. 'readystatechange',
  2873. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2874. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2875. };
  2876. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2877. if (AdapterJS.options.hidePluginInstallPrompt) {
  2878. return;
  2879. }
  2880. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2881. if(downloadLink) { // if download link
  2882. var popupString;
  2883. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2884. popupString = 'This website requires you to install the ' +
  2885. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2886. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2887. ' WebRTC Plugin</a>' +
  2888. ' to work on this browser.';
  2889. } else { // no portal link, just print a generic explanation
  2890. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2891. }
  2892. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2893. } else { // no download link, just print a generic explanation
  2894. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2895. }
  2896. };
  2897. // Try to detect the plugin and act accordingly
  2898. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2899. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2900. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2901. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2902. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2903. }
  2904. },{}],13:[function(require,module,exports){
  2905. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2906. var UI = {};
  2907. var VideoLayout = require("./videolayout/VideoLayout.js");
  2908. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2909. var Prezi = require("./prezi/Prezi.js");
  2910. var Etherpad = require("./etherpad/Etherpad.js");
  2911. var Chat = require("./side_pannels/chat/Chat.js");
  2912. var Toolbar = require("./toolbars/Toolbar");
  2913. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2914. var BottomToolbar = require("./toolbars/BottomToolbar");
  2915. var ContactList = require("./side_pannels/contactlist/ContactList");
  2916. var Avatar = require("./avatar/Avatar");
  2917. var EventEmitter = require("events");
  2918. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2919. var Settings = require("./../settings/Settings");
  2920. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2921. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2922. UI.messageHandler = require("./util/MessageHandler");
  2923. var messageHandler = UI.messageHandler;
  2924. var Authentication = require("./authentication/Authentication");
  2925. var UIUtil = require("./util/UIUtil");
  2926. var NicknameHandler = require("./util/NicknameHandler");
  2927. var JitsiPopover = require("./util/JitsiPopover");
  2928. var CQEvents = require("../../service/connectionquality/CQEvents");
  2929. var DesktopSharingEventTypes
  2930. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2931. var RTCEvents = require("../../service/RTC/RTCEvents");
  2932. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2933. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2934. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2935. var UIEvents = require("../../service/UI/UIEvents");
  2936. var MemberEvents = require("../../service/members/Events");
  2937. var eventEmitter = new EventEmitter();
  2938. var roomNode = null;
  2939. var roomName = null;
  2940. function promptDisplayName() {
  2941. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2942. message += APP.translation.translateString(
  2943. "dialog.displayNameRequired");
  2944. message += '</h2>' +
  2945. '<input name="displayName" type="text" data-i18n=' +
  2946. '"[placeholder]defaultNickname" placeholder="' +
  2947. APP.translation.translateString(
  2948. "defaultNickname", {name: "Jane Pink"}) +
  2949. '" autofocus>';
  2950. var buttonTxt
  2951. = APP.translation.generateTranslationHTML("dialog.Ok");
  2952. var buttons = [];
  2953. buttons.push({title: buttonTxt, value: "ok"});
  2954. messageHandler.openDialog(null, message,
  2955. true,
  2956. buttons,
  2957. function (e, v, m, f) {
  2958. if (v == "ok") {
  2959. var displayName = f.displayName;
  2960. if (displayName) {
  2961. VideoLayout.inputDisplayNameHandler(displayName);
  2962. return true;
  2963. }
  2964. }
  2965. e.preventDefault();
  2966. },
  2967. function () {
  2968. var form = $.prompt.getPrompt();
  2969. var input = form.find("input[name='displayName']");
  2970. input.focus();
  2971. var button = form.find("button");
  2972. button.attr("disabled", "disabled");
  2973. input.keyup(function () {
  2974. if(!input.val())
  2975. button.attr("disabled", "disabled");
  2976. else
  2977. button.removeAttr("disabled");
  2978. });
  2979. }
  2980. );
  2981. }
  2982. function notifyForInitialMute() {
  2983. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2984. "notify.muted", null, {timeOut: 120000});
  2985. }
  2986. function setupPrezi() {
  2987. $("#reloadPresentationLink").click(function() {
  2988. Prezi.reloadPresentation();
  2989. });
  2990. }
  2991. function setupChat() {
  2992. Chat.init();
  2993. $("#toggle_smileys").click(function() {
  2994. Chat.toggleSmileys();
  2995. });
  2996. }
  2997. function setupToolbars() {
  2998. Toolbar.init(UI);
  2999. Toolbar.setupButtonsFromConfig();
  3000. BottomToolbar.init();
  3001. }
  3002. function streamHandler(stream, isMuted) {
  3003. switch (stream.type) {
  3004. case "audio":
  3005. VideoLayout.changeLocalAudio(stream, isMuted);
  3006. break;
  3007. case "video":
  3008. VideoLayout.changeLocalVideo(stream, isMuted);
  3009. break;
  3010. case "stream":
  3011. VideoLayout.changeLocalStream(stream, isMuted);
  3012. break;
  3013. }
  3014. }
  3015. function onXmppConnectionFailed(stropheErrorMsg) {
  3016. var title = APP.translation.generateTranslationHTML(
  3017. "dialog.error");
  3018. var message;
  3019. if (stropheErrorMsg) {
  3020. message = APP.translation.generateTranslationHTML(
  3021. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  3022. } else {
  3023. message = APP.translation.generateTranslationHTML(
  3024. "dialog.connectError");
  3025. }
  3026. messageHandler.openDialog(
  3027. title, message, true, {}, function (e, v, m, f) { return false; });
  3028. }
  3029. function onDisposeConference(unload) {
  3030. Toolbar.showAuthenticateButton(false);
  3031. }
  3032. function onDisplayNameChanged(jid, displayName) {
  3033. ContactList.onDisplayNameChange(jid, displayName);
  3034. SettingsMenu.onDisplayNameChange(jid, displayName);
  3035. VideoLayout.onDisplayNameChanged(jid, displayName);
  3036. }
  3037. function registerListeners() {
  3038. APP.RTC.addStreamListener(streamHandler,
  3039. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  3040. APP.RTC.addStreamListener(streamHandler,
  3041. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  3042. APP.RTC.addStreamListener(function (stream) {
  3043. VideoLayout.onRemoteStreamAdded(stream);
  3044. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  3045. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  3046. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  3047. function (resourceJid) {
  3048. VideoLayout.onDominantSpeakerChanged(resourceJid);
  3049. });
  3050. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  3051. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  3052. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  3053. endpointsEnteringLastN, stream);
  3054. });
  3055. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  3056. function (devices) {
  3057. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  3058. });
  3059. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  3060. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function () {
  3061. // when the data channel becomes available, tell the bridge about video
  3062. // selections so that it can do adaptive simulcast,
  3063. // we want the notification to trigger even if userJid is undefined,
  3064. // or null.
  3065. var userResource = APP.UI.getLargeVideoResource();
  3066. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userResource);
  3067. });
  3068. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  3069. var resourceJid;
  3070. if(jid === APP.statistics.LOCAL_JID) {
  3071. resourceJid = AudioLevels.LOCAL_LEVEL;
  3072. if(APP.RTC.localAudio.isMuted()) {
  3073. audioLevel = 0;
  3074. }
  3075. } else {
  3076. resourceJid = Strophe.getResourceFromJid(jid);
  3077. }
  3078. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  3079. UI.getLargeVideoResource());
  3080. });
  3081. APP.desktopsharing.addListener(function () {
  3082. ToolbarToggler.showDesktopSharingButton();
  3083. }, DesktopSharingEventTypes.INIT);
  3084. APP.desktopsharing.addListener(
  3085. Toolbar.changeDesktopSharingButtonState,
  3086. DesktopSharingEventTypes.SWITCHING_DONE);
  3087. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  3088. VideoLayout.updateLocalConnectionStats);
  3089. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  3090. VideoLayout.updateConnectionStats);
  3091. APP.connectionquality.addListener(CQEvents.STOP,
  3092. VideoLayout.onStatsStop);
  3093. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  3094. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  3095. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  3096. messageHandler.openMessageDialog(
  3097. 'dialog.serviceUnavailable',
  3098. 'dialog.gracefulShutdown'
  3099. );
  3100. });
  3101. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  3102. var title = APP.translation.generateTranslationHTML(
  3103. "dialog.reservationError");
  3104. var message = APP.translation.generateTranslationHTML(
  3105. "dialog.reservationErrorMsg", {code: code, msg: msg});
  3106. messageHandler.openDialog(
  3107. title,
  3108. message,
  3109. true, {},
  3110. function (event, value, message, formVals) {
  3111. return false;
  3112. }
  3113. );
  3114. });
  3115. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  3116. messageHandler.openMessageDialog("dialog.sessTerminated",
  3117. "dialog.kickMessage");
  3118. });
  3119. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  3120. //FIXME: use Session Terminated from translation, but
  3121. // 'reason' text comes from XMPP packet and is not translated
  3122. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  3123. messageHandler.openDialog(
  3124. title, reason, true, {},
  3125. function (event, value, message, formVals) {
  3126. return false;
  3127. }
  3128. );
  3129. });
  3130. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  3131. messageHandler.showError("dialog.error",
  3132. "dialog.bridgeUnavailable");
  3133. });
  3134. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  3135. Avatar.setUserAvatar(from, id);
  3136. });
  3137. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  3138. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  3139. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  3140. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  3141. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  3142. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  3143. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  3144. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  3145. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  3146. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  3147. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  3148. onAuthenticationRequired);
  3149. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_VIDEO_TYPE_CHANGED,
  3150. onPeerVideoTypeChanged);
  3151. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  3152. function (resource, devices) {
  3153. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  3154. });
  3155. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_AUDIO_MUTED,
  3156. VideoLayout.onAudioMute);
  3157. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_VIDEO_MUTED,
  3158. VideoLayout.onVideoMute);
  3159. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function (doMuteAudio) {
  3160. UI.setAudioMuted(doMuteAudio);
  3161. });
  3162. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  3163. onDtmfSupportChanged);
  3164. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  3165. SettingsMenu.setStartMuted(audio, video);
  3166. });
  3167. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  3168. UI.setInitialMuteFromFocus(audio, video);
  3169. });
  3170. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  3171. UI.messageHandler.showError("dialog.sorry",
  3172. "dialog.internalError");
  3173. });
  3174. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function () {
  3175. messageHandler.showError("dialog.error",
  3176. "dialog.SLDFailure");
  3177. });
  3178. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function () {
  3179. messageHandler.showError("dialog.error",
  3180. "dialog.SRDFailure");
  3181. });
  3182. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function () {
  3183. messageHandler.showError();
  3184. });
  3185. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function () {
  3186. // FIXME: re-use LoginDialog which supports retries
  3187. UI.showLoginPopup(connect);
  3188. });
  3189. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focusComponent, retrySec) {
  3190. UI.messageHandler.notify(
  3191. null, "notify.focus",
  3192. 'disconnected', "notify.focusFail",
  3193. {component: focusComponent, ms: retrySec});
  3194. });
  3195. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  3196. UI.messageHandler.openReportDialog(null,
  3197. "dialog.connectError", pres);
  3198. });
  3199. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  3200. UI.messageHandler.openReportDialog(null,
  3201. "dialog.connectError", pres);
  3202. });
  3203. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function () {
  3204. var roomName = UI.generateRoomName();
  3205. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  3206. });
  3207. //NicknameHandler emits this event
  3208. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  3209. APP.xmpp.addToPresence("displayName", nickname);
  3210. });
  3211. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  3212. AudioLevels.init();
  3213. });
  3214. if (!interfaceConfig.filmStripOnly) {
  3215. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  3216. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  3217. // Listens for video interruption events.
  3218. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  3219. // Listens for video restores events.
  3220. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  3221. }
  3222. }
  3223. /**
  3224. * Mutes/unmutes the local video.
  3225. *
  3226. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  3227. * @param options an object which specifies optional arguments such as the
  3228. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  3229. * specifies whether the method was initiated in response to a user command (in
  3230. * contrast to an automatic decision taken by the application logic)
  3231. */
  3232. function setVideoMute(mute, options) {
  3233. APP.RTC.setVideoMute(mute,
  3234. UI.setVideoMuteButtonsState,
  3235. options);
  3236. }
  3237. function onResize() {
  3238. Chat.resizeChat();
  3239. VideoLayout.resizeLargeVideoContainer();
  3240. }
  3241. function bindEvents() {
  3242. /**
  3243. * Resizes and repositions videos in full screen mode.
  3244. */
  3245. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  3246. onResize);
  3247. $(window).resize(onResize);
  3248. }
  3249. UI.start = function (init) {
  3250. document.title = interfaceConfig.APP_NAME;
  3251. var setupWelcomePage = null;
  3252. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3253. (!window.localStorage.welcomePageDisabled ||
  3254. window.localStorage.welcomePageDisabled == "false")) {
  3255. $("#videoconference_page").hide();
  3256. if (!setupWelcomePage)
  3257. setupWelcomePage = require("./welcome_page/WelcomePage");
  3258. setupWelcomePage();
  3259. return;
  3260. }
  3261. $("#welcome_page").hide();
  3262. // Set the defaults for prompt dialogs.
  3263. $.prompt.setDefaults({persistent: false});
  3264. registerListeners();
  3265. VideoLayout.init(eventEmitter);
  3266. NicknameHandler.init(eventEmitter);
  3267. bindEvents();
  3268. setupPrezi();
  3269. if (!interfaceConfig.filmStripOnly) {
  3270. $("#videospace").mousemove(function () {
  3271. return ToolbarToggler.showToolbar();
  3272. });
  3273. setupToolbars();
  3274. setupChat();
  3275. // Display notice message at the top of the toolbar
  3276. if (config.noticeMessage) {
  3277. $('#noticeText').text(config.noticeMessage);
  3278. $('#notice').css({display: 'block'});
  3279. }
  3280. $("#downloadlog").click(function (event) {
  3281. dump(event.target);
  3282. });
  3283. }
  3284. else
  3285. {
  3286. $("#header").css("display", "none");
  3287. $("#bottomToolbar").css("display", "none");
  3288. $("#downloadlog").css("display", "none");
  3289. $("#remoteVideos").css("padding", "0px 0px 18px 0px");
  3290. $("#remoteVideos").css("right", "0px");
  3291. messageHandler.disableNotifications();
  3292. $('body').popover("disable");
  3293. // $("[data-toggle=popover]").popover("disable");
  3294. JitsiPopover.enabled = false;
  3295. }
  3296. document.title = interfaceConfig.APP_NAME;
  3297. if(config.requireDisplayName) {
  3298. var currentSettings = Settings.getSettings();
  3299. if (!currentSettings.displayName) {
  3300. promptDisplayName();
  3301. }
  3302. }
  3303. init();
  3304. if (!interfaceConfig.filmStripOnly) {
  3305. toastr.options = {
  3306. "closeButton": true,
  3307. "debug": false,
  3308. "positionClass": "notification-bottom-right",
  3309. "onclick": null,
  3310. "showDuration": "300",
  3311. "hideDuration": "1000",
  3312. "timeOut": "2000",
  3313. "extendedTimeOut": "1000",
  3314. "showEasing": "swing",
  3315. "hideEasing": "linear",
  3316. "showMethod": "fadeIn",
  3317. "hideMethod": "fadeOut",
  3318. "reposition": function () {
  3319. if (PanelToggler.isVisible()) {
  3320. $("#toast-container").addClass("notification-bottom-right-center");
  3321. } else {
  3322. $("#toast-container").removeClass("notification-bottom-right-center");
  3323. }
  3324. },
  3325. "newestOnTop": false
  3326. };
  3327. SettingsMenu.init();
  3328. }
  3329. };
  3330. function chatAddError(errorMessage, originalText) {
  3331. return Chat.chatAddError(errorMessage, originalText);
  3332. }
  3333. function chatSetSubject(text) {
  3334. return Chat.chatSetSubject(text);
  3335. }
  3336. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3337. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3338. }
  3339. function onMucJoined(jid, info) {
  3340. Toolbar.updateRoomUrl(window.location.href);
  3341. var meHTML = APP.translation.generateTranslationHTML("me");
  3342. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3343. var settings = Settings.getSettings();
  3344. // Make sure we configure our avatar id, before creating avatar for us
  3345. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3346. // Add myself to the contact list.
  3347. ContactList.addContact(jid);
  3348. // Once we've joined the muc show the toolbar
  3349. ToolbarToggler.showToolbar();
  3350. var displayName =
  3351. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  3352. if (displayName)
  3353. onDisplayNameChanged('localVideoContainer', displayName);
  3354. VideoLayout.mucJoined();
  3355. }
  3356. function initEtherpad(name) {
  3357. Etherpad.init(name);
  3358. }
  3359. function onMucMemberLeft(jid) {
  3360. console.log('left.muc', jid);
  3361. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3362. '>.displayname').html();
  3363. messageHandler.notify(displayName,'notify.somebody',
  3364. 'disconnected',
  3365. 'notify.disconnected');
  3366. if (!config.startAudioMuted ||
  3367. config.startAudioMuted > APP.members.size()) {
  3368. UIUtil.playSoundNotification('userLeft');
  3369. }
  3370. ContactList.removeContact(jid);
  3371. VideoLayout.participantLeft(jid);
  3372. }
  3373. function onLocalRoleChanged(jid, info, pres, isModerator) {
  3374. console.info("My role changed, new role: " + info.role);
  3375. onModeratorStatusChanged(isModerator);
  3376. VideoLayout.showModeratorIndicator();
  3377. SettingsMenu.onRoleChanged();
  3378. if (isModerator) {
  3379. Authentication.closeAuthenticationWindow();
  3380. messageHandler.notify(null, "notify.me",
  3381. 'connected', "notify.moderator");
  3382. Toolbar.checkAutoRecord();
  3383. }
  3384. }
  3385. function onModeratorStatusChanged(isModerator) {
  3386. Toolbar.showSipCallButton(isModerator);
  3387. Toolbar.showRecordingButton(
  3388. isModerator); //&&
  3389. // FIXME:
  3390. // Recording visible if
  3391. // there are at least 2(+ 1 focus) participants
  3392. //Object.keys(connection.emuc.members).length >= 3);
  3393. }
  3394. function onPasswordRequired(callback) {
  3395. // password is required
  3396. Toolbar.lockLockButton();
  3397. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3398. message += APP.translation.translateString(
  3399. "dialog.passwordRequired");
  3400. message += '</h2>' +
  3401. '<input name="lockKey" type="text" data-i18n=' +
  3402. '"[placeholder]dialog.password" placeholder="' +
  3403. APP.translation.translateString("dialog.password") +
  3404. '" autofocus>';
  3405. messageHandler.openTwoButtonDialog(null, null, null, message,
  3406. true,
  3407. "dialog.Ok",
  3408. function (e, v, m, f) {},
  3409. null,
  3410. function (e, v, m, f) {
  3411. if (v) {
  3412. var lockKey = f.lockKey;
  3413. if (lockKey) {
  3414. Toolbar.setSharedKey(lockKey);
  3415. callback(lockKey);
  3416. }
  3417. }
  3418. },
  3419. ':input:first'
  3420. );
  3421. }
  3422. /**
  3423. * The dialpad button is shown iff there is at least one member that supports
  3424. * DTMF (e.g. jigasi).
  3425. */
  3426. function onDtmfSupportChanged(dtmfSupport) {
  3427. //TODO: enable when the UI is ready
  3428. //Toolbar.showDialPadButton(dtmfSupport);
  3429. }
  3430. function onMucMemberJoined(jid, id, displayName) {
  3431. messageHandler.notify(displayName,'notify.somebody',
  3432. 'connected',
  3433. 'notify.connected');
  3434. if (!config.startAudioMuted ||
  3435. config.startAudioMuted > APP.members.size())
  3436. UIUtil.playSoundNotification('userJoined');
  3437. // Configure avatar
  3438. Avatar.setUserAvatar(jid, id);
  3439. // Add Peer's container
  3440. VideoLayout.ensurePeerContainerExists(jid);
  3441. }
  3442. function onMucPresenceStatus(jid, info) {
  3443. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3444. }
  3445. function onPeerVideoTypeChanged(resourceJid, newVideoType) {
  3446. VideoLayout.onVideoTypeChanged(resourceJid, newVideoType);
  3447. }
  3448. function onMucRoleChanged(role, displayName) {
  3449. VideoLayout.showModeratorIndicator();
  3450. if (role === 'moderator') {
  3451. var messageKey, messageOptions = {};
  3452. if (!displayName) {
  3453. messageKey = "notify.grantedToUnknown";
  3454. }
  3455. else {
  3456. messageKey = "notify.grantedTo";
  3457. messageOptions = {to: displayName};
  3458. }
  3459. messageHandler.notify(
  3460. displayName,'notify.somebody',
  3461. 'connected', messageKey,
  3462. messageOptions);
  3463. }
  3464. }
  3465. function onAuthenticationRequired(intervalCallback) {
  3466. Authentication.openAuthenticationDialog(
  3467. roomName, intervalCallback, function () {
  3468. Toolbar.authenticateClicked();
  3469. });
  3470. }
  3471. function onLastNChanged(oldValue, newValue) {
  3472. if (config.muteLocalVideoIfNotInLastN) {
  3473. setVideoMute(!newValue, { 'byUser': false });
  3474. }
  3475. }
  3476. UI.toggleSmileys = function () {
  3477. Chat.toggleSmileys();
  3478. };
  3479. UI.getSettings = function () {
  3480. return Settings.getSettings();
  3481. };
  3482. UI.toggleFilmStrip = function () {
  3483. return BottomToolbar.toggleFilmStrip();
  3484. };
  3485. UI.toggleChat = function () {
  3486. return BottomToolbar.toggleChat();
  3487. };
  3488. UI.toggleContactList = function () {
  3489. return BottomToolbar.toggleContactList();
  3490. };
  3491. UI.inputDisplayNameHandler = function (value) {
  3492. VideoLayout.inputDisplayNameHandler(value);
  3493. };
  3494. UI.getLargeVideoResource = function () {
  3495. return VideoLayout.getLargeVideoResource();
  3496. };
  3497. UI.getRoomNode = function () {
  3498. if (roomNode)
  3499. return roomNode;
  3500. var path = window.location.pathname;
  3501. // determinde the room node from the url
  3502. // TODO: just the roomnode or the whole bare jid?
  3503. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3504. // custom function might be responsible for doing the pushstate
  3505. roomNode = config.getroomnode(path);
  3506. } else {
  3507. /* fall back to default strategy
  3508. * this is making assumptions about how the URL->room mapping happens.
  3509. * It currently assumes deployment at root, with a rewrite like the
  3510. * following one (for nginx):
  3511. location ~ ^/([a-zA-Z0-9]+)$ {
  3512. rewrite ^/(.*)$ / break;
  3513. }
  3514. */
  3515. if (path.length > 1) {
  3516. roomNode = path.substr(1).toLowerCase();
  3517. } else {
  3518. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3519. roomNode = word.toLowerCase();
  3520. window.history.pushState('VideoChat',
  3521. 'Room: ' + word, window.location.pathname + word);
  3522. }
  3523. }
  3524. return roomNode;
  3525. };
  3526. UI.generateRoomName = function () {
  3527. if (roomName)
  3528. return roomName;
  3529. var roomNode = UI.getRoomNode();
  3530. roomName = roomNode + '@' + config.hosts.muc;
  3531. return roomName;
  3532. };
  3533. UI.connectionIndicatorShowMore = function(jid) {
  3534. return VideoLayout.showMore(jid);
  3535. };
  3536. UI.showLoginPopup = function(callback) {
  3537. console.log('password is required');
  3538. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3539. message += APP.translation.translateString(
  3540. "dialog.passwordRequired");
  3541. message += '</h2>' +
  3542. '<input name="username" type="text" ' +
  3543. 'placeholder="user@domain.net" autofocus>' +
  3544. '<input name="password" ' +
  3545. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3546. ' placeholder="user password">';
  3547. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3548. true,
  3549. "dialog.Ok",
  3550. function (e, v, m, f) {
  3551. if (v) {
  3552. if (f.username !== null && f.password != null) {
  3553. callback(f.username, f.password);
  3554. }
  3555. }
  3556. },
  3557. null, null, ':input:first'
  3558. );
  3559. };
  3560. UI.checkForNicknameAndJoin = function () {
  3561. Authentication.closeAuthenticationDialog();
  3562. Authentication.stopInterval();
  3563. var nick = null;
  3564. if (config.useNicks) {
  3565. nick = window.prompt('Your nickname (optional)');
  3566. }
  3567. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3568. };
  3569. function dump(elem, filename) {
  3570. elem = elem.parentNode;
  3571. elem.download = filename || 'meetlog.json';
  3572. elem.href = 'data:application/json;charset=utf-8,\n';
  3573. var data = APP.xmpp.getJingleLog();
  3574. var metadata = {};
  3575. metadata.time = new Date();
  3576. metadata.url = window.location.href;
  3577. metadata.ua = navigator.userAgent;
  3578. var log = APP.xmpp.getXmppLog();
  3579. if (log) {
  3580. metadata.xmpp = log;
  3581. }
  3582. data.metadata = metadata;
  3583. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3584. return false;
  3585. }
  3586. UI.getRoomName = function () {
  3587. return roomName;
  3588. };
  3589. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3590. if (muteAudio || muteVideo)
  3591. notifyForInitialMute();
  3592. if (muteAudio)
  3593. UI.setAudioMuted(true);
  3594. if (muteVideo)
  3595. UI.setVideoMute(true);
  3596. };
  3597. /**
  3598. * Mutes/unmutes the local video.
  3599. */
  3600. UI.toggleVideo = function () {
  3601. setVideoMute(!APP.RTC.localVideo.isMuted());
  3602. };
  3603. /**
  3604. * Mutes / unmutes audio for the local participant.
  3605. */
  3606. UI.toggleAudio = function() {
  3607. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3608. };
  3609. /**
  3610. * Sets muted audio state for the local participant.
  3611. */
  3612. UI.setAudioMuted = function (mute, earlyMute) {
  3613. var audioMute = null;
  3614. if (earlyMute)
  3615. audioMute = function (mute, cb) {
  3616. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3617. };
  3618. else
  3619. audioMute = function (mute, cb) {
  3620. return APP.xmpp.setAudioMute(mute, cb);
  3621. };
  3622. if (!audioMute(mute, function () {
  3623. VideoLayout.showLocalAudioIndicator(mute);
  3624. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3625. })) {
  3626. // We still click the button.
  3627. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3628. return;
  3629. }
  3630. };
  3631. UI.addListener = function (type, listener) {
  3632. eventEmitter.on(type, listener);
  3633. };
  3634. UI.clickOnVideo = function (videoNumber) {
  3635. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3636. if (remoteVideos.length > videoNumber) {
  3637. remoteVideos[videoNumber].click();
  3638. }
  3639. };
  3640. //Used by torture
  3641. UI.showToolbar = function () {
  3642. return ToolbarToggler.showToolbar();
  3643. };
  3644. //Used by torture
  3645. UI.dockToolbar = function (isDock) {
  3646. return ToolbarToggler.dockToolbar(isDock);
  3647. };
  3648. UI.setVideoMuteButtonsState = function (mute) {
  3649. var video = $('#toolbar_button_camera');
  3650. var communicativeClass = "icon-camera";
  3651. var muteClass = "icon-camera icon-camera-disabled";
  3652. if (mute) {
  3653. video.removeClass(communicativeClass);
  3654. video.addClass(muteClass);
  3655. } else {
  3656. video.removeClass(muteClass);
  3657. video.addClass(communicativeClass);
  3658. }
  3659. };
  3660. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3661. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3662. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3663. if(resourceJid === APP.xmpp.myResource())
  3664. SettingsMenu.changeAvatar(thumbUrl);
  3665. };
  3666. UI.setVideoMute = setVideoMute;
  3667. module.exports = UI;
  3668. },{"../../service/RTC/RTCEvents":165,"../../service/RTC/StreamEventTypes":167,"../../service/UI/UIEvents":168,"../../service/connectionquality/CQEvents":170,"../../service/desktopsharing/DesktopSharingEventTypes":171,"../../service/members/Events":172,"../../service/xmpp/XMPPEvents":174,"../RTC/RTCBrowserType":10,"./../settings/Settings":51,"./audio_levels/AudioLevels.js":14,"./authentication/Authentication":16,"./avatar/Avatar":18,"./etherpad/Etherpad.js":19,"./prezi/Prezi.js":20,"./side_pannels/SidePanelToggler":22,"./side_pannels/chat/Chat.js":23,"./side_pannels/contactlist/ContactList":27,"./side_pannels/settings/SettingsMenu":28,"./toolbars/BottomToolbar":29,"./toolbars/Toolbar":30,"./toolbars/ToolbarToggler":31,"./util/JitsiPopover":32,"./util/MessageHandler":33,"./util/NicknameHandler":34,"./util/UIUtil":35,"./videolayout/VideoLayout.js":41,"./welcome_page/RoomnameGenerator":42,"./welcome_page/WelcomePage":43,"events":1}],14:[function(require,module,exports){
  3669. /* global APP, interfaceConfig, $, Strophe */
  3670. var CanvasUtil = require("./CanvasUtils");
  3671. var ASDrawContext = null;
  3672. function initActiveSpeakerAudioLevels() {
  3673. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3674. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3675. // Draw a circle.
  3676. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3677. // Add a shadow around the circle
  3678. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3679. ASDrawContext.shadowOffsetX = 0;
  3680. ASDrawContext.shadowOffsetY = 0;
  3681. }
  3682. /**
  3683. * The audio Levels plugin.
  3684. */
  3685. var AudioLevels = (function(my) {
  3686. var audioLevelCanvasCache = {};
  3687. my.LOCAL_LEVEL = 'local';
  3688. my.init = function () {
  3689. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3690. initActiveSpeakerAudioLevels();
  3691. };
  3692. /**
  3693. * Updates the audio level canvas for the given peerJid. If the canvas
  3694. * didn't exist we create it.
  3695. */
  3696. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3697. var resourceJid = null;
  3698. var videoSpanId = null;
  3699. if (!peerJid)
  3700. videoSpanId = 'localVideoContainer';
  3701. else {
  3702. resourceJid = Strophe.getResourceFromJid(peerJid);
  3703. videoSpanId = 'participant_' + resourceJid;
  3704. }
  3705. var videoSpan = document.getElementById(videoSpanId);
  3706. if (!videoSpan) {
  3707. if (resourceJid)
  3708. console.error("No video element for jid", resourceJid);
  3709. else
  3710. console.error("No video element for local video.");
  3711. return;
  3712. }
  3713. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3714. var videoSpaceWidth = $('#remoteVideos').width();
  3715. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3716. var thumbnailWidth = thumbnailSize[0];
  3717. var thumbnailHeight = thumbnailSize[1];
  3718. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3719. audioLevelCanvas = document.createElement('canvas');
  3720. audioLevelCanvas.className = "audiolevel";
  3721. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3722. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3723. resizeAudioLevelCanvas( audioLevelCanvas,
  3724. thumbnailWidth,
  3725. thumbnailHeight);
  3726. videoSpan.appendChild(audioLevelCanvas);
  3727. } else {
  3728. audioLevelCanvas = audioLevelCanvas.get(0);
  3729. resizeAudioLevelCanvas( audioLevelCanvas,
  3730. thumbnailWidth,
  3731. thumbnailHeight);
  3732. }
  3733. };
  3734. /**
  3735. * Updates the audio level UI for the given resourceJid.
  3736. *
  3737. * @param resourceJid the resource jid indicating the video element for
  3738. * which we draw the audio level
  3739. * @param audioLevel the newAudio level to render
  3740. */
  3741. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3742. drawAudioLevelCanvas(resourceJid, audioLevel);
  3743. var videoSpanId = getVideoSpanId(resourceJid);
  3744. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3745. if (!audioLevelCanvas)
  3746. return;
  3747. var drawContext = audioLevelCanvas.getContext('2d');
  3748. var canvasCache = audioLevelCanvasCache[resourceJid];
  3749. drawContext.clearRect (0, 0,
  3750. audioLevelCanvas.width, audioLevelCanvas.height);
  3751. drawContext.drawImage(canvasCache, 0, 0);
  3752. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3753. if(!APP.xmpp.myJid()) {
  3754. return;
  3755. }
  3756. resourceJid = APP.xmpp.myResource();
  3757. }
  3758. if(resourceJid === largeVideoResourceJid) {
  3759. window.requestAnimationFrame(function () {
  3760. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3761. });
  3762. }
  3763. };
  3764. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3765. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3766. return;
  3767. ASDrawContext.clearRect(0, 0, 300, 300);
  3768. if(audioLevel == 0)
  3769. return;
  3770. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3771. // Fill the shape.
  3772. ASDrawContext.fill();
  3773. };
  3774. /**
  3775. * Resizes the given audio level canvas to match the given thumbnail size.
  3776. */
  3777. function resizeAudioLevelCanvas(audioLevelCanvas,
  3778. thumbnailWidth,
  3779. thumbnailHeight) {
  3780. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3781. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3782. }
  3783. /**
  3784. * Draws the audio level canvas into the cached canvas object.
  3785. *
  3786. * @param resourceJid the resource jid indicating the video element for
  3787. * which we draw the audio level
  3788. * @param audioLevel the newAudio level to render
  3789. */
  3790. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3791. if (!audioLevelCanvasCache[resourceJid]) {
  3792. var videoSpanId = getVideoSpanId(resourceJid);
  3793. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3794. /*
  3795. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3796. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3797. * error. Since audio levels are frequently updated, the errors have
  3798. * been observed to pile into the console, strain the CPU.
  3799. */
  3800. if (audioLevelCanvasOrig) {
  3801. audioLevelCanvasCache[resourceJid] =
  3802. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3803. }
  3804. }
  3805. var canvas = audioLevelCanvasCache[resourceJid];
  3806. if (!canvas)
  3807. return;
  3808. var drawContext = canvas.getContext('2d');
  3809. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3810. var shadowLevel = getShadowLevel(audioLevel);
  3811. if (shadowLevel > 0) {
  3812. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3813. CanvasUtil.drawRoundRectGlow(drawContext,
  3814. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3815. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3816. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3817. interfaceConfig.CANVAS_RADIUS,
  3818. interfaceConfig.SHADOW_COLOR,
  3819. shadowLevel);
  3820. }
  3821. }
  3822. /**
  3823. * Returns the shadow/glow level for the given audio level.
  3824. *
  3825. * @param audioLevel the audio level from which we determine the shadow
  3826. * level
  3827. */
  3828. function getShadowLevel (audioLevel) {
  3829. var shadowLevel = 0;
  3830. if (audioLevel <= 0.3) {
  3831. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3832. }
  3833. else if (audioLevel <= 0.6) {
  3834. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3835. }
  3836. else {
  3837. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3838. }
  3839. return shadowLevel;
  3840. }
  3841. /**
  3842. * Returns the video span id corresponding to the given resourceJid or local
  3843. * user.
  3844. */
  3845. function getVideoSpanId(resourceJid) {
  3846. var videoSpanId = null;
  3847. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3848. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3849. videoSpanId = 'localVideoContainer';
  3850. else
  3851. videoSpanId = 'participant_' + resourceJid;
  3852. return videoSpanId;
  3853. }
  3854. /**
  3855. * Indicates that the remote video has been resized.
  3856. */
  3857. $(document).bind('remotevideo.resized', function (event, width, height) {
  3858. var resized = false;
  3859. $('#remoteVideos>span>canvas').each(function() {
  3860. var canvas = $(this).get(0);
  3861. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3862. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3863. resized = true;
  3864. }
  3865. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3866. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3867. resized = true;
  3868. }
  3869. });
  3870. if (resized)
  3871. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3872. audioLevelCanvasCache[resourceJid].width =
  3873. width + interfaceConfig.CANVAS_EXTRA;
  3874. audioLevelCanvasCache[resourceJid].height =
  3875. height + interfaceConfig.CANVAS_EXTRA;
  3876. });
  3877. });
  3878. return my;
  3879. })(AudioLevels || {});
  3880. module.exports = AudioLevels;
  3881. },{"./CanvasUtils":15}],15:[function(require,module,exports){
  3882. /**
  3883. * Utility class for drawing canvas shapes.
  3884. */
  3885. var CanvasUtil = (function(my) {
  3886. /**
  3887. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3888. * of the glow.
  3889. *
  3890. * @param drawContext the context of the canvas to draw to
  3891. * @param x the x coordinate of the round rectangle
  3892. * @param y the y coordinate of the round rectangle
  3893. * @param w the width of the round rectangle
  3894. * @param h the height of the round rectangle
  3895. * @param glowColor the color of the glow
  3896. * @param glowWidth the width of the glow
  3897. */
  3898. my.drawRoundRectGlow
  3899. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3900. // Save the previous state of the context.
  3901. drawContext.save();
  3902. if (w < 2 * r) r = w / 2;
  3903. if (h < 2 * r) r = h / 2;
  3904. // Draw a round rectangle.
  3905. drawContext.beginPath();
  3906. drawContext.moveTo(x+r, y);
  3907. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3908. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3909. drawContext.arcTo(x, y+h, x, y, r);
  3910. drawContext.arcTo(x, y, x+w, y, r);
  3911. drawContext.closePath();
  3912. // Add a shadow around the rectangle
  3913. drawContext.shadowColor = glowColor;
  3914. drawContext.shadowBlur = glowWidth;
  3915. drawContext.shadowOffsetX = 0;
  3916. drawContext.shadowOffsetY = 0;
  3917. // Fill the shape.
  3918. drawContext.fill();
  3919. drawContext.save();
  3920. drawContext.restore();
  3921. // 1) Uncomment this line to use Composite Operation, which is doing the
  3922. // same as the clip function below and is also antialiasing the round
  3923. // border, but is said to be less fast performance wise.
  3924. // drawContext.globalCompositeOperation='destination-out';
  3925. drawContext.beginPath();
  3926. drawContext.moveTo(x+r, y);
  3927. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3928. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3929. drawContext.arcTo(x, y+h, x, y, r);
  3930. drawContext.arcTo(x, y, x+w, y, r);
  3931. drawContext.closePath();
  3932. // 2) Uncomment this line to use Composite Operation, which is doing the
  3933. // same as the clip function below and is also antialiasing the round
  3934. // border, but is said to be less fast performance wise.
  3935. // drawContext.fill();
  3936. // Comment these two lines if choosing to do the same with composite
  3937. // operation above 1 and 2.
  3938. drawContext.clip();
  3939. drawContext.clearRect(0, 0, 277, 200);
  3940. // Restore the previous context state.
  3941. drawContext.restore();
  3942. };
  3943. /**
  3944. * Clones the given canvas.
  3945. *
  3946. * @return the new cloned canvas.
  3947. */
  3948. my.cloneCanvas = function (oldCanvas) {
  3949. /*
  3950. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3951. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3952. * levels are frequently updated, the errors have been observed to pile
  3953. * into the console, strain the CPU.
  3954. */
  3955. if (!oldCanvas)
  3956. return oldCanvas;
  3957. //create a new canvas
  3958. var newCanvas = document.createElement('canvas');
  3959. var context = newCanvas.getContext('2d');
  3960. //set dimensions
  3961. newCanvas.width = oldCanvas.width;
  3962. newCanvas.height = oldCanvas.height;
  3963. //apply the old canvas to the new one
  3964. context.drawImage(oldCanvas, 0, 0);
  3965. //return the new canvas
  3966. return newCanvas;
  3967. };
  3968. return my;
  3969. })(CanvasUtil || {});
  3970. module.exports = CanvasUtil;
  3971. },{}],16:[function(require,module,exports){
  3972. /* global $, APP*/
  3973. var LoginDialog = require('./LoginDialog');
  3974. var Moderator = require('../../xmpp/moderator');
  3975. /* Initial "authentication required" dialog */
  3976. var authDialog = null;
  3977. /* Loop retry ID that wits for other user to create the room */
  3978. var authRetryId = null;
  3979. var authenticationWindow = null;
  3980. var Authentication = {
  3981. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3982. // This is the loop that will wait for the room to be created by
  3983. // someone else. 'auth_required.moderator' will bring us back here.
  3984. authRetryId = window.setTimeout(intervalCallback, 5000);
  3985. // Show prompt only if it's not open
  3986. if (authDialog !== null) {
  3987. return;
  3988. }
  3989. // extract room name from 'room@muc.server.net'
  3990. var room = roomName.substr(0, roomName.indexOf('@'));
  3991. var title
  3992. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3993. var msg
  3994. = APP.translation.generateTranslationHTML(
  3995. "dialog.WaitForHostMsg", {room: room});
  3996. var buttonTxt
  3997. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3998. var buttons = [];
  3999. buttons.push({title: buttonTxt, value: "authNow"});
  4000. authDialog = APP.UI.messageHandler.openDialog(
  4001. title,
  4002. msg,
  4003. true,
  4004. buttons,
  4005. function (onSubmitEvent, submitValue) {
  4006. // Do not close the dialog yet
  4007. onSubmitEvent.preventDefault();
  4008. // Open login popup
  4009. if (submitValue === 'authNow') {
  4010. callback();
  4011. }
  4012. }
  4013. );
  4014. },
  4015. closeAuthenticationWindow: function () {
  4016. if (authenticationWindow) {
  4017. authenticationWindow.close();
  4018. authenticationWindow = null;
  4019. }
  4020. },
  4021. xmppAuthenticate: function () {
  4022. var loginDialog = LoginDialog.show(
  4023. function (connection, state) {
  4024. if (!state) {
  4025. // User cancelled
  4026. loginDialog.close();
  4027. return;
  4028. } else if (state == APP.xmpp.Status.CONNECTED) {
  4029. loginDialog.close();
  4030. Authentication.stopInterval();
  4031. Authentication.closeAuthenticationDialog();
  4032. // Close the connection as anonymous one will be used
  4033. // to create the conference. Session-id will authorize
  4034. // the request.
  4035. connection.disconnect();
  4036. var roomName = APP.UI.generateRoomName();
  4037. Moderator.allocateConferenceFocus(roomName, function () {
  4038. // If it's not "on the fly" authentication now join
  4039. // the conference room
  4040. if (!APP.xmpp.isMUCJoined()) {
  4041. APP.UI.checkForNicknameAndJoin();
  4042. }
  4043. });
  4044. }
  4045. }, true);
  4046. },
  4047. focusAuthenticationWindow: function () {
  4048. // If auth window exists just bring it to the front
  4049. if (authenticationWindow) {
  4050. authenticationWindow.focus();
  4051. return;
  4052. }
  4053. },
  4054. closeAuthenticationDialog: function () {
  4055. // Close authentication dialog if opened
  4056. if (authDialog) {
  4057. authDialog.close();
  4058. authDialog = null;
  4059. }
  4060. },
  4061. createAuthenticationWindow: function (callback, url) {
  4062. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  4063. url, 910, 660,
  4064. // On closed
  4065. function () {
  4066. // Close authentication dialog if opened
  4067. Authentication.closeAuthenticationDialog();
  4068. callback();
  4069. authenticationWindow = null;
  4070. });
  4071. return authenticationWindow;
  4072. },
  4073. stopInterval: function () {
  4074. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  4075. if (authRetryId) {
  4076. window.clearTimeout(authRetryId);
  4077. authRetryId = null;
  4078. }
  4079. }
  4080. };
  4081. module.exports = Authentication;
  4082. },{"../../xmpp/moderator":64,"./LoginDialog":17}],17:[function(require,module,exports){
  4083. /* global $, APP, config*/
  4084. var XMPP = require('../../xmpp/xmpp');
  4085. var Moderator = require('../../xmpp/moderator');
  4086. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  4087. // anonymous domain is not enabled
  4088. /**
  4089. * Creates new <tt>Dialog</tt> instance.
  4090. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  4091. * when we either fail to connect or succeed(check Strophe.Status).
  4092. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  4093. * in order to create session-id after the connection is established.
  4094. * @constructor
  4095. */
  4096. function Dialog(callback, obtainSession) {
  4097. var self = this;
  4098. var stop = false;
  4099. var connection = APP.xmpp.createConnection();
  4100. var message = '<h2 data-i18n="dialog.passwordRequired">';
  4101. message += APP.translation.translateString("dialog.passwordRequired");
  4102. message += '</h2>' +
  4103. '<input name="username" type="text" ' +
  4104. 'placeholder="user@domain.net" autofocus>' +
  4105. '<input name="password" ' +
  4106. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  4107. ' placeholder="user password">';
  4108. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  4109. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  4110. var states = {
  4111. login: {
  4112. html: message,
  4113. buttons: [
  4114. { title: okButton, value: true},
  4115. { title: cancelButton, value: false}
  4116. ],
  4117. focus: ':input:first',
  4118. submit: function (e, v, m, f) {
  4119. e.preventDefault();
  4120. if (v) {
  4121. var jid = f.username;
  4122. var password = f.password;
  4123. if (jid && password) {
  4124. stop = false;
  4125. connection.reset();
  4126. connDialog.goToState('connecting');
  4127. connection.connect(jid, password, stateHandler);
  4128. }
  4129. } else {
  4130. // User cancelled
  4131. stop = true;
  4132. callback();
  4133. }
  4134. }
  4135. },
  4136. connecting: {
  4137. title: APP.translation.translateString('dialog.connecting'),
  4138. html: '<div id="connectionStatus"></div>',
  4139. buttons: [],
  4140. defaultButton: 0
  4141. },
  4142. finished: {
  4143. title: APP.translation.translateString('dialog.error'),
  4144. html: '<div id="errorMessage"></div>',
  4145. buttons: [
  4146. {
  4147. title: APP.translation.translateString('dialog.retry'),
  4148. value: 'retry'
  4149. },
  4150. {
  4151. title: APP.translation.translateString('dialog.Cancel'),
  4152. value: 'cancel'
  4153. },
  4154. ],
  4155. defaultButton: 0,
  4156. submit: function (e, v, m, f) {
  4157. e.preventDefault();
  4158. if (v === 'retry')
  4159. connDialog.goToState('login');
  4160. else
  4161. callback();
  4162. }
  4163. }
  4164. };
  4165. var connDialog
  4166. = APP.UI.messageHandler.openDialogWithStates(states,
  4167. { persistent: true, closeText: '' }, null);
  4168. var stateHandler = function (status, message) {
  4169. if (stop) {
  4170. return;
  4171. }
  4172. var translateKey = "connection." + XMPP.getStatusString(status);
  4173. var statusStr = APP.translation.translateString(translateKey);
  4174. // Display current state
  4175. var connectionStatus =
  4176. connDialog.getState('connecting').find('#connectionStatus');
  4177. connectionStatus.text(statusStr);
  4178. switch (status) {
  4179. case XMPP.Status.CONNECTED:
  4180. stop = true;
  4181. if (!obtainSession) {
  4182. callback(connection, status);
  4183. return;
  4184. }
  4185. // Obtaining session-id status
  4186. connectionStatus.text(
  4187. APP.translation.translateString(
  4188. 'connection.FETCH_SESSION_ID'));
  4189. // Authenticate with Jicofo and obtain session-id
  4190. var roomName = APP.UI.generateRoomName();
  4191. // Jicofo will return new session-id when connected
  4192. // from authenticated domain
  4193. connection.sendIQ(
  4194. Moderator.createConferenceIq(roomName),
  4195. function (result) {
  4196. connectionStatus.text(
  4197. APP.translation.translateString(
  4198. 'connection.GOT_SESSION_ID'));
  4199. stop = true;
  4200. // Parse session-id
  4201. Moderator.parseSessionId(result);
  4202. callback(connection, status);
  4203. },
  4204. function (error) {
  4205. console.error("Auth on the fly failed", error);
  4206. stop = true;
  4207. var errorMsg =
  4208. APP.translation.translateString(
  4209. 'connection.GET_SESSION_ID_ERROR') +
  4210. $(error).find('>error').attr('code');
  4211. self.displayError(errorMsg);
  4212. connection.disconnect();
  4213. });
  4214. break;
  4215. case XMPP.Status.AUTHFAIL:
  4216. case XMPP.Status.CONNFAIL:
  4217. case XMPP.Status.DISCONNECTED:
  4218. stop = true;
  4219. callback(connection, status);
  4220. var errorMessage = statusStr;
  4221. if (message)
  4222. {
  4223. errorMessage += ': ' + message;
  4224. }
  4225. self.displayError(errorMessage);
  4226. break;
  4227. default:
  4228. break;
  4229. }
  4230. };
  4231. /**
  4232. * Displays error message in 'finished' state which allows either to cancel
  4233. * or retry.
  4234. * @param message the final message to be displayed.
  4235. */
  4236. this.displayError = function (message) {
  4237. var finishedState = connDialog.getState('finished');
  4238. var errorMessageElem = finishedState.find('#errorMessage');
  4239. errorMessageElem.text(message);
  4240. connDialog.goToState('finished');
  4241. };
  4242. /**
  4243. * Closes LoginDialog.
  4244. */
  4245. this.close = function () {
  4246. stop = true;
  4247. connDialog.close();
  4248. };
  4249. }
  4250. var LoginDialog = {
  4251. /**
  4252. * Displays login prompt used to establish new XMPP connection. Given
  4253. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  4254. * called when we connect successfully(status === CONNECTED) or when we fail
  4255. * to do so. On connection failure program can call Dialog.close() method in
  4256. * order to cancel or do nothing to let the user retry.
  4257. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4258. * called when we either fail to connect or succeed(check
  4259. * Strophe.Status).
  4260. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4261. * Jicofo in order to create session-id after the connection is
  4262. * established.
  4263. * @returns {Dialog}
  4264. */
  4265. show: function (callback, obtainSession) {
  4266. return new Dialog(callback, obtainSession);
  4267. }
  4268. };
  4269. module.exports = LoginDialog;
  4270. },{"../../xmpp/moderator":64,"../../xmpp/xmpp":73}],18:[function(require,module,exports){
  4271. var Settings = require("../../settings/Settings");
  4272. var users = {};
  4273. var Avatar = {
  4274. /**
  4275. * Sets the user's avatar in the settings menu(if local user), contact list
  4276. * and thumbnail
  4277. * @param jid jid of the user
  4278. * @param id email or userID to be used as a hash
  4279. */
  4280. setUserAvatar: function (jid, id) {
  4281. if (id) {
  4282. if (users[jid] === id) {
  4283. return;
  4284. }
  4285. users[jid] = id;
  4286. }
  4287. var thumbUrl = this.getThumbUrl(jid);
  4288. var contactListUrl = this.getContactListUrl(jid);
  4289. var resourceJid = Strophe.getResourceFromJid(jid);
  4290. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4291. },
  4292. /**
  4293. * Returns image URL for the avatar to be displayed on large video area
  4294. * where current active speaker is presented.
  4295. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4296. */
  4297. getActiveSpeakerUrl: function (jid) {
  4298. return this.getGravatarUrl(jid, 100);
  4299. },
  4300. /**
  4301. * Returns image URL for the avatar to be displayed on small video thumbnail
  4302. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4303. */
  4304. getThumbUrl: function (jid) {
  4305. return this.getGravatarUrl(jid, 100);
  4306. },
  4307. /**
  4308. * Returns the URL for the avatar to be displayed as contactlist item
  4309. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4310. */
  4311. getContactListUrl: function (jid) {
  4312. return this.getGravatarUrl(jid, 30);
  4313. },
  4314. getGravatarUrl: function (jid, size) {
  4315. if (!jid) {
  4316. console.error("Get gravatar - jid is undefined");
  4317. return null;
  4318. }
  4319. var id = users[jid];
  4320. if (!id) {
  4321. console.warn(
  4322. "No avatar stored yet for " + jid + " - using JID as ID");
  4323. id = jid;
  4324. }
  4325. return 'https://www.gravatar.com/avatar/' +
  4326. MD5.hexdigest(id.trim().toLowerCase()) +
  4327. "?d=wavatar&size=" + (size || "30");
  4328. }
  4329. };
  4330. module.exports = Avatar;
  4331. },{"../../settings/Settings":51}],19:[function(require,module,exports){
  4332. /* global $, config,
  4333. setLargeVideoVisible, Util */
  4334. var VideoLayout = require("../videolayout/VideoLayout");
  4335. var Prezi = require("../prezi/Prezi");
  4336. var UIUtil = require("../util/UIUtil");
  4337. var etherpadName = null;
  4338. var etherpadIFrame = null;
  4339. var domain = null;
  4340. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4341. /**
  4342. * Resizes the etherpad.
  4343. */
  4344. function resize() {
  4345. if ($('#etherpad>iframe').length) {
  4346. var remoteVideos = $('#remoteVideos');
  4347. var availableHeight
  4348. = window.innerHeight - remoteVideos.outerHeight();
  4349. var availableWidth = UIUtil.getAvailableVideoWidth();
  4350. $('#etherpad>iframe').width(availableWidth);
  4351. $('#etherpad>iframe').height(availableHeight);
  4352. }
  4353. }
  4354. /**
  4355. * Creates the Etherpad button and adds it to the toolbar.
  4356. */
  4357. function enableEtherpadButton() {
  4358. if (!$('#toolbar_button_etherpad').is(":visible"))
  4359. $('#toolbar_button_etherpad').css({display: 'inline-block'});
  4360. }
  4361. /**
  4362. * Creates the IFrame for the etherpad.
  4363. */
  4364. function createIFrame() {
  4365. etherpadIFrame = VideoLayout.createEtherpadIframe(
  4366. domain + etherpadName + options, function() {
  4367. document.domain = document.domain;
  4368. bubbleIframeMouseMove(etherpadIFrame);
  4369. setTimeout(function() {
  4370. // the iframes inside of the etherpad are
  4371. // not yet loaded when the etherpad iframe is loaded
  4372. var outer = etherpadIFrame.
  4373. contentDocument.getElementsByName("ace_outer")[0];
  4374. bubbleIframeMouseMove(outer);
  4375. var inner = outer.
  4376. contentDocument.getElementsByName("ace_inner")[0];
  4377. bubbleIframeMouseMove(inner);
  4378. }, 2000);
  4379. });
  4380. }
  4381. function bubbleIframeMouseMove(iframe){
  4382. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4383. iframe.contentWindow.onmousemove = function(e){
  4384. if(existingOnMouseMove) existingOnMouseMove(e);
  4385. var evt = document.createEvent("MouseEvents");
  4386. var boundingClientRect = iframe.getBoundingClientRect();
  4387. evt.initMouseEvent(
  4388. "mousemove",
  4389. true, // bubbles
  4390. false, // not cancelable
  4391. window,
  4392. e.detail,
  4393. e.screenX,
  4394. e.screenY,
  4395. e.clientX + boundingClientRect.left,
  4396. e.clientY + boundingClientRect.top,
  4397. e.ctrlKey,
  4398. e.altKey,
  4399. e.shiftKey,
  4400. e.metaKey,
  4401. e.button,
  4402. null // no related element
  4403. );
  4404. iframe.dispatchEvent(evt);
  4405. };
  4406. }
  4407. var Etherpad = {
  4408. /**
  4409. * Initializes the etherpad.
  4410. */
  4411. init: function (name) {
  4412. if (config.etherpad_base && !etherpadName && name) {
  4413. domain = config.etherpad_base;
  4414. etherpadName = name;
  4415. enableEtherpadButton();
  4416. /**
  4417. * Resizes the etherpad, when the window is resized.
  4418. */
  4419. $(window).resize(function () {
  4420. resize();
  4421. });
  4422. }
  4423. },
  4424. /**
  4425. * Opens/hides the Etherpad.
  4426. */
  4427. toggleEtherpad: function (isPresentation) {
  4428. if (!etherpadIFrame)
  4429. createIFrame();
  4430. if(VideoLayout.getLargeVideoState() === "etherpad")
  4431. {
  4432. VideoLayout.setLargeVideoState("video");
  4433. }
  4434. else
  4435. {
  4436. VideoLayout.setLargeVideoState("etherpad");
  4437. }
  4438. resize();
  4439. }
  4440. };
  4441. module.exports = Etherpad;
  4442. },{"../prezi/Prezi":20,"../util/UIUtil":35,"../videolayout/VideoLayout":41}],20:[function(require,module,exports){
  4443. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4444. var UIUtil = require("../util/UIUtil");
  4445. var VideoLayout = require("../videolayout/VideoLayout");
  4446. var messageHandler = require("../util/MessageHandler");
  4447. var PreziPlayer = require("./PreziPlayer");
  4448. var preziPlayer = null;
  4449. /**
  4450. * Shows/hides a presentation.
  4451. */
  4452. function setPresentationVisible(visible) {
  4453. if (visible) {
  4454. VideoLayout.setLargeVideoState("prezi");
  4455. }
  4456. else {
  4457. VideoLayout.setLargeVideoState("video");
  4458. }
  4459. }
  4460. var Prezi = {
  4461. /**
  4462. * Reloads the current presentation.
  4463. */
  4464. reloadPresentation: function() {
  4465. var iframe = document.getElementById(preziPlayer.options.preziId);
  4466. iframe.src = iframe.src;
  4467. },
  4468. /**
  4469. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4470. * otherwise.
  4471. */
  4472. isPresentationVisible: function () {
  4473. return ($('#presentation>iframe') != null
  4474. && $('#presentation>iframe').css('opacity') == 1);
  4475. },
  4476. /**
  4477. * Opens the Prezi dialog, from which the user could choose a presentation
  4478. * to load.
  4479. */
  4480. openPreziDialog: function() {
  4481. var myprezi = APP.xmpp.getPrezi();
  4482. if (myprezi) {
  4483. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4484. null,
  4485. "dialog.removePreziMsg",
  4486. null,
  4487. false,
  4488. "dialog.Remove",
  4489. function(e,v,m,f) {
  4490. if(v) {
  4491. APP.xmpp.removePreziFromPresence();
  4492. }
  4493. }
  4494. );
  4495. }
  4496. else if (preziPlayer != null) {
  4497. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4498. null, "dialog.sharePreziMsg",
  4499. null,
  4500. false,
  4501. "dialog.Ok",
  4502. function(e,v,m,f) {
  4503. $.prompt.close();
  4504. }
  4505. );
  4506. }
  4507. else {
  4508. var html = APP.translation.generateTranslationHTML(
  4509. "dialog.sharePreziTitle");
  4510. var cancelButton = APP.translation.generateTranslationHTML(
  4511. "dialog.Cancel");
  4512. var shareButton = APP.translation.generateTranslationHTML(
  4513. "dialog.Share");
  4514. var backButton = APP.translation.generateTranslationHTML(
  4515. "dialog.Back");
  4516. var buttons = [];
  4517. var buttons1 = [];
  4518. // Cancel button to both states
  4519. buttons.push({title: cancelButton, value: false});
  4520. buttons1.push({title: cancelButton, value: false});
  4521. // Share button
  4522. buttons.push({title: shareButton, value: true});
  4523. // Back button
  4524. buttons1.push({title: backButton, value: true});
  4525. var linkError = APP.translation.generateTranslationHTML(
  4526. "dialog.preziLinkError");
  4527. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4528. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4529. var openPreziState = {
  4530. state0: {
  4531. html: '<h2>' + html + '</h2>' +
  4532. '<input name="preziUrl" type="text" ' +
  4533. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4534. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4535. '\' placeholder="' + defaultUrl + '" autofocus>',
  4536. persistent: false,
  4537. buttons: buttons,
  4538. focus: ':input:first',
  4539. defaultButton: 0,
  4540. submit: function (e, v, m, f) {
  4541. e.preventDefault();
  4542. if(v)
  4543. {
  4544. var preziUrl = f.preziUrl;
  4545. if (preziUrl)
  4546. {
  4547. var urlValue
  4548. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4549. if (urlValue.indexOf('http://prezi.com/') != 0
  4550. && urlValue.indexOf('https://prezi.com/') != 0)
  4551. {
  4552. $.prompt.goToState('state1');
  4553. return false;
  4554. }
  4555. else {
  4556. var presIdTmp = urlValue.substring(
  4557. urlValue.indexOf("prezi.com/") + 10);
  4558. if (!isAlphanumeric(presIdTmp)
  4559. || presIdTmp.indexOf('/') < 2) {
  4560. $.prompt.goToState('state1');
  4561. return false;
  4562. }
  4563. else {
  4564. APP.xmpp.addToPresence("prezi", urlValue);
  4565. $.prompt.close();
  4566. }
  4567. }
  4568. }
  4569. }
  4570. else
  4571. $.prompt.close();
  4572. }
  4573. },
  4574. state1: {
  4575. html: '<h2>' + html + '</h2>' +
  4576. linkError,
  4577. persistent: false,
  4578. buttons: buttons1,
  4579. focus: ':input:first',
  4580. defaultButton: 1,
  4581. submit: function (e, v, m, f) {
  4582. e.preventDefault();
  4583. if (v === 0)
  4584. $.prompt.close();
  4585. else
  4586. $.prompt.goToState('state0');
  4587. }
  4588. }
  4589. };
  4590. messageHandler.openDialogWithStates(openPreziState);
  4591. }
  4592. }
  4593. };
  4594. /**
  4595. * A new presentation has been added.
  4596. *
  4597. * @param event the event indicating the add of a presentation
  4598. * @param jid the jid from which the presentation was added
  4599. * @param presUrl url of the presentation
  4600. * @param currentSlide the current slide to which we should move
  4601. */
  4602. function presentationAdded(event, jid, presUrl, currentSlide) {
  4603. console.log("presentation added", presUrl);
  4604. var presId = getPresentationId(presUrl);
  4605. var elementId = 'participant_'
  4606. + Strophe.getResourceFromJid(jid)
  4607. + '_' + presId;
  4608. VideoLayout.addPreziContainer(elementId);
  4609. var controlsEnabled = false;
  4610. if (jid === APP.xmpp.myJid())
  4611. controlsEnabled = true;
  4612. setPresentationVisible(true);
  4613. VideoLayout.setLargeVideoHover(
  4614. function (event) {
  4615. if (Prezi.isPresentationVisible()) {
  4616. var reloadButtonRight = window.innerWidth
  4617. - $('#presentation>iframe').offset().left
  4618. - $('#presentation>iframe').width();
  4619. $('#reloadPresentation').css({ right: reloadButtonRight,
  4620. display:'inline-block'});
  4621. }
  4622. },
  4623. function (event) {
  4624. if (!Prezi.isPresentationVisible())
  4625. $('#reloadPresentation').css({display:'none'});
  4626. else {
  4627. var e = event.toElement || event.relatedTarget;
  4628. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4629. $('#reloadPresentation').css({display:'none'});
  4630. }
  4631. });
  4632. preziPlayer = new PreziPlayer(
  4633. 'presentation',
  4634. {preziId: presId,
  4635. width: getPresentationWidth(),
  4636. height: getPresentationHeihgt(),
  4637. controls: controlsEnabled,
  4638. debug: true
  4639. });
  4640. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4641. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4642. console.log("prezi status", event.value);
  4643. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4644. if (jid != APP.xmpp.myJid())
  4645. preziPlayer.flyToStep(currentSlide);
  4646. }
  4647. });
  4648. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4649. console.log("event value", event.value);
  4650. APP.xmpp.addToPresence("preziSlide", event.value);
  4651. });
  4652. $("#" + elementId).css( 'background-image',
  4653. 'url(../images/avatarprezi.png)');
  4654. $("#" + elementId).click(
  4655. function () {
  4656. setPresentationVisible(true);
  4657. }
  4658. );
  4659. };
  4660. /**
  4661. * A presentation has been removed.
  4662. *
  4663. * @param event the event indicating the remove of a presentation
  4664. * @param jid the jid for which the presentation was removed
  4665. * @param the url of the presentation
  4666. */
  4667. function presentationRemoved(event, jid, presUrl) {
  4668. console.log('presentation removed', presUrl);
  4669. var presId = getPresentationId(presUrl);
  4670. setPresentationVisible(false);
  4671. $('#participant_'
  4672. + Strophe.getResourceFromJid(jid)
  4673. + '_' + presId).remove();
  4674. $('#presentation>iframe').remove();
  4675. if (preziPlayer != null) {
  4676. preziPlayer.destroy();
  4677. preziPlayer = null;
  4678. }
  4679. };
  4680. /**
  4681. * Indicates if the given string is an alphanumeric string.
  4682. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4683. * purpose of checking URIs.
  4684. */
  4685. function isAlphanumeric(unsafeText) {
  4686. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4687. return regex.test(unsafeText);
  4688. }
  4689. /**
  4690. * Returns the presentation id from the given url.
  4691. */
  4692. function getPresentationId (presUrl) {
  4693. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4694. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4695. }
  4696. /**
  4697. * Returns the presentation width.
  4698. */
  4699. function getPresentationWidth() {
  4700. var availableWidth = UIUtil.getAvailableVideoWidth();
  4701. var availableHeight = getPresentationHeihgt();
  4702. var aspectRatio = 16.0 / 9.0;
  4703. if (availableHeight < availableWidth / aspectRatio) {
  4704. availableWidth = Math.floor(availableHeight * aspectRatio);
  4705. }
  4706. return availableWidth;
  4707. }
  4708. /**
  4709. * Returns the presentation height.
  4710. */
  4711. function getPresentationHeihgt() {
  4712. var remoteVideos = $('#remoteVideos');
  4713. return window.innerHeight - remoteVideos.outerHeight();
  4714. }
  4715. /**
  4716. * Resizes the presentation iframe.
  4717. */
  4718. function resize() {
  4719. if ($('#presentation>iframe')) {
  4720. $('#presentation>iframe').width(getPresentationWidth());
  4721. $('#presentation>iframe').height(getPresentationHeihgt());
  4722. }
  4723. }
  4724. /**
  4725. * Presentation has been removed.
  4726. */
  4727. $(document).bind('presentationremoved.muc', presentationRemoved);
  4728. /**
  4729. * Presentation has been added.
  4730. */
  4731. $(document).bind('presentationadded.muc', presentationAdded);
  4732. /*
  4733. * Indicates presentation slide change.
  4734. */
  4735. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4736. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4737. preziPlayer.flyToStep(current);
  4738. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4739. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4740. preziPlayer.flyToStep(current, i);
  4741. }
  4742. }
  4743. });
  4744. $(window).resize(function () {
  4745. resize();
  4746. });
  4747. module.exports = Prezi;
  4748. },{"../toolbars/ToolbarToggler":31,"../util/MessageHandler":33,"../util/UIUtil":35,"../videolayout/VideoLayout":41,"./PreziPlayer":21}],21:[function(require,module,exports){
  4749. (function() {
  4750. "use strict";
  4751. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4752. window.PreziPlayer = (function() {
  4753. PreziPlayer.API_VERSION = 1;
  4754. PreziPlayer.CURRENT_STEP = 'currentStep';
  4755. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4756. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4757. PreziPlayer.STATUS_LOADING = 'loading';
  4758. PreziPlayer.STATUS_READY = 'ready';
  4759. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4760. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4761. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4762. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4763. PreziPlayer.EVENT_STATUS = "statusChange";
  4764. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4765. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4766. PreziPlayer.domain = "https://prezi.com";
  4767. PreziPlayer.path = "/player/";
  4768. PreziPlayer.players = {};
  4769. PreziPlayer.binded_methods = ['changesHandler'];
  4770. PreziPlayer.createMultiplePlayers = function(optionArray){
  4771. for(var i=0; i<optionArray.length; i++) {
  4772. var optionSet = optionArray[i];
  4773. new PreziPlayer(optionSet.id, optionSet);
  4774. };
  4775. };
  4776. PreziPlayer.messageReceived = function(event){
  4777. var message, item, player;
  4778. try {
  4779. message = JSON.parse(event.data);
  4780. if (message.id && (player = PreziPlayer.players[message.id])) {
  4781. if (player.options.debug === true) {
  4782. if (console && console.log)
  4783. console.log('received', message);
  4784. }
  4785. if (message.type === "changes") {
  4786. player.changesHandler(message);
  4787. }
  4788. for (var i = 0; i < player.callbacks.length; i++) {
  4789. item = player.callbacks[i];
  4790. if (item && message.type === item.event) {
  4791. item.callback(message);
  4792. }
  4793. }
  4794. }
  4795. } catch (e) { }
  4796. };
  4797. function PreziPlayer(id, options) {
  4798. var params, paramString = "", _this = this;
  4799. if (PreziPlayer.players[id]){
  4800. PreziPlayer.players[id].destroy();
  4801. }
  4802. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4803. var method_name = PreziPlayer.binded_methods[i];
  4804. _this[method_name] = __bind(_this[method_name], _this);
  4805. };
  4806. options = options || {};
  4807. this.options = options;
  4808. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4809. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4810. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4811. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4812. this.callbacks = [];
  4813. this.id = id;
  4814. this.embedTo = document.getElementById(id);
  4815. if (!this.embedTo) {
  4816. throw "The element id is not available.";
  4817. }
  4818. this.iframe = document.createElement('iframe');
  4819. params = [
  4820. { name: 'oid', value: options.preziId },
  4821. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4822. { name: 'controls', value: options.controls ? 1 : 0 }
  4823. ];
  4824. for(var i=0; i<params.length; i++) {
  4825. var param = params[i];
  4826. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4827. };
  4828. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4829. this.iframe.frameBorder = 0;
  4830. this.iframe.scrolling = "no";
  4831. this.iframe.width = options.width || 640;
  4832. this.iframe.height = options.height || 480;
  4833. this.embedTo.innerHTML = '';
  4834. // JITSI: IN CASE SOMETHING GOES WRONG.
  4835. try {
  4836. this.embedTo.appendChild(this.iframe);
  4837. }
  4838. catch (err) {
  4839. console.log("CATCH ERROR");
  4840. }
  4841. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4842. // crashes for us.
  4843. this.initPollInterval = setInterval(function(){
  4844. _this.sendMessage({'action': 'init'});
  4845. }, 500);
  4846. PreziPlayer.players[id] = this;
  4847. }
  4848. PreziPlayer.prototype.changesHandler = function(message) {
  4849. var key, value, j, item;
  4850. if (this.initPollInterval) {
  4851. clearInterval(this.initPollInterval);
  4852. this.initPollInterval = false;
  4853. }
  4854. for (key in message.data) {
  4855. if (message.data.hasOwnProperty(key)){
  4856. value = message.data[key];
  4857. this.values[key] = value;
  4858. for (j=0; j<this.callbacks.length; j++) {
  4859. item = this.callbacks[j];
  4860. if (item && item.event === key + "Change"){
  4861. item.callback({type: item.event, value: value});
  4862. }
  4863. }
  4864. }
  4865. }
  4866. };
  4867. PreziPlayer.prototype.destroy = function() {
  4868. if (this.initPollInterval) {
  4869. clearInterval(this.initPollInterval);
  4870. this.initPollInterval = false;
  4871. }
  4872. this.embedTo.innerHTML = '';
  4873. };
  4874. PreziPlayer.prototype.sendMessage = function(message) {
  4875. if (this.options.debug === true) {
  4876. if (console && console.log) console.log('sent', message);
  4877. }
  4878. message.version = PreziPlayer.API_VERSION;
  4879. message.id = this.id;
  4880. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4881. };
  4882. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4883. PreziPlayer.prototype.flyToNextStep = function() {
  4884. return this.sendMessage({
  4885. 'action': 'present',
  4886. 'data': ['moveToNextStep']
  4887. });
  4888. };
  4889. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4890. PreziPlayer.prototype.flyToPreviousStep = function() {
  4891. return this.sendMessage({
  4892. 'action': 'present',
  4893. 'data': ['moveToPrevStep']
  4894. });
  4895. };
  4896. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4897. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4898. var obj = this;
  4899. // check animation_step
  4900. if (animation_step > 0 &&
  4901. obj.values.animationCountOnSteps &&
  4902. obj.values.animationCountOnSteps[step] <= animation_step) {
  4903. animation_step = obj.values.animationCountOnSteps[step];
  4904. }
  4905. // jump to animation steps by calling flyToNextStep()
  4906. function doAnimationSteps() {
  4907. if (obj.values.isMoving == true) {
  4908. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4909. return;
  4910. }
  4911. while (animation_step-- > 0) {
  4912. obj.flyToNextStep(); // do the animation steps
  4913. }
  4914. }
  4915. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4916. // jump to the step
  4917. return this.sendMessage({
  4918. 'action': 'present',
  4919. 'data': ['moveToStep', step]
  4920. });
  4921. };
  4922. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4923. PreziPlayer.prototype.flyToObject = function(objectId) {
  4924. return this.sendMessage({
  4925. 'action': 'present',
  4926. 'data': ['moveToObject', objectId]
  4927. });
  4928. };
  4929. PreziPlayer.prototype.play = function(defaultDelay) {
  4930. return this.sendMessage({
  4931. 'action': 'present',
  4932. 'data': ['startAutoPlay', defaultDelay]
  4933. });
  4934. };
  4935. PreziPlayer.prototype.stop = function() {
  4936. return this.sendMessage({
  4937. 'action': 'present',
  4938. 'data': ['stopAutoPlay']
  4939. });
  4940. };
  4941. PreziPlayer.prototype.pause = function(defaultDelay) {
  4942. return this.sendMessage({
  4943. 'action': 'present',
  4944. 'data': ['pauseAutoPlay', defaultDelay]
  4945. });
  4946. };
  4947. PreziPlayer.prototype.getCurrentStep = function() {
  4948. return this.values.currentStep;
  4949. };
  4950. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4951. return this.values.currentAnimationStep;
  4952. };
  4953. PreziPlayer.prototype.getCurrentObject = function() {
  4954. return this.values.currentObject;
  4955. };
  4956. PreziPlayer.prototype.getStatus = function() {
  4957. return this.values.status;
  4958. };
  4959. PreziPlayer.prototype.isPlaying = function() {
  4960. return this.values.isAutoPlaying;
  4961. };
  4962. PreziPlayer.prototype.getStepCount = function() {
  4963. return this.values.stepCount;
  4964. };
  4965. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4966. return this.values.animationCountOnSteps;
  4967. };
  4968. PreziPlayer.prototype.getTitle = function() {
  4969. return this.values.title;
  4970. };
  4971. PreziPlayer.prototype.setDimensions = function(dims) {
  4972. for (var parameter in dims) {
  4973. this.iframe[parameter] = dims[parameter];
  4974. }
  4975. }
  4976. PreziPlayer.prototype.getDimensions = function() {
  4977. return {
  4978. width: parseInt(this.iframe.width, 10),
  4979. height: parseInt(this.iframe.height, 10)
  4980. }
  4981. }
  4982. PreziPlayer.prototype.on = function(event, callback) {
  4983. this.callbacks.push({
  4984. event: event,
  4985. callback: callback
  4986. });
  4987. };
  4988. PreziPlayer.prototype.off = function(event, callback) {
  4989. var j, item;
  4990. if (event === undefined) {
  4991. this.callbacks = [];
  4992. }
  4993. j = this.callbacks.length;
  4994. while (j--) {
  4995. item = this.callbacks[j];
  4996. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4997. this.callbacks.splice(j, 1);
  4998. }
  4999. }
  5000. };
  5001. if (window.addEventListener) {
  5002. window.addEventListener('message', PreziPlayer.messageReceived, false);
  5003. } else {
  5004. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  5005. }
  5006. return PreziPlayer;
  5007. })();
  5008. })();
  5009. module.exports = PreziPlayer;
  5010. },{}],22:[function(require,module,exports){
  5011. /* global require, $ */
  5012. var Chat = require("./chat/Chat");
  5013. var ContactList = require("./contactlist/ContactList");
  5014. var Settings = require("./../../settings/Settings");
  5015. var SettingsMenu = require("./settings/SettingsMenu");
  5016. var VideoLayout = require("../videolayout/VideoLayout");
  5017. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  5018. var UIUtil = require("../util/UIUtil");
  5019. var LargeVideo = require("../videolayout/LargeVideo");
  5020. /**
  5021. * Toggler for the chat, contact list, settings menu, etc..
  5022. */
  5023. var PanelToggler = (function(my) {
  5024. var currentlyOpen = null;
  5025. var buttons = {
  5026. '#chatspace': '#chatBottomButton',
  5027. '#contactlist': '#contactListButton',
  5028. '#settingsmenu': '#toolbar_button_settings'
  5029. };
  5030. /**
  5031. * Toggles the windows in the side panel
  5032. * @param object the window that should be shown
  5033. * @param selector the selector for the element containing the panel
  5034. * @param onOpenComplete function to be called when the panel is opened
  5035. * @param onOpen function to be called if the window is going to be opened
  5036. * @param onClose function to be called if the window is going to be closed
  5037. */
  5038. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  5039. UIUtil.buttonClick(buttons[selector], "active");
  5040. if (object.isVisible()) {
  5041. $("#toast-container").animate({
  5042. right: '5px'
  5043. },
  5044. {
  5045. queue: false,
  5046. duration: 500
  5047. });
  5048. $(selector).hide("slide", {
  5049. direction: "right",
  5050. queue: false,
  5051. duration: 500
  5052. });
  5053. if(typeof onClose === "function") {
  5054. onClose();
  5055. }
  5056. currentlyOpen = null;
  5057. }
  5058. else {
  5059. // Undock the toolbar when the chat is shown and if we're in a
  5060. // video mode.
  5061. if (LargeVideo.isLargeVideoVisible()) {
  5062. ToolbarToggler.dockToolbar(false);
  5063. }
  5064. if(currentlyOpen) {
  5065. var current = $(currentlyOpen);
  5066. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  5067. current.css('z-index', 4);
  5068. setTimeout(function () {
  5069. current.css('display', 'none');
  5070. current.css('z-index', 5);
  5071. }, 500);
  5072. }
  5073. $("#toast-container").animate({
  5074. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  5075. },
  5076. {
  5077. queue: false,
  5078. duration: 500
  5079. });
  5080. $(selector).show("slide", {
  5081. direction: "right",
  5082. queue: false,
  5083. duration: 500,
  5084. complete: onOpenComplete
  5085. });
  5086. if(typeof onOpen === "function") {
  5087. onOpen();
  5088. }
  5089. currentlyOpen = selector;
  5090. }
  5091. };
  5092. /**
  5093. * Opens / closes the chat area.
  5094. */
  5095. my.toggleChat = function() {
  5096. var chatCompleteFunction = Chat.isVisible() ?
  5097. function() {} : function () {
  5098. Chat.scrollChatToBottom();
  5099. $('#chatspace').trigger('shown');
  5100. };
  5101. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  5102. toggle(Chat,
  5103. '#chatspace',
  5104. function () {
  5105. // Request the focus in the nickname field or the chat input field.
  5106. if ($('#nickname').css('visibility') === 'visible') {
  5107. $('#nickinput').focus();
  5108. } else {
  5109. $('#usermsg').focus();
  5110. }
  5111. },
  5112. null,
  5113. Chat.resizeChat,
  5114. null);
  5115. };
  5116. /**
  5117. * Opens / closes the contact list area.
  5118. */
  5119. my.toggleContactList = function () {
  5120. var completeFunction = ContactList.isVisible() ?
  5121. function() {} : function () { $('#contactlist').trigger('shown');};
  5122. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  5123. toggle(ContactList,
  5124. '#contactlist',
  5125. null,
  5126. function() {
  5127. ContactList.setVisualNotification(false);
  5128. },
  5129. null);
  5130. };
  5131. /**
  5132. * Opens / closes the settings menu
  5133. */
  5134. my.toggleSettingsMenu = function() {
  5135. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  5136. toggle(SettingsMenu,
  5137. '#settingsmenu',
  5138. null,
  5139. function() {
  5140. var settings = Settings.getSettings();
  5141. $('#setDisplayName').get(0).value = settings.displayName;
  5142. $('#setEmail').get(0).value = settings.email;
  5143. },
  5144. null);
  5145. };
  5146. /**
  5147. * Returns the size of the side panel.
  5148. */
  5149. my.getPanelSize = function () {
  5150. var availableHeight = window.innerHeight;
  5151. var availableWidth = window.innerWidth;
  5152. var panelWidth = 200;
  5153. if (availableWidth * 0.2 < 200) {
  5154. panelWidth = availableWidth * 0.2;
  5155. }
  5156. return [panelWidth, availableHeight];
  5157. };
  5158. my.isVisible = function() {
  5159. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  5160. };
  5161. return my;
  5162. }(PanelToggler || {}));
  5163. module.exports = PanelToggler;
  5164. },{"../toolbars/ToolbarToggler":31,"../util/UIUtil":35,"../videolayout/LargeVideo":37,"../videolayout/VideoLayout":41,"./../../settings/Settings":51,"./chat/Chat":23,"./contactlist/ContactList":27,"./settings/SettingsMenu":28}],23:[function(require,module,exports){
  5165. /* global APP, $, Util, nickname:true */
  5166. var Replacement = require("./Replacement");
  5167. var CommandsProcessor = require("./Commands");
  5168. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  5169. var smileys = require("./smileys.json").smileys;
  5170. var NicknameHandler = require("../../util/NicknameHandler");
  5171. var UIUtil = require("../../util/UIUtil");
  5172. var UIEvents = require("../../../../service/UI/UIEvents");
  5173. var notificationInterval = false;
  5174. var unreadMessages = 0;
  5175. /**
  5176. * Shows/hides a visual notification, indicating that a message has arrived.
  5177. */
  5178. function setVisualNotification(show) {
  5179. var unreadMsgElement = document.getElementById('unreadMessages');
  5180. var unreadMsgBottomElement
  5181. = document.getElementById('bottomUnreadMessages');
  5182. var glower = $('#toolbar_button_chat');
  5183. var bottomGlower = $('#chatBottomButton');
  5184. if (unreadMessages) {
  5185. unreadMsgElement.innerHTML = unreadMessages.toString();
  5186. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  5187. ToolbarToggler.dockToolbar(true);
  5188. var chatButtonElement
  5189. = document.getElementById('toolbar_button_chat');
  5190. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  5191. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  5192. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  5193. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  5194. unreadMsgElement.setAttribute(
  5195. 'style',
  5196. 'top:' + topIndent +
  5197. '; left:' + leftIndent + ';');
  5198. var chatBottomButtonElement
  5199. = document.getElementById('chatBottomButton').parentNode;
  5200. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  5201. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  5202. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  5203. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  5204. unreadMsgBottomElement.setAttribute(
  5205. 'style',
  5206. 'top:' + bottomTopIndent +
  5207. '; left:' + bottomLeftIndent + ';');
  5208. if (!glower.hasClass('icon-chat-simple')) {
  5209. glower.removeClass('icon-chat');
  5210. glower.addClass('icon-chat-simple');
  5211. }
  5212. }
  5213. else {
  5214. unreadMsgElement.innerHTML = '';
  5215. unreadMsgBottomElement.innerHTML = '';
  5216. glower.removeClass('icon-chat-simple');
  5217. glower.addClass('icon-chat');
  5218. }
  5219. if (show && !notificationInterval) {
  5220. notificationInterval = window.setInterval(function () {
  5221. glower.toggleClass('active');
  5222. bottomGlower.toggleClass('active glowing');
  5223. }, 800);
  5224. }
  5225. else if (!show && notificationInterval) {
  5226. window.clearInterval(notificationInterval);
  5227. notificationInterval = false;
  5228. glower.removeClass('active');
  5229. bottomGlower.removeClass('glowing');
  5230. bottomGlower.addClass('active');
  5231. }
  5232. }
  5233. /**
  5234. * Returns the current time in the format it is shown to the user
  5235. * @returns {string}
  5236. */
  5237. function getCurrentTime(stamp) {
  5238. var now = (stamp? new Date(stamp): new Date());
  5239. var hour = now.getHours();
  5240. var minute = now.getMinutes();
  5241. var second = now.getSeconds();
  5242. if(hour.toString().length === 1) {
  5243. hour = '0'+hour;
  5244. }
  5245. if(minute.toString().length === 1) {
  5246. minute = '0'+minute;
  5247. }
  5248. if(second.toString().length === 1) {
  5249. second = '0'+second;
  5250. }
  5251. return hour+':'+minute+':'+second;
  5252. }
  5253. function toggleSmileys() {
  5254. var smileys = $('#smileysContainer');
  5255. if(!smileys.is(':visible')) {
  5256. smileys.show("slide", { direction: "down", duration: 300});
  5257. } else {
  5258. smileys.hide("slide", { direction: "down", duration: 300});
  5259. }
  5260. $('#usermsg').focus();
  5261. }
  5262. function addClickFunction(smiley, number) {
  5263. smiley.onclick = function addSmileyToMessage() {
  5264. var usermsg = $('#usermsg');
  5265. var message = usermsg.val();
  5266. message += smileys['smiley' + number];
  5267. usermsg.val(message);
  5268. usermsg.get(0).setSelectionRange(message.length, message.length);
  5269. toggleSmileys();
  5270. usermsg.focus();
  5271. };
  5272. }
  5273. /**
  5274. * Adds the smileys container to the chat
  5275. */
  5276. function addSmileys() {
  5277. var smileysContainer = document.createElement('div');
  5278. smileysContainer.id = 'smileysContainer';
  5279. for(var i = 1; i <= 21; i++) {
  5280. var smileyContainer = document.createElement('div');
  5281. smileyContainer.id = 'smiley' + i;
  5282. smileyContainer.className = 'smileyContainer';
  5283. var smiley = document.createElement('img');
  5284. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5285. smiley.className = 'smiley';
  5286. addClickFunction(smiley, i);
  5287. smileyContainer.appendChild(smiley);
  5288. smileysContainer.appendChild(smileyContainer);
  5289. }
  5290. $("#chatspace").append(smileysContainer);
  5291. }
  5292. /**
  5293. * Resizes the chat conversation.
  5294. */
  5295. function resizeChatConversation() {
  5296. var msgareaHeight = $('#usermsg').outerHeight();
  5297. var chatspace = $('#chatspace');
  5298. var width = chatspace.width();
  5299. var chat = $('#chatconversation');
  5300. var smileys = $('#smileysarea');
  5301. smileys.height(msgareaHeight);
  5302. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5303. $('#smileysContainer').css('bottom', msgareaHeight);
  5304. chat.width(width - 10);
  5305. chat.height(window.innerHeight - 15 - msgareaHeight);
  5306. }
  5307. /**
  5308. * Chat related user interface.
  5309. */
  5310. var Chat = (function (my) {
  5311. /**
  5312. * Initializes chat related interface.
  5313. */
  5314. my.init = function () {
  5315. if(NicknameHandler.getNickname())
  5316. Chat.setChatConversationMode(true);
  5317. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5318. function (nickname) {
  5319. Chat.setChatConversationMode(true);
  5320. });
  5321. $('#nickinput').keydown(function (event) {
  5322. if (event.keyCode === 13) {
  5323. event.preventDefault();
  5324. var val = UIUtil.escapeHtml(this.value);
  5325. this.value = '';
  5326. if (!NicknameHandler.getNickname()) {
  5327. NicknameHandler.setNickname(val);
  5328. return;
  5329. }
  5330. }
  5331. });
  5332. var usermsg = $('#usermsg');
  5333. usermsg.keydown(function (event) {
  5334. if (event.keyCode === 13) {
  5335. event.preventDefault();
  5336. var value = this.value;
  5337. usermsg.val('').trigger('autosize.resize');
  5338. this.focus();
  5339. var command = new CommandsProcessor(value);
  5340. if(command.isCommand()) {
  5341. command.processCommand();
  5342. }
  5343. else {
  5344. var message = UIUtil.escapeHtml(value);
  5345. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5346. }
  5347. }
  5348. });
  5349. var onTextAreaResize = function () {
  5350. resizeChatConversation();
  5351. Chat.scrollChatToBottom();
  5352. };
  5353. usermsg.autosize({callback: onTextAreaResize});
  5354. $("#chatspace").bind("shown",
  5355. function () {
  5356. unreadMessages = 0;
  5357. setVisualNotification(false);
  5358. });
  5359. addSmileys();
  5360. };
  5361. /**
  5362. * Appends the given message to the chat conversation.
  5363. */
  5364. my.updateChatConversation =
  5365. function (from, displayName, message, myjid, stamp) {
  5366. var divClassName = '';
  5367. if (APP.xmpp.myJid() === from) {
  5368. divClassName = "localuser";
  5369. }
  5370. else {
  5371. divClassName = "remoteuser";
  5372. if (!Chat.isVisible()) {
  5373. unreadMessages++;
  5374. UIUtil.playSoundNotification('chatNotification');
  5375. setVisualNotification(true);
  5376. }
  5377. }
  5378. // replace links and smileys
  5379. // Strophe already escapes special symbols on sending,
  5380. // so we escape here only tags to avoid double &amp;
  5381. var escMessage = message.replace(/</g, '&lt;').
  5382. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5383. var escDisplayName = UIUtil.escapeHtml(displayName);
  5384. message = Replacement.processReplacements(escMessage);
  5385. var messageContainer =
  5386. '<div class="chatmessage">'+
  5387. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5388. '<div class="username ' + divClassName +'">' + escDisplayName +
  5389. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5390. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5391. '</div>';
  5392. $('#chatconversation').append(messageContainer);
  5393. $('#chatconversation').animate(
  5394. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5395. };
  5396. /**
  5397. * Appends error message to the conversation
  5398. * @param errorMessage the received error message.
  5399. * @param originalText the original message.
  5400. */
  5401. my.chatAddError = function(errorMessage, originalText) {
  5402. errorMessage = UIUtil.escapeHtml(errorMessage);
  5403. originalText = UIUtil.escapeHtml(originalText);
  5404. $('#chatconversation').append(
  5405. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5406. (originalText? (' \"'+ originalText + '\"') : "") +
  5407. ' was not sent.' +
  5408. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5409. $('#chatconversation').animate(
  5410. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5411. };
  5412. /**
  5413. * Sets the subject to the UI
  5414. * @param subject the subject
  5415. */
  5416. my.chatSetSubject = function(subject) {
  5417. if (subject)
  5418. subject = subject.trim();
  5419. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5420. if(subject === "") {
  5421. $("#subject").css({display: "none"});
  5422. }
  5423. else {
  5424. $("#subject").css({display: "block"});
  5425. }
  5426. };
  5427. /**
  5428. * Sets the chat conversation mode.
  5429. */
  5430. my.setChatConversationMode = function (isConversationMode) {
  5431. if (isConversationMode) {
  5432. $('#nickname').css({visibility: 'hidden'});
  5433. $('#chatconversation').css({visibility: 'visible'});
  5434. $('#usermsg').css({visibility: 'visible'});
  5435. $('#smileysarea').css({visibility: 'visible'});
  5436. $('#usermsg').focus();
  5437. }
  5438. };
  5439. /**
  5440. * Resizes the chat area.
  5441. */
  5442. my.resizeChat = function () {
  5443. var chatSize = require("../SidePanelToggler").getPanelSize();
  5444. $('#chatspace').width(chatSize[0]);
  5445. $('#chatspace').height(chatSize[1]);
  5446. resizeChatConversation();
  5447. };
  5448. /**
  5449. * Indicates if the chat is currently visible.
  5450. */
  5451. my.isVisible = function () {
  5452. return $('#chatspace').is(":visible");
  5453. };
  5454. /**
  5455. * Shows and hides the window with the smileys
  5456. */
  5457. my.toggleSmileys = toggleSmileys;
  5458. /**
  5459. * Scrolls chat to the bottom.
  5460. */
  5461. my.scrollChatToBottom = function() {
  5462. setTimeout(function () {
  5463. $('#chatconversation').scrollTop(
  5464. $('#chatconversation')[0].scrollHeight);
  5465. }, 5);
  5466. };
  5467. return my;
  5468. }(Chat || {}));
  5469. module.exports = Chat;
  5470. },{"../../../../service/UI/UIEvents":168,"../../toolbars/ToolbarToggler":31,"../../util/NicknameHandler":34,"../../util/UIUtil":35,"../SidePanelToggler":22,"./Commands":24,"./Replacement":25,"./smileys.json":26}],24:[function(require,module,exports){
  5471. /* global APP, require */
  5472. var UIUtil = require("../../util/UIUtil");
  5473. /**
  5474. * List with supported commands. The keys are the names of the commands and
  5475. * the value is the function that processes the message.
  5476. * @type {{String: function}}
  5477. */
  5478. var commands = {
  5479. "topic" : processTopic
  5480. };
  5481. /**
  5482. * Extracts the command from the message.
  5483. * @param message the received message
  5484. * @returns {string} the command
  5485. */
  5486. function getCommand(message) {
  5487. if(message) {
  5488. for(var command in commands) {
  5489. if(message.indexOf("/" + command) == 0)
  5490. return command;
  5491. }
  5492. }
  5493. return "";
  5494. }
  5495. /**
  5496. * Processes the data for topic command.
  5497. * @param commandArguments the arguments of the topic command.
  5498. */
  5499. function processTopic(commandArguments) {
  5500. var topic = UIUtil.escapeHtml(commandArguments);
  5501. APP.xmpp.setSubject(topic);
  5502. }
  5503. /**
  5504. * Constructs a new CommandProccessor instance from a message that
  5505. * handles commands received via chat messages.
  5506. * @param message the message
  5507. * @constructor
  5508. */
  5509. function CommandsProcessor(message) {
  5510. var command = getCommand(message);
  5511. /**
  5512. * Returns the name of the command.
  5513. * @returns {String} the command
  5514. */
  5515. this.getCommand = function() {
  5516. return command;
  5517. };
  5518. var messageArgument = message.substr(command.length + 2);
  5519. /**
  5520. * Returns the arguments of the command.
  5521. * @returns {string}
  5522. */
  5523. this.getArgument = function() {
  5524. return messageArgument;
  5525. };
  5526. }
  5527. /**
  5528. * Checks whether this instance is valid command or not.
  5529. * @returns {boolean}
  5530. */
  5531. CommandsProcessor.prototype.isCommand = function() {
  5532. if (this.getCommand())
  5533. return true;
  5534. return false;
  5535. };
  5536. /**
  5537. * Processes the command.
  5538. */
  5539. CommandsProcessor.prototype.processCommand = function() {
  5540. if(!this.isCommand())
  5541. return;
  5542. commands[this.getCommand()](this.getArgument());
  5543. };
  5544. module.exports = CommandsProcessor;
  5545. },{"../../util/UIUtil":35}],25:[function(require,module,exports){
  5546. var Smileys = require("./smileys.json");
  5547. /**
  5548. * Processes links and smileys in "body"
  5549. */
  5550. function processReplacements(body)
  5551. {
  5552. //make links clickable
  5553. body = linkify(body);
  5554. //add smileys
  5555. body = smilify(body);
  5556. return body;
  5557. }
  5558. /**
  5559. * Finds and replaces all links in the links in "body"
  5560. * with their <a href=""></a>
  5561. */
  5562. function linkify(inputText)
  5563. {
  5564. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5565. //URLs starting with http://, https://, or ftp://
  5566. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5567. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5568. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5569. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5570. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5571. //Change email addresses to mailto:: links.
  5572. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5573. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5574. return replacedText;
  5575. }
  5576. /**
  5577. * Replaces common smiley strings with images
  5578. */
  5579. function smilify(body)
  5580. {
  5581. if(!body) {
  5582. return body;
  5583. }
  5584. var regexs = Smileys["regexs"];
  5585. for(var smiley in regexs) {
  5586. if(regexs.hasOwnProperty(smiley)) {
  5587. body = body.replace(regexs[smiley],
  5588. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5589. }
  5590. }
  5591. return body;
  5592. }
  5593. module.exports = {
  5594. processReplacements: processReplacements,
  5595. linkify: linkify
  5596. };
  5597. },{"./smileys.json":26}],26:[function(require,module,exports){
  5598. module.exports={
  5599. "smileys": {
  5600. "smiley1": ":)",
  5601. "smiley2": ":(",
  5602. "smiley3": ":D",
  5603. "smiley4": "(y)",
  5604. "smiley5": " :P",
  5605. "smiley6": "(wave)",
  5606. "smiley7": "(blush)",
  5607. "smiley8": "(chuckle)",
  5608. "smiley9": "(shocked)",
  5609. "smiley10": ":*",
  5610. "smiley11": "(n)",
  5611. "smiley12": "(search)",
  5612. "smiley13": " <3",
  5613. "smiley14": "(oops)",
  5614. "smiley15": "(angry)",
  5615. "smiley16": "(angel)",
  5616. "smiley17": "(sick)",
  5617. "smiley18": ";(",
  5618. "smiley19": "(bomb)",
  5619. "smiley20": "(clap)",
  5620. "smiley21": " ;)"
  5621. },
  5622. "regexs": {
  5623. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5624. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5625. "smiley1": /(:-\)|:\))/gi,
  5626. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5627. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5628. "smiley6": /(\(wave\))/gi,
  5629. "smiley7": /(\(blush\))/gi,
  5630. "smiley8": /(\(chuckle\))/gi,
  5631. "smiley9": /(:-0|\(shocked\))/gi,
  5632. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5633. "smiley11": /(\(n\))/gi,
  5634. "smiley12": /(\(search\))/g,
  5635. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5636. "smiley14": /(\(oops\))/gi,
  5637. "smiley15": /(\(angry\))/gi,
  5638. "smiley16": /(\(angel\))/gi,
  5639. "smiley17": /(\(sick\))/gi,
  5640. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5641. "smiley19": /(\(bomb\))/gi,
  5642. "smiley20": /(\(clap\))/gi,
  5643. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5644. }
  5645. }
  5646. },{}],27:[function(require,module,exports){
  5647. /* global $, APP, Strophe */
  5648. var Avatar = require('../../avatar/Avatar');
  5649. var numberOfContacts = 0;
  5650. var notificationInterval;
  5651. /**
  5652. * Updates the number of participants in the contact list button and sets
  5653. * the glow
  5654. * @param delta indicates whether a new user has joined (1) or someone has
  5655. * left(-1)
  5656. */
  5657. function updateNumberOfParticipants(delta) {
  5658. numberOfContacts += delta;
  5659. if (numberOfContacts === 1) {
  5660. // when the user is alone we don't show the number of participants
  5661. $("#numberOfParticipants").text('');
  5662. ContactList.setVisualNotification(false);
  5663. } else if (numberOfContacts > 1) {
  5664. ContactList.setVisualNotification(!ContactList.isVisible());
  5665. $("#numberOfParticipants").text(numberOfContacts);
  5666. } else {
  5667. console.error("Invalid number of participants: " + numberOfContacts);
  5668. }
  5669. }
  5670. /**
  5671. * Creates the avatar element.
  5672. *
  5673. * @return {object} the newly created avatar element
  5674. */
  5675. function createAvatar(jid) {
  5676. var avatar = document.createElement('img');
  5677. avatar.className = "icon-avatar avatar";
  5678. avatar.src = Avatar.getContactListUrl(jid);
  5679. return avatar;
  5680. }
  5681. /**
  5682. * Creates the display name paragraph.
  5683. *
  5684. * @param displayName the display name to set
  5685. */
  5686. function createDisplayNameParagraph(key, displayName) {
  5687. var p = document.createElement('p');
  5688. if(displayName)
  5689. p.innerText = displayName;
  5690. else if(key) {
  5691. p.setAttribute("data-i18n",key);
  5692. p.innerText = APP.translation.translateString(key);
  5693. }
  5694. return p;
  5695. }
  5696. function stopGlowing(glower) {
  5697. window.clearInterval(notificationInterval);
  5698. notificationInterval = false;
  5699. glower.removeClass('glowing');
  5700. if (!ContactList.isVisible()) {
  5701. glower.removeClass('active');
  5702. }
  5703. }
  5704. /**
  5705. * Contact list.
  5706. */
  5707. var ContactList = {
  5708. /**
  5709. * Indicates if the chat is currently visible.
  5710. *
  5711. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5712. * otherwise
  5713. */
  5714. isVisible: function () {
  5715. return $('#contactlist').is(":visible");
  5716. },
  5717. /**
  5718. * Adds a contact for the given peerJid if such doesn't yet exist.
  5719. *
  5720. * @param peerJid the peerJid corresponding to the contact
  5721. */
  5722. ensureAddContact: function (peerJid) {
  5723. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5724. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5725. if (!contact || contact.length <= 0)
  5726. ContactList.addContact(peerJid);
  5727. },
  5728. /**
  5729. * Adds a contact for the given peer jid.
  5730. *
  5731. * @param peerJid the jid of the contact to add
  5732. */
  5733. addContact: function (peerJid) {
  5734. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5735. var contactlist = $('#contacts');
  5736. var newContact = document.createElement('li');
  5737. newContact.id = resourceJid;
  5738. newContact.className = "clickable";
  5739. newContact.onclick = function (event) {
  5740. if (event.currentTarget.className === "clickable") {
  5741. $(ContactList).trigger('contactclicked', [peerJid]);
  5742. }
  5743. };
  5744. newContact.appendChild(createAvatar(peerJid));
  5745. newContact.appendChild(createDisplayNameParagraph("participant"));
  5746. if (resourceJid === APP.xmpp.myResource()) {
  5747. contactlist.prepend(newContact);
  5748. }
  5749. else {
  5750. contactlist.append(newContact);
  5751. }
  5752. updateNumberOfParticipants(1);
  5753. },
  5754. /**
  5755. * Removes a contact for the given peer jid.
  5756. *
  5757. * @param peerJid the peerJid corresponding to the contact to remove
  5758. */
  5759. removeContact: function (peerJid) {
  5760. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5761. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5762. if (contact && contact.length > 0) {
  5763. var contactlist = $('#contactlist>ul');
  5764. contactlist.get(0).removeChild(contact.get(0));
  5765. updateNumberOfParticipants(-1);
  5766. }
  5767. },
  5768. setVisualNotification: function (show, stopGlowingIn) {
  5769. var glower = $('#contactListButton');
  5770. if (show && !notificationInterval) {
  5771. notificationInterval = window.setInterval(function () {
  5772. glower.toggleClass('active glowing');
  5773. }, 800);
  5774. }
  5775. else if (!show && notificationInterval) {
  5776. stopGlowing(glower);
  5777. }
  5778. if (stopGlowingIn) {
  5779. setTimeout(function () {
  5780. stopGlowing(glower);
  5781. }, stopGlowingIn);
  5782. }
  5783. },
  5784. setClickable: function (resourceJid, isClickable) {
  5785. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5786. if (isClickable) {
  5787. contact.addClass('clickable');
  5788. } else {
  5789. contact.removeClass('clickable');
  5790. }
  5791. },
  5792. onDisplayNameChange: function (peerJid, displayName) {
  5793. if (peerJid === 'localVideoContainer')
  5794. peerJid = APP.xmpp.myJid();
  5795. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5796. var contactName = $('#contacts #' + resourceJid + '>p');
  5797. if (contactName && displayName && displayName.length > 0)
  5798. contactName.html(displayName);
  5799. },
  5800. userAvatarChanged: function (resourceJid, contactListUrl) {
  5801. // set the avatar in the contact list
  5802. var contact = $('#' + resourceJid + '>img');
  5803. if (contact && contact.length > 0) {
  5804. contact.get(0).src = contactListUrl;
  5805. }
  5806. }
  5807. };
  5808. module.exports = ContactList;
  5809. },{"../../avatar/Avatar":18}],28:[function(require,module,exports){
  5810. /* global APP, $ */
  5811. var Avatar = require("../../avatar/Avatar");
  5812. var Settings = require("./../../../settings/Settings");
  5813. var UIUtil = require("../../util/UIUtil");
  5814. var languages = require("../../../../service/translation/languages");
  5815. function generateLanguagesSelectBox() {
  5816. var currentLang = APP.translation.getCurrentLanguage();
  5817. var html = "<select id=\"languages_selectbox\">";
  5818. var langArray = languages.getLanguages();
  5819. for(var i = 0; i < langArray.length; i++) {
  5820. var lang = langArray[i];
  5821. html += "<option ";
  5822. if(lang === currentLang)
  5823. html += "selected ";
  5824. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5825. html += "</option>";
  5826. }
  5827. return html + "</select>";
  5828. }
  5829. var SettingsMenu = {
  5830. init: function () {
  5831. var startMutedSelector = $("#startMutedOptions");
  5832. startMutedSelector.before(generateLanguagesSelectBox());
  5833. APP.translation.translateElement($("#languages_selectbox"));
  5834. $('#settingsmenu>input').keyup(function(event){
  5835. if(event.keyCode === 13) {//enter
  5836. SettingsMenu.update();
  5837. }
  5838. });
  5839. if (APP.xmpp.isModerator()) {
  5840. startMutedSelector.css("display", "block");
  5841. }
  5842. else {
  5843. startMutedSelector.css("display", "none");
  5844. }
  5845. $("#updateSettings").click(function () {
  5846. SettingsMenu.update();
  5847. });
  5848. },
  5849. onRoleChanged: function () {
  5850. if(APP.xmpp.isModerator()) {
  5851. $("#startMutedOptions").css("display", "block");
  5852. }
  5853. else {
  5854. $("#startMutedOptions").css("display", "none");
  5855. }
  5856. },
  5857. setStartMuted: function (audio, video) {
  5858. $("#startAudioMuted").attr("checked", audio);
  5859. $("#startVideoMuted").attr("checked", video);
  5860. },
  5861. update: function() {
  5862. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5863. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5864. if(newDisplayName) {
  5865. var displayName = Settings.setDisplayName(newDisplayName);
  5866. APP.xmpp.addToPresence("displayName", displayName, true);
  5867. }
  5868. var language = $("#languages_selectbox").val();
  5869. APP.translation.setLanguage(language);
  5870. Settings.setLanguage(language);
  5871. APP.xmpp.addToPresence("email", newEmail);
  5872. var email = Settings.setEmail(newEmail);
  5873. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5874. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5875. APP.xmpp.addToPresence("startMuted",
  5876. [startAudioMuted, startVideoMuted]);
  5877. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5878. },
  5879. isVisible: function() {
  5880. return $('#settingsmenu').is(':visible');
  5881. },
  5882. setDisplayName: function(newDisplayName) {
  5883. var displayName = Settings.setDisplayName(newDisplayName);
  5884. $('#setDisplayName').get(0).value = displayName;
  5885. },
  5886. onDisplayNameChange: function(peerJid, newDisplayName) {
  5887. if(peerJid === 'localVideoContainer' ||
  5888. peerJid === APP.xmpp.myJid()) {
  5889. this.setDisplayName(newDisplayName);
  5890. }
  5891. },
  5892. changeAvatar: function (thumbUrl) {
  5893. $('#avatar').get(0).src = thumbUrl;
  5894. }
  5895. };
  5896. module.exports = SettingsMenu;
  5897. },{"../../../../service/translation/languages":173,"../../avatar/Avatar":18,"../../util/UIUtil":35,"./../../../settings/Settings":51}],29:[function(require,module,exports){
  5898. /* global $ */
  5899. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5900. var UIUtil = require("../util/UIUtil");
  5901. var buttonHandlers = {
  5902. "bottom_toolbar_contact_list": function () {
  5903. BottomToolbar.toggleContactList();
  5904. },
  5905. "bottom_toolbar_film_strip": function () {
  5906. BottomToolbar.toggleFilmStrip();
  5907. },
  5908. "bottom_toolbar_chat": function () {
  5909. BottomToolbar.toggleChat();
  5910. }
  5911. };
  5912. var defaultBottomToolbarButtons = {
  5913. 'chat': '#bottom_toolbar_chat',
  5914. 'contacts': '#bottom_toolbar_contact_list',
  5915. 'filmstrip': '#bottom_toolbar_film_strip'
  5916. };
  5917. var BottomToolbar = (function (my) {
  5918. my.init = function () {
  5919. UIUtil.hideDisabledButtons(defaultBottomToolbarButtons);
  5920. for(var k in buttonHandlers)
  5921. $("#" + k).click(buttonHandlers[k]);
  5922. };
  5923. my.toggleChat = function() {
  5924. PanelToggler.toggleChat();
  5925. };
  5926. my.toggleContactList = function() {
  5927. PanelToggler.toggleContactList();
  5928. };
  5929. my.toggleFilmStrip = function() {
  5930. var filmstrip = $("#remoteVideos");
  5931. filmstrip.toggleClass("hidden");
  5932. };
  5933. $(document).bind("remotevideo.resized", function (event, width, height) {
  5934. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5935. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5936. });
  5937. return my;
  5938. }(BottomToolbar || {}));
  5939. module.exports = BottomToolbar;
  5940. },{"../side_pannels/SidePanelToggler":22,"../util/UIUtil":35}],30:[function(require,module,exports){
  5941. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  5942. Util */
  5943. var messageHandler = require("../util/MessageHandler");
  5944. var BottomToolbar = require("./BottomToolbar");
  5945. var Prezi = require("../prezi/Prezi");
  5946. var Etherpad = require("../etherpad/Etherpad");
  5947. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5948. var Authentication = require("../authentication/Authentication");
  5949. var UIUtil = require("../util/UIUtil");
  5950. var AuthenticationEvents
  5951. = require("../../../service/authentication/AuthenticationEvents");
  5952. var roomUrl = null;
  5953. var sharedKey = '';
  5954. var UI = null;
  5955. var recordingToaster = null;
  5956. var buttonHandlers = {
  5957. "toolbar_button_mute": function () {
  5958. return APP.UI.toggleAudio();
  5959. },
  5960. "toolbar_button_camera": function () {
  5961. return APP.UI.toggleVideo();
  5962. },
  5963. /*"toolbar_button_authentication": function () {
  5964. return Toolbar.authenticateClicked();
  5965. },*/
  5966. "toolbar_button_record": function () {
  5967. return toggleRecording();
  5968. },
  5969. "toolbar_button_security": function () {
  5970. return Toolbar.openLockDialog();
  5971. },
  5972. "toolbar_button_link": function () {
  5973. return Toolbar.openLinkDialog();
  5974. },
  5975. "toolbar_button_chat": function () {
  5976. return BottomToolbar.toggleChat();
  5977. },
  5978. "toolbar_button_prezi": function () {
  5979. return Prezi.openPreziDialog();
  5980. },
  5981. "toolbar_button_etherpad": function () {
  5982. return Etherpad.toggleEtherpad(0);
  5983. },
  5984. "toolbar_button_desktopsharing": function () {
  5985. return APP.desktopsharing.toggleScreenSharing();
  5986. },
  5987. "toolbar_button_fullScreen": function() {
  5988. UIUtil.buttonClick("#toolbar_button_fullScreen", "icon-full-screen icon-exit-full-screen");
  5989. return Toolbar.toggleFullScreen();
  5990. },
  5991. "toolbar_button_sip": function () {
  5992. return callSipButtonClicked();
  5993. },
  5994. "toolbar_button_dialpad": function () {
  5995. return dialpadButtonClicked();
  5996. },
  5997. "toolbar_button_settings": function () {
  5998. PanelToggler.toggleSettingsMenu();
  5999. },
  6000. "toolbar_button_hangup": function () {
  6001. return hangup();
  6002. },
  6003. "toolbar_button_login": function () {
  6004. Toolbar.authenticateClicked();
  6005. },
  6006. "toolbar_button_logout": function () {
  6007. // Ask for confirmation
  6008. messageHandler.openTwoButtonDialog(
  6009. "dialog.logoutTitle",
  6010. null,
  6011. "dialog.logoutQuestion",
  6012. null,
  6013. false,
  6014. "dialog.Yes",
  6015. function (evt, yes) {
  6016. if (yes) {
  6017. APP.xmpp.logout(function (url) {
  6018. if (url) {
  6019. window.location.href = url;
  6020. } else {
  6021. hangup();
  6022. }
  6023. });
  6024. }
  6025. });
  6026. }
  6027. };
  6028. var defaultToolbarButtons = {
  6029. 'microphone': '#toolbar_button_mute',
  6030. 'camera': '#toolbar_button_camera',
  6031. 'desktop': '#toolbar_button_desktopsharing',
  6032. 'security': '#toolbar_button_security',
  6033. 'invite': '#toolbar_button_link',
  6034. 'chat': '#toolbar_button_chat',
  6035. 'prezi': '#toolbar_button_prezi',
  6036. 'ethherpad': '#toolbar_button_etherpad',
  6037. 'fullscreen': '#toolbar_button_fullScreen',
  6038. 'settings': '#toolbar_button_settings',
  6039. 'hangup': '#toolbar_button_hangup'
  6040. };
  6041. function hangup() {
  6042. APP.xmpp.disposeConference();
  6043. if(config.enableWelcomePage) {
  6044. setTimeout(function() {
  6045. window.localStorage.welcomePageDisabled = false;
  6046. window.location.pathname = "/";
  6047. }, 10000);
  6048. }
  6049. var title = APP.translation.generateTranslationHTML(
  6050. "dialog.sessTerminated");
  6051. var msg = APP.translation.generateTranslationHTML(
  6052. "dialog.hungUp");
  6053. var button = APP.translation.generateTranslationHTML(
  6054. "dialog.joinAgain");
  6055. var buttons = [];
  6056. buttons.push({title: button, value: true});
  6057. UI.messageHandler.openDialog(
  6058. title,
  6059. msg,
  6060. true,
  6061. buttons,
  6062. function(event, value, message, formVals) {
  6063. window.location.reload();
  6064. return false;
  6065. }
  6066. );
  6067. }
  6068. /**
  6069. * Starts or stops the recording for the conference.
  6070. */
  6071. function toggleRecording(predefinedToken) {
  6072. APP.xmpp.toggleRecording(function (callback) {
  6073. if (predefinedToken) {
  6074. callback(UIUtil.escapeHtml(predefinedToken));
  6075. return;
  6076. }
  6077. var msg = APP.translation.generateTranslationHTML(
  6078. "dialog.recordingToken");
  6079. var token = APP.translation.translateString("dialog.token");
  6080. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  6081. '<h2>' + msg + '</h2>' +
  6082. '<input name="recordingToken" type="text" ' +
  6083. ' data-i18n="[placeholder]dialog.token" ' +
  6084. 'placeholder="' + token + '" autofocus>',
  6085. false,
  6086. "dialog.Save",
  6087. function (e, v, m, f) {
  6088. if (v) {
  6089. var token = f.recordingToken;
  6090. if (token) {
  6091. callback(UIUtil.escapeHtml(token));
  6092. }
  6093. }
  6094. },
  6095. null,
  6096. function () { },
  6097. ':input:first'
  6098. );
  6099. }, Toolbar.setRecordingButtonState);
  6100. }
  6101. /**
  6102. * Locks / unlocks the room.
  6103. */
  6104. function lockRoom(lock) {
  6105. var currentSharedKey = '';
  6106. if (lock)
  6107. currentSharedKey = sharedKey;
  6108. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  6109. // password is required
  6110. if (sharedKey) {
  6111. console.log('set room password');
  6112. Toolbar.lockLockButton();
  6113. }
  6114. else {
  6115. console.log('removed room password');
  6116. Toolbar.unlockLockButton();
  6117. }
  6118. }, function (err) {
  6119. console.warn('setting password failed', err);
  6120. messageHandler.showError("dialog.lockTitle",
  6121. "dialog.lockMessage");
  6122. Toolbar.setSharedKey('');
  6123. }, function () {
  6124. console.warn('room passwords not supported');
  6125. messageHandler.showError("dialog.warning",
  6126. "dialog.passwordNotSupported");
  6127. Toolbar.setSharedKey('');
  6128. });
  6129. }
  6130. /**
  6131. * Invite participants to conference.
  6132. */
  6133. function inviteParticipants() {
  6134. if (roomUrl === null)
  6135. return;
  6136. var sharedKeyText = "";
  6137. if (sharedKey && sharedKey.length > 0) {
  6138. sharedKeyText =
  6139. APP.translation.translateString("email.sharedKey",
  6140. {sharedKey: sharedKey});
  6141. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  6142. }
  6143. var supportedBrowsers = "Chromium, Google Chrome " +
  6144. APP.translation.translateString("email.and") + " Opera";
  6145. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  6146. var subject = APP.translation.translateString("email.subject",
  6147. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  6148. var body = APP.translation.translateString("email.body",
  6149. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  6150. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  6151. body = body.replace(/\n/g, "%0D%0A");
  6152. if (window.localStorage.displayname) {
  6153. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  6154. }
  6155. if (interfaceConfig.INVITATION_POWERED_BY) {
  6156. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  6157. }
  6158. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  6159. }
  6160. function dialpadButtonClicked() {
  6161. //TODO show the dialpad box
  6162. }
  6163. function callSipButtonClicked() {
  6164. var defaultNumber
  6165. = config.defaultSipNumber ? config.defaultSipNumber : '';
  6166. var sipMsg = APP.translation.generateTranslationHTML(
  6167. "dialog.sipMsg");
  6168. messageHandler.openTwoButtonDialog(null, null, null,
  6169. '<h2>' + sipMsg + '</h2>' +
  6170. '<input name="sipNumber" type="text"' +
  6171. ' value="' + defaultNumber + '" autofocus>',
  6172. false,
  6173. "dialog.Dial",
  6174. function (e, v, m, f) {
  6175. if (v) {
  6176. var numberInput = f.sipNumber;
  6177. if (numberInput) {
  6178. APP.xmpp.dial(
  6179. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  6180. }
  6181. }
  6182. },
  6183. null, null, ':input:first'
  6184. );
  6185. }
  6186. var Toolbar = (function (my) {
  6187. my.init = function (ui) {
  6188. UIUtil.hideDisabledButtons(defaultToolbarButtons);
  6189. for(var k in buttonHandlers)
  6190. $("#" + k).click(buttonHandlers[k]);
  6191. UI = ui;
  6192. // Update login info
  6193. APP.xmpp.addListener(
  6194. AuthenticationEvents.IDENTITY_UPDATED,
  6195. function (authenticationEnabled, userIdentity) {
  6196. var loggedIn = false;
  6197. if (userIdentity) {
  6198. loggedIn = true;
  6199. }
  6200. Toolbar.showAuthenticateButton(authenticationEnabled);
  6201. if (authenticationEnabled) {
  6202. Toolbar.setAuthenticatedIdentity(userIdentity);
  6203. Toolbar.showLoginButton(!loggedIn);
  6204. Toolbar.showLogoutButton(loggedIn);
  6205. }
  6206. }
  6207. );
  6208. };
  6209. /**
  6210. * Sets shared key
  6211. * @param sKey the shared key
  6212. */
  6213. my.setSharedKey = function (sKey) {
  6214. sharedKey = sKey;
  6215. };
  6216. my.authenticateClicked = function () {
  6217. Authentication.focusAuthenticationWindow();
  6218. if (!APP.xmpp.isExternalAuthEnabled()) {
  6219. Authentication.xmppAuthenticate();
  6220. return;
  6221. }
  6222. // Get authentication URL
  6223. if (!APP.xmpp.isMUCJoined()) {
  6224. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  6225. // If conference has not been started yet - redirect to login page
  6226. window.location.href = url;
  6227. });
  6228. } else {
  6229. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  6230. // Otherwise - open popup with authentication URL
  6231. var authenticationWindow = Authentication.createAuthenticationWindow(
  6232. function () {
  6233. // On popup closed - retry room allocation
  6234. APP.xmpp.allocateConferenceFocus(
  6235. APP.UI.getRoomName(),
  6236. function () { console.info("AUTH DONE"); }
  6237. );
  6238. }, url);
  6239. if (!authenticationWindow) {
  6240. messageHandler.openMessageDialog(
  6241. null, "dialog.popupError");
  6242. }
  6243. });
  6244. }
  6245. };
  6246. /**
  6247. * Updates the room invite url.
  6248. */
  6249. my.updateRoomUrl = function (newRoomUrl) {
  6250. roomUrl = newRoomUrl;
  6251. // If the invite dialog has been already opened we update the information.
  6252. var inviteLink = document.getElementById('inviteLinkRef');
  6253. if (inviteLink) {
  6254. inviteLink.value = roomUrl;
  6255. inviteLink.select();
  6256. $('#inviteLinkRef').parent()
  6257. .find('button[value=true]').prop('disabled', false);
  6258. }
  6259. };
  6260. /**
  6261. * Disables and enables some of the buttons.
  6262. */
  6263. my.setupButtonsFromConfig = function () {
  6264. if (UIUtil.isButtonEnabled('prezi')) {
  6265. $("#toolbar_button_prezi").css({display: "none"});
  6266. }
  6267. };
  6268. /**
  6269. * Opens the lock room dialog.
  6270. */
  6271. my.openLockDialog = function () {
  6272. // Only the focus is able to set a shared key.
  6273. if (!APP.xmpp.isModerator()) {
  6274. if (sharedKey) {
  6275. messageHandler.openMessageDialog(null,
  6276. "dialog.passwordError");
  6277. } else {
  6278. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6279. }
  6280. } else {
  6281. if (sharedKey) {
  6282. messageHandler.openTwoButtonDialog(null, null,
  6283. "dialog.passwordCheck",
  6284. null,
  6285. false,
  6286. "dialog.Remove",
  6287. function (e, v) {
  6288. if (v) {
  6289. Toolbar.setSharedKey('');
  6290. lockRoom(false);
  6291. }
  6292. });
  6293. } else {
  6294. var msg = APP.translation.generateTranslationHTML(
  6295. "dialog.passwordMsg");
  6296. var yourPassword = APP.translation.translateString(
  6297. "dialog.yourPassword");
  6298. messageHandler.openTwoButtonDialog(null, null, null,
  6299. '<h2>' + msg + '</h2>' +
  6300. '<input name="lockKey" type="text"' +
  6301. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6302. 'placeholder="' + yourPassword + '" autofocus>',
  6303. false,
  6304. "dialog.Save",
  6305. function (e, v, m, f) {
  6306. if (v) {
  6307. var lockKey = f.lockKey;
  6308. if (lockKey) {
  6309. Toolbar.setSharedKey(
  6310. UIUtil.escapeHtml(lockKey));
  6311. lockRoom(true);
  6312. }
  6313. }
  6314. },
  6315. null, null, 'input:first'
  6316. );
  6317. }
  6318. }
  6319. };
  6320. /**
  6321. * Opens the invite link dialog.
  6322. */
  6323. my.openLinkDialog = function () {
  6324. var inviteAttreibutes;
  6325. if (roomUrl === null) {
  6326. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6327. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6328. } else {
  6329. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6330. }
  6331. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6332. null, null,
  6333. '<input id="inviteLinkRef" type="text" ' +
  6334. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6335. false,
  6336. "dialog.Invite",
  6337. function (e, v) {
  6338. if (v) {
  6339. if (roomUrl) {
  6340. inviteParticipants();
  6341. }
  6342. }
  6343. },
  6344. function (event) {
  6345. if (roomUrl) {
  6346. document.getElementById('inviteLinkRef').select();
  6347. } else {
  6348. if (event && event.target)
  6349. $(event.target)
  6350. .find('button[value=true]').prop('disabled', true);
  6351. }
  6352. }
  6353. );
  6354. };
  6355. /**
  6356. * Opens the settings dialog.
  6357. * FIXME: not used ?
  6358. */
  6359. my.openSettingsDialog = function () {
  6360. var settings1 = APP.translation.generateTranslationHTML(
  6361. "dialog.settings1");
  6362. var settings2 = APP.translation.generateTranslationHTML(
  6363. "dialog.settings2");
  6364. var settings3 = APP.translation.generateTranslationHTML(
  6365. "dialog.settings3");
  6366. var yourPassword = APP.translation.translateString(
  6367. "dialog.yourPassword");
  6368. messageHandler.openTwoButtonDialog(null,
  6369. '<h2>' + settings1 + '</h2>' +
  6370. '<input type="checkbox" id="initMuted">' +
  6371. settings2 + '<br/>' +
  6372. '<input type="checkbox" id="requireNicknames">' +
  6373. settings3 +
  6374. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6375. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6376. null,
  6377. null,
  6378. false,
  6379. "dialog.Save",
  6380. function () {
  6381. document.getElementById('lockKey').focus();
  6382. },
  6383. function (e, v) {
  6384. if (v) {
  6385. if ($('#initMuted').is(":checked")) {
  6386. // it is checked
  6387. }
  6388. if ($('#requireNicknames').is(":checked")) {
  6389. // it is checked
  6390. }
  6391. /*
  6392. var lockKey = document.getElementById('lockKey');
  6393. if (lockKey.value) {
  6394. setSharedKey(lockKey.value);
  6395. lockRoom(true);
  6396. }
  6397. */
  6398. }
  6399. }
  6400. );
  6401. };
  6402. /**
  6403. * Toggles the application in and out of full screen mode
  6404. * (a.k.a. presentation mode in Chrome).
  6405. */
  6406. my.toggleFullScreen = function () {
  6407. var fsElement = document.documentElement;
  6408. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6409. //Enter Full Screen
  6410. if (fsElement.mozRequestFullScreen) {
  6411. fsElement.mozRequestFullScreen();
  6412. }
  6413. else {
  6414. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6415. }
  6416. } else {
  6417. //Exit Full Screen
  6418. if (document.mozCancelFullScreen) {
  6419. document.mozCancelFullScreen();
  6420. } else {
  6421. document.webkitCancelFullScreen();
  6422. }
  6423. }
  6424. };
  6425. /**
  6426. * Unlocks the lock button state.
  6427. */
  6428. my.unlockLockButton = function () {
  6429. if ($("#toolbar_button_security").hasClass("icon-security-locked"))
  6430. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6431. };
  6432. /**
  6433. * Updates the lock button state to locked.
  6434. */
  6435. my.lockLockButton = function () {
  6436. if ($("#toolbar_button_security").hasClass("icon-security"))
  6437. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6438. };
  6439. /**
  6440. * Shows or hides authentication button
  6441. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6442. */
  6443. my.showAuthenticateButton = function (show) {
  6444. if (UIUtil.isButtonEnabled('authentication') && show) {
  6445. $('#authentication').css({display: "inline"});
  6446. }
  6447. else {
  6448. $('#authentication').css({display: "none"});
  6449. }
  6450. };
  6451. // Shows or hides the 'recording' button.
  6452. my.showRecordingButton = function (show) {
  6453. if (UIUtil.isButtonEnabled('recording') && show) {
  6454. $('#toolbar_button_record').css({display: "inline-block"});
  6455. }
  6456. else {
  6457. $('#toolbar_button_record').css({display: "none"});
  6458. }
  6459. };
  6460. // Sets the state of the recording button
  6461. my.setRecordingButtonState = function (recordingState) {
  6462. var selector = $('#toolbar_button_record');
  6463. if (recordingState === 'on') {
  6464. selector.removeClass("icon-recEnable");
  6465. selector.addClass("icon-recEnable active");
  6466. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6467. var recordOnKey = "recording.on";
  6468. $('#videoConnectionMessage').attr("data-i18n", recordOnKey);
  6469. $('#videoConnectionMessage').text(APP.translation.translateString(recordOnKey));
  6470. setTimeout(function(){
  6471. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6472. $('#videoConnectionMessage').css({display: "none"});
  6473. }, 1500);
  6474. recordingToaster = messageHandler.notify(null, "recording.toaster", null,
  6475. null, null, {timeOut: 0, closeButton: null, tapToDismiss: false});
  6476. } else if (recordingState === 'off') {
  6477. selector.removeClass("icon-recEnable active");
  6478. selector.addClass("icon-recEnable");
  6479. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6480. $('#videoConnectionMessage').css({display: "none"});
  6481. if (recordingToaster)
  6482. messageHandler.remove(recordingToaster);
  6483. } else if (recordingState === 'pending') {
  6484. selector.removeClass("icon-recEnable active");
  6485. selector.addClass("icon-recEnable");
  6486. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6487. var recordPendingKey = "recording.pending";
  6488. $('#videoConnectionMessage').attr("data-i18n", recordPendingKey);
  6489. $('#videoConnectionMessage').text(APP.translation.translateString(recordPendingKey));
  6490. $('#videoConnectionMessage').css({display: "block"});
  6491. }
  6492. };
  6493. // checks whether recording is enabled and whether we have params to start automatically recording
  6494. my.checkAutoRecord = function () {
  6495. if (UIUtil.isButtonEnabled('recording') && config.autoRecord) {
  6496. toggleRecording(config.autoRecordToken);
  6497. }
  6498. }
  6499. // Shows or hides SIP calls button
  6500. my.showSipCallButton = function (show) {
  6501. if (APP.xmpp.isSipGatewayEnabled() && UIUtil.isButtonEnabled('sip') && show) {
  6502. $('#toolbar_button_sip').css({display: "inline-block"});
  6503. } else {
  6504. $('#toolbar_button_sip').css({display: "none"});
  6505. }
  6506. };
  6507. // Shows or hides the dialpad button
  6508. my.showDialPadButton = function (show) {
  6509. if (UIUtil.isButtonEnabled('dialpad') && show) {
  6510. $('#toolbar_button_dialpad').css({display: "inline-block"});
  6511. } else {
  6512. $('#toolbar_button_dialpad').css({display: "none"});
  6513. }
  6514. };
  6515. /**
  6516. * Displays user authenticated identity name(login).
  6517. * @param authIdentity identity name to be displayed.
  6518. */
  6519. my.setAuthenticatedIdentity = function (authIdentity) {
  6520. if (authIdentity) {
  6521. var selector = $('#toolbar_auth_identity');
  6522. selector.css({display: "list-item"});
  6523. selector.text(authIdentity);
  6524. } else {
  6525. $('#toolbar_auth_identity').css({display: "none"});
  6526. }
  6527. };
  6528. /**
  6529. * Shows/hides login button.
  6530. * @param show <tt>true</tt> to show
  6531. */
  6532. my.showLoginButton = function (show) {
  6533. if (UIUtil.isButtonEnabled('authentication') && show) {
  6534. $('#toolbar_button_login').css({display: "list-item"});
  6535. } else {
  6536. $('#toolbar_button_login').css({display: "none"});
  6537. }
  6538. };
  6539. /**
  6540. * Shows/hides logout button.
  6541. * @param show <tt>true</tt> to show
  6542. */
  6543. my.showLogoutButton = function (show) {
  6544. if (UIUtil.isButtonEnabled('authentication') && show) {
  6545. $('#toolbar_button_logout').css({display: "list-item"});
  6546. } else {
  6547. $('#toolbar_button_logout').css({display: "none"});
  6548. }
  6549. };
  6550. /**
  6551. * Sets the state of the button. The button has blue glow if desktop
  6552. * streaming is active.
  6553. * @param active the state of the desktop streaming.
  6554. */
  6555. my.changeDesktopSharingButtonState = function (active) {
  6556. var button = $("#toolbar_button_desktopsharing");
  6557. if (active) {
  6558. button.addClass("glow");
  6559. } else {
  6560. button.removeClass("glow");
  6561. }
  6562. };
  6563. return my;
  6564. }(Toolbar || {}));
  6565. module.exports = Toolbar;
  6566. },{"../../../service/authentication/AuthenticationEvents":169,"../authentication/Authentication":16,"../etherpad/Etherpad":19,"../prezi/Prezi":20,"../side_pannels/SidePanelToggler":22,"../util/MessageHandler":33,"../util/UIUtil":35,"./BottomToolbar":29}],31:[function(require,module,exports){
  6567. /* global APP, config, $, interfaceConfig, Moderator,
  6568. DesktopStreaming.showDesktopSharingButton */
  6569. var toolbarTimeoutObject,
  6570. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT,
  6571. UIUtil = require("../util/UIUtil");
  6572. function showDesktopSharingButton() {
  6573. if (APP.desktopsharing.isDesktopSharingEnabled() && UIUtil.isButtonEnabled('desktop')) {
  6574. $('#toolbar_button_desktopsharing').css({display: "inline-block"});
  6575. } else {
  6576. $('#toolbar_button_desktopsharing').css({display: "none"});
  6577. }
  6578. }
  6579. /**
  6580. * Hides the toolbar.
  6581. */
  6582. function hideToolbar() {
  6583. if(config.alwaysVisibleToolbar)
  6584. return;
  6585. var header = $("#header"),
  6586. bottomToolbar = $("#bottomToolbar");
  6587. var isToolbarHover = false;
  6588. header.find('*').each(function () {
  6589. var id = $(this).attr('id');
  6590. if ($("#" + id + ":hover").length > 0) {
  6591. isToolbarHover = true;
  6592. }
  6593. });
  6594. if ($("#bottomToolbar:hover").length > 0) {
  6595. isToolbarHover = true;
  6596. }
  6597. clearTimeout(toolbarTimeoutObject);
  6598. toolbarTimeoutObject = null;
  6599. if (!isToolbarHover) {
  6600. header.hide("slide", { direction: "up", duration: 300});
  6601. $('#subject').animate({top: "-=40"}, 300);
  6602. if ($("#remoteVideos").hasClass("hidden")) {
  6603. bottomToolbar.hide(
  6604. "slide", {direction: "right", duration: 300});
  6605. }
  6606. }
  6607. else {
  6608. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6609. }
  6610. }
  6611. var ToolbarToggler = {
  6612. /**
  6613. * Shows the main toolbar.
  6614. */
  6615. showToolbar: function () {
  6616. if (interfaceConfig.filmStripOnly)
  6617. return;
  6618. var header = $("#header"),
  6619. bottomToolbar = $("#bottomToolbar");
  6620. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6621. header.show("slide", { direction: "up", duration: 300});
  6622. $('#subject').animate({top: "+=40"}, 300);
  6623. if (!bottomToolbar.is(":visible")) {
  6624. bottomToolbar.show(
  6625. "slide", {direction: "right", duration: 300});
  6626. }
  6627. if (toolbarTimeoutObject) {
  6628. clearTimeout(toolbarTimeoutObject);
  6629. toolbarTimeoutObject = null;
  6630. }
  6631. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6632. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6633. }
  6634. if (APP.xmpp.isModerator())
  6635. {
  6636. // TODO: Enable settings functionality.
  6637. // Need to uncomment the settings button in index.html.
  6638. // $('#settingsButton').css({visibility:"visible"});
  6639. }
  6640. // Show/hide desktop sharing button
  6641. showDesktopSharingButton();
  6642. },
  6643. /**
  6644. * Docks/undocks the toolbar.
  6645. *
  6646. * @param isDock indicates what operation to perform
  6647. */
  6648. dockToolbar: function (isDock) {
  6649. if (interfaceConfig.filmStripOnly)
  6650. return;
  6651. if (isDock) {
  6652. // First make sure the toolbar is shown.
  6653. if (!$('#header').is(':visible')) {
  6654. this.showToolbar();
  6655. }
  6656. // Then clear the time out, to dock the toolbar.
  6657. if (toolbarTimeoutObject) {
  6658. clearTimeout(toolbarTimeoutObject);
  6659. toolbarTimeoutObject = null;
  6660. }
  6661. }
  6662. else {
  6663. if (!$('#header').is(':visible')) {
  6664. this.showToolbar();
  6665. }
  6666. else {
  6667. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6668. }
  6669. }
  6670. },
  6671. showDesktopSharingButton: showDesktopSharingButton
  6672. };
  6673. module.exports = ToolbarToggler;
  6674. },{"../util/UIUtil":35}],32:[function(require,module,exports){
  6675. /* global $ */
  6676. var JitsiPopover = (function () {
  6677. /**
  6678. * Constructs new JitsiPopover and attaches it to the element
  6679. * @param element jquery selector
  6680. * @param options the options for the popover.
  6681. * @constructor
  6682. */
  6683. function JitsiPopover(element, options)
  6684. {
  6685. this.options = {
  6686. skin: "white",
  6687. content: ""
  6688. };
  6689. if(options)
  6690. {
  6691. if(options.skin)
  6692. this.options.skin = options.skin;
  6693. if(options.content)
  6694. this.options.content = options.content;
  6695. }
  6696. this.elementIsHovered = false;
  6697. this.popoverIsHovered = false;
  6698. this.popoverShown = false;
  6699. element.data("jitsi_popover", this);
  6700. this.element = element;
  6701. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6702. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6703. '<div class="jitsiPopupmenuPadding"></div></div>';
  6704. var self = this;
  6705. this.element.on("mouseenter", function () {
  6706. self.elementIsHovered = true;
  6707. self.show();
  6708. }).on("mouseleave", function () {
  6709. self.elementIsHovered = false;
  6710. setTimeout(function () {
  6711. self.hide();
  6712. }, 10);
  6713. });
  6714. }
  6715. /**
  6716. * Shows the popover
  6717. */
  6718. JitsiPopover.prototype.show = function () {
  6719. if(!JitsiPopover.enabled)
  6720. return;
  6721. this.createPopover();
  6722. this.popoverShown = true;
  6723. };
  6724. /**
  6725. * Hides the popover
  6726. */
  6727. JitsiPopover.prototype.hide = function () {
  6728. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6729. this.popoverShown) {
  6730. this.forceHide();
  6731. }
  6732. };
  6733. /**
  6734. * Hides the popover.
  6735. */
  6736. JitsiPopover.prototype.forceHide = function () {
  6737. $(".jitsipopover").remove();
  6738. this.popoverShown = false;
  6739. };
  6740. /**
  6741. * Creates the popover html.
  6742. */
  6743. JitsiPopover.prototype.createPopover = function () {
  6744. $("body").append(this.template);
  6745. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6746. var self = this;
  6747. $(".jitsipopover").on("mouseenter", function () {
  6748. self.popoverIsHovered = true;
  6749. }).on("mouseleave", function () {
  6750. self.popoverIsHovered = false;
  6751. self.hide();
  6752. });
  6753. this.refreshPosition();
  6754. };
  6755. /**
  6756. * Refreshes the position of the popover.
  6757. */
  6758. JitsiPopover.prototype.refreshPosition = function () {
  6759. $(".jitsipopover").position({
  6760. my: "bottom",
  6761. at: "top",
  6762. collision: "fit",
  6763. of: this.element,
  6764. using: function (position, elements) {
  6765. var calcLeft = elements.target.left - elements.element.left +
  6766. elements.target.width/2;
  6767. $(".jitsipopover").css(
  6768. {top: position.top, left: position.left, display: "table"});
  6769. $(".jitsipopover > .arrow").css({left: calcLeft});
  6770. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6771. {left: calcLeft - 50});
  6772. }
  6773. });
  6774. };
  6775. /**
  6776. * Updates the content of popover.
  6777. * @param content new content
  6778. */
  6779. JitsiPopover.prototype.updateContent = function (content) {
  6780. this.options.content = content;
  6781. if(!this.popoverShown)
  6782. return;
  6783. $(".jitsipopover").remove();
  6784. this.createPopover();
  6785. };
  6786. JitsiPopover.enabled = true;
  6787. return JitsiPopover;
  6788. })();
  6789. module.exports = JitsiPopover;
  6790. },{}],33:[function(require,module,exports){
  6791. /* global $, APP, jQuery, toastr */
  6792. /**
  6793. * Flag for enable/disable of the notifications.
  6794. * @type {boolean}
  6795. */
  6796. var notificationsEnabled = true;
  6797. var messageHandler = (function(my) {
  6798. /**
  6799. * Shows a message to the user.
  6800. *
  6801. * @param titleKey the title of the message
  6802. * @param messageKey the text of the message
  6803. */
  6804. my.openMessageDialog = function(titleKey, messageKey) {
  6805. var title = null;
  6806. if(titleKey) {
  6807. title = APP.translation.generateTranslationHTML(titleKey);
  6808. }
  6809. var message = APP.translation.generateTranslationHTML(messageKey);
  6810. $.prompt(message,
  6811. {title: title, persistent: false}
  6812. );
  6813. };
  6814. /**
  6815. * Shows a message to the user with two buttons: first is given as a
  6816. * parameter and the second is Cancel.
  6817. *
  6818. * @param titleString the title of the message
  6819. * @param msgString the text of the message
  6820. * @param persistent boolean value which determines whether the message is
  6821. * persistent or not
  6822. * @param leftButton the fist button's text
  6823. * @param submitFunction function to be called on submit
  6824. * @param loadedFunction function to be called after the prompt is fully
  6825. * loaded
  6826. * @param closeFunction function to be called after the prompt is closed
  6827. * @param focus optional focus selector or button index to be focused after
  6828. * the dialog is opened
  6829. * @param defaultButton index of default button which will be activated when
  6830. * the user press 'enter'. Indexed from 0.
  6831. */
  6832. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6833. persistent, leftButtonKey, submitFunction, loadedFunction,
  6834. closeFunction, focus, defaultButton) {
  6835. var buttons = [];
  6836. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6837. buttons.push({ title: leftButton, value: true});
  6838. var cancelButton
  6839. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6840. buttons.push({title: cancelButton, value: false});
  6841. var message = msgString, title = titleString;
  6842. if (titleKey) {
  6843. title = APP.translation.generateTranslationHTML(titleKey);
  6844. }
  6845. if (msgKey) {
  6846. message = APP.translation.generateTranslationHTML(msgKey);
  6847. }
  6848. $.prompt(message, {
  6849. title: title,
  6850. persistent: false,
  6851. buttons: buttons,
  6852. defaultButton: defaultButton,
  6853. focus: focus,
  6854. loaded: loadedFunction,
  6855. submit: submitFunction,
  6856. close: closeFunction
  6857. });
  6858. };
  6859. /**
  6860. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6861. *
  6862. * @param titleString the title of the message
  6863. * @param msgString the text of the message
  6864. * @param persistent boolean value which determines whether the message is
  6865. * persistent or not
  6866. * @param buttons object with the buttons. The keys must be the name of the
  6867. * button and value is the value that will be passed to
  6868. * submitFunction
  6869. * @param submitFunction function to be called on submit
  6870. * @param loadedFunction function to be called after the prompt is fully
  6871. * loaded
  6872. */
  6873. my.openDialog = function (titleString, msgString, persistent, buttons,
  6874. submitFunction, loadedFunction) {
  6875. var args = {
  6876. title: titleString,
  6877. persistent: persistent,
  6878. buttons: buttons,
  6879. defaultButton: 1,
  6880. loaded: loadedFunction,
  6881. submit: submitFunction
  6882. };
  6883. if (persistent) {
  6884. args.closeText = '';
  6885. }
  6886. return new Impromptu(msgString, args);
  6887. };
  6888. /**
  6889. * Closes currently opened dialog.
  6890. */
  6891. my.closeDialog = function () {
  6892. $.prompt.close();
  6893. };
  6894. /**
  6895. * Shows a dialog with different states to the user.
  6896. *
  6897. * @param statesObject object containing all the states of the dialog.
  6898. */
  6899. my.openDialogWithStates = function (statesObject, options) {
  6900. return new Impromptu(statesObject, options);
  6901. };
  6902. /**
  6903. * Opens new popup window for given <tt>url</tt> centered over current
  6904. * window.
  6905. *
  6906. * @param url the URL to be displayed in the popup window
  6907. * @param w the width of the popup window
  6908. * @param h the height of the popup window
  6909. * @param onPopupClosed optional callback function called when popup window
  6910. * has been closed.
  6911. *
  6912. * @returns {object} popup window object if opened successfully or undefined
  6913. * in case we failed to open it(popup blocked)
  6914. */
  6915. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6916. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6917. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6918. var popup = window.open(
  6919. url, '_blank',
  6920. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6921. if (popup && onPopupClosed) {
  6922. var pollTimer = window.setInterval(function () {
  6923. if (popup.closed !== false) {
  6924. window.clearInterval(pollTimer);
  6925. onPopupClosed();
  6926. }
  6927. }, 200);
  6928. }
  6929. return popup;
  6930. };
  6931. /**
  6932. * Shows a dialog prompting the user to send an error report.
  6933. *
  6934. * @param titleKey the title of the message
  6935. * @param msgKey the text of the message
  6936. * @param error the error that is being reported
  6937. */
  6938. my.openReportDialog = function(titleKey, msgKey, error) {
  6939. my.openMessageDialog(titleKey, msgKey);
  6940. console.log(error);
  6941. //FIXME send the error to the server
  6942. };
  6943. /**
  6944. * Shows an error dialog to the user.
  6945. * @param titleKey the title of the message.
  6946. * @param msgKey the text of the message.
  6947. */
  6948. my.showError = function(titleKey, msgKey) {
  6949. if (!titleKey) {
  6950. titleKey = "dialog.oops";
  6951. }
  6952. if (!msgKey) {
  6953. msgKey = "dialog.defaultError";
  6954. }
  6955. messageHandler.openMessageDialog(titleKey, msgKey);
  6956. };
  6957. /**
  6958. * Displayes notification.
  6959. * @param displayName display name of the participant that is associated with the notification.
  6960. * @param displayNameKey the key from the language file for the display name.
  6961. * @param cls css class for the notification
  6962. * @param messageKey the key from the language file for the text of the message.
  6963. * @param messageArguments object with the arguments for the message.
  6964. * @param options object with language options.
  6965. */
  6966. my.notify = function(displayName, displayNameKey,
  6967. cls, messageKey, messageArguments, options) {
  6968. if(!notificationsEnabled)
  6969. return;
  6970. var displayNameSpan = '<span class="nickname" ';
  6971. if (displayName) {
  6972. displayNameSpan += ">" + displayName;
  6973. } else {
  6974. displayNameSpan += "data-i18n='" + displayNameKey +
  6975. "'>" + APP.translation.translateString(displayNameKey);
  6976. }
  6977. displayNameSpan += "</span>";
  6978. return toastr.info(
  6979. displayNameSpan + '<br>' +
  6980. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6981. (messageArguments?
  6982. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6983. : "") + ">" +
  6984. APP.translation.translateString(messageKey,
  6985. messageArguments) +
  6986. '</span>', null, options);
  6987. };
  6988. /**
  6989. * Removes the toaster.
  6990. * @param toasterElement
  6991. */
  6992. my.remove = function(toasterElement) {
  6993. toasterElement.remove();
  6994. };
  6995. /**
  6996. * Disables notifications.
  6997. */
  6998. my.disableNotifications = function () {
  6999. notificationsEnabled = false;
  7000. };
  7001. /**
  7002. * Enables notifications.
  7003. */
  7004. my.enableNotifications = function () {
  7005. notificationsEnabled = true;
  7006. };
  7007. return my;
  7008. }(messageHandler || {}));
  7009. module.exports = messageHandler;
  7010. },{}],34:[function(require,module,exports){
  7011. var UIEvents = require("../../../service/UI/UIEvents");
  7012. var nickname = null;
  7013. var eventEmitter = null;
  7014. var NicknameHandler = {
  7015. init: function (emitter) {
  7016. eventEmitter = emitter;
  7017. var storedDisplayName = window.localStorage.displayname;
  7018. if (storedDisplayName) {
  7019. nickname = storedDisplayName;
  7020. }
  7021. },
  7022. setNickname: function (newNickname) {
  7023. if (!newNickname || nickname === newNickname)
  7024. return;
  7025. nickname = newNickname;
  7026. window.localStorage.displayname = nickname;
  7027. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  7028. },
  7029. getNickname: function () {
  7030. return nickname;
  7031. },
  7032. addListener: function (type, listener) {
  7033. eventEmitter.on(type, listener);
  7034. }
  7035. };
  7036. module.exports = NicknameHandler;
  7037. },{"../../../service/UI/UIEvents":168}],35:[function(require,module,exports){
  7038. /* global $, config, interfaceConfig */
  7039. /**
  7040. * Created by hristo on 12/22/14.
  7041. */
  7042. var UIUtil = module.exports = {
  7043. /**
  7044. * Returns the available video width.
  7045. */
  7046. getAvailableVideoWidth: function (isVisible) {
  7047. var PanelToggler = require("../side_pannels/SidePanelToggler");
  7048. if(typeof isVisible === "undefined" || isVisible === null)
  7049. isVisible = PanelToggler.isVisible();
  7050. var rightPanelWidth
  7051. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  7052. return window.innerWidth - rightPanelWidth;
  7053. },
  7054. /**
  7055. * Changes the style class of the element given by id.
  7056. */
  7057. buttonClick: function(id, classname) {
  7058. $(id).toggleClass(classname); // add the class to the clicked element
  7059. },
  7060. /**
  7061. * Returns the text width for the given element.
  7062. *
  7063. * @param el the element
  7064. */
  7065. getTextWidth: function (el) {
  7066. return (el.clientWidth + 1);
  7067. },
  7068. /**
  7069. * Returns the text height for the given element.
  7070. *
  7071. * @param el the element
  7072. */
  7073. getTextHeight: function (el) {
  7074. return (el.clientHeight + 1);
  7075. },
  7076. /**
  7077. * Plays the sound given by id.
  7078. *
  7079. * @param id the identifier of the audio element.
  7080. */
  7081. playSoundNotification: function (id) {
  7082. document.getElementById(id).play();
  7083. },
  7084. /**
  7085. * Escapes the given text.
  7086. */
  7087. escapeHtml: function (unsafeText) {
  7088. return $('<div/>').text(unsafeText).html();
  7089. },
  7090. imageToGrayScale: function (canvas) {
  7091. var context = canvas.getContext('2d');
  7092. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  7093. var pixels = imgData.data;
  7094. for (var i = 0, n = pixels.length; i < n; i += 4) {
  7095. var grayscale
  7096. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  7097. pixels[i ] = grayscale; // red
  7098. pixels[i+1] = grayscale; // green
  7099. pixels[i+2] = grayscale; // blue
  7100. // pixels[i+3] is alpha
  7101. }
  7102. // redraw the image in black & white
  7103. context.putImageData(imgData, 0, 0);
  7104. },
  7105. setTooltip: function (element, key, position) {
  7106. element.setAttribute("data-i18n", "[data-content]" + key);
  7107. element.setAttribute("data-toggle", "popover");
  7108. element.setAttribute("data-placement", position);
  7109. element.setAttribute("data-html", true);
  7110. element.setAttribute("data-container", "body");
  7111. },
  7112. /**
  7113. * Inserts given child element as the first one into the container.
  7114. * @param container the container to which new child element will be added
  7115. * @param newChild the new element that will be inserted into the container
  7116. */
  7117. prependChild: function (container, newChild) {
  7118. var firstChild = container.childNodes[0];
  7119. if (firstChild) {
  7120. container.insertBefore(newChild, firstChild);
  7121. } else {
  7122. container.appendChild(newChild);
  7123. }
  7124. },
  7125. isButtonEnabled: function (name) {
  7126. var isEnabled = interfaceConfig.TOOLBAR_BUTTONS.indexOf(name) !== -1;
  7127. if (name === 'prezi') {
  7128. return isEnabled && !config.disablePrezi;
  7129. } else if (name === 'recording') {
  7130. return isEnabled && config.enableRecording;
  7131. }
  7132. return isEnabled;
  7133. },
  7134. hideDisabledButtons: function (mappings) {
  7135. var selector = Object.keys(mappings)
  7136. .map(function (buttonName) { return UIUtil.isButtonEnabled(buttonName) ? null : mappings[buttonName]; })
  7137. .filter(function (item) { return item; })
  7138. .join(',');
  7139. $(selector).hide();
  7140. }
  7141. };
  7142. },{"../side_pannels/SidePanelToggler":22}],36:[function(require,module,exports){
  7143. /* global APP, $ */
  7144. var JitsiPopover = require("../util/JitsiPopover");
  7145. /**
  7146. * Constructs new connection indicator.
  7147. * @param videoContainer the video container associated with the indicator.
  7148. * @constructor
  7149. */
  7150. function ConnectionIndicator(videoContainer, jid) {
  7151. this.videoContainer = videoContainer;
  7152. this.bandwidth = null;
  7153. this.packetLoss = null;
  7154. this.bitrate = null;
  7155. this.showMoreValue = false;
  7156. this.resolution = null;
  7157. this.transport = [];
  7158. this.popover = null;
  7159. this.jid = jid;
  7160. this.create();
  7161. }
  7162. /**
  7163. * Values for the connection quality
  7164. * @type {{98: string,
  7165. * 81: string,
  7166. * 64: string,
  7167. * 47: string,
  7168. * 30: string,
  7169. * 0: string}}
  7170. */
  7171. ConnectionIndicator.connectionQualityValues = {
  7172. 98: "18px", //full
  7173. 81: "15px",//4 bars
  7174. 64: "11px",//3 bars
  7175. 47: "7px",//2 bars
  7176. 30: "3px",//1 bar
  7177. 0: "0px"//empty
  7178. };
  7179. ConnectionIndicator.getIP = function(value) {
  7180. return value.substring(0, value.lastIndexOf(":"));
  7181. };
  7182. ConnectionIndicator.getPort = function(value) {
  7183. return value.substring(value.lastIndexOf(":") + 1, value.length);
  7184. };
  7185. ConnectionIndicator.getStringFromArray = function (array) {
  7186. var res = "";
  7187. for(var i = 0; i < array.length; i++) {
  7188. res += (i === 0? "" : ", ") + array[i];
  7189. }
  7190. return res;
  7191. };
  7192. /**
  7193. * Generates the html content.
  7194. * @returns {string} the html content.
  7195. */
  7196. ConnectionIndicator.prototype.generateText = function () {
  7197. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  7198. var translate = APP.translation.translateString;
  7199. if(this.bitrate === null) {
  7200. downloadBitrate = "N/A";
  7201. uploadBitrate = "N/A";
  7202. }
  7203. else {
  7204. downloadBitrate =
  7205. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  7206. uploadBitrate =
  7207. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  7208. }
  7209. if(this.packetLoss === null) {
  7210. packetLoss = "N/A";
  7211. } else {
  7212. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  7213. (this.packetLoss.download !== null ?
  7214. this.packetLoss.download : "N/A") +
  7215. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  7216. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  7217. "%";
  7218. }
  7219. var resolutionValue = null;
  7220. if(this.resolution && this.jid != null) {
  7221. var keys = Object.keys(this.resolution);
  7222. for(var ssrc in this.resolution) {
  7223. resolutionValue = this.resolution[ssrc];
  7224. }
  7225. }
  7226. if(this.jid === null) {
  7227. resolution = "";
  7228. if(this.resolution === null || !Object.keys(this.resolution) ||
  7229. Object.keys(this.resolution).length === 0) {
  7230. resolution = "N/A";
  7231. } else {
  7232. for (i in this.resolution) {
  7233. resolutionValue = this.resolution[i];
  7234. if (resolutionValue) {
  7235. if (resolutionValue.height &&
  7236. resolutionValue.width) {
  7237. resolution += (resolution === "" ? "" : ", ") +
  7238. resolutionValue.width + "x" +
  7239. resolutionValue.height;
  7240. }
  7241. }
  7242. }
  7243. }
  7244. } else if(!resolutionValue ||
  7245. !resolutionValue.height ||
  7246. !resolutionValue.width) {
  7247. resolution = "N/A";
  7248. } else {
  7249. resolution = resolutionValue.width + "x" + resolutionValue.height;
  7250. }
  7251. var result = "<table style='width:100%'>" +
  7252. "<tr>" +
  7253. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  7254. translate("connectionindicator.bitrate") + "</span></td>" +
  7255. "<td><span class='jitsipopover_green'>&darr;</span>" +
  7256. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  7257. uploadBitrate + "</td>" +
  7258. "</tr><tr>" +
  7259. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  7260. translate("connectionindicator.packetloss") + "</span></td>" +
  7261. "<td>" + packetLoss + "</td>" +
  7262. "</tr><tr>" +
  7263. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  7264. translate("connectionindicator.resolution") + "</span></td>" +
  7265. "<td>" + resolution + "</td></tr></table>";
  7266. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  7267. result += "<div class=\"jitsipopover_showmore\" " +
  7268. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  7269. // FIXME: we do not know local jid when this text is generated
  7270. //this.jid + "')\" data-i18n='connectionindicator." +
  7271. "local')\" data-i18n='connectionindicator." +
  7272. (this.showMoreValue ? "less" : "more") + "'>" +
  7273. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  7274. "</div><br />";
  7275. }
  7276. if (this.showMoreValue) {
  7277. var downloadBandwidth, uploadBandwidth, transport;
  7278. if (this.bandwidth === null) {
  7279. downloadBandwidth = "N/A";
  7280. uploadBandwidth = "N/A";
  7281. } else {
  7282. downloadBandwidth = this.bandwidth.download?
  7283. this.bandwidth.download + " Kbps" :
  7284. "N/A";
  7285. uploadBandwidth = this.bandwidth.upload?
  7286. this.bandwidth.upload + " Kbps" :
  7287. "N/A";
  7288. }
  7289. if (!this.transport || this.transport.length === 0) {
  7290. transport = "<tr>" +
  7291. "<td><span class='jitsipopover_blue' " +
  7292. "data-i18n='connectionindicator.address'>" +
  7293. translate("connectionindicator.address") + "</span></td>" +
  7294. "<td> N/A</td></tr>";
  7295. } else {
  7296. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7297. for(i = 0; i < this.transport.length; i++) {
  7298. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7299. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7300. var localIP =
  7301. ConnectionIndicator.getIP(this.transport[i].localip);
  7302. var localPort =
  7303. ConnectionIndicator.getPort(this.transport[i].localip);
  7304. if(data.remoteIP.indexOf(ip) == -1) {
  7305. data.remoteIP.push(ip);
  7306. }
  7307. if(data.remotePort.indexOf(port) == -1) {
  7308. data.remotePort.push(port);
  7309. }
  7310. if(data.localIP.indexOf(localIP) == -1) {
  7311. data.localIP.push(localIP);
  7312. }
  7313. if(data.localPort.indexOf(localPort) == -1) {
  7314. data.localPort.push(localPort);
  7315. }
  7316. }
  7317. var local_address_key = "connectionindicator.localaddress";
  7318. var remote_address_key = "connectionindicator.remoteaddress";
  7319. var localTransport =
  7320. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7321. local_address_key +"' data-i18n-options='" +
  7322. JSON.stringify({count: data.localIP.length}) + "'>" +
  7323. translate(local_address_key, {count: data.localIP.length}) +
  7324. "</span></td><td> " +
  7325. ConnectionIndicator.getStringFromArray(data.localIP) +
  7326. "</td></tr>";
  7327. transport =
  7328. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7329. remote_address_key + "' data-i18n-options='" +
  7330. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7331. translate(remote_address_key,
  7332. {count: data.remoteIP.length}) +
  7333. "</span></td><td> " +
  7334. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7335. "</td></tr>";
  7336. var key_remote = "connectionindicator.remoteport",
  7337. key_local = "connectionindicator.localport";
  7338. transport += "<tr>" +
  7339. "<td>" +
  7340. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7341. "' data-i18n-options='" +
  7342. JSON.stringify({count: this.transport.length}) + "'>" +
  7343. translate(key_remote, {count: this.transport.length}) +
  7344. "</span></td><td>";
  7345. localTransport += "<tr>" +
  7346. "<td>" +
  7347. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7348. "' data-i18n-options='" +
  7349. JSON.stringify({count: this.transport.length}) + "'>" +
  7350. translate(key_local, {count: this.transport.length}) +
  7351. "</span></td><td>";
  7352. transport +=
  7353. ConnectionIndicator.getStringFromArray(data.remotePort);
  7354. localTransport +=
  7355. ConnectionIndicator.getStringFromArray(data.localPort);
  7356. transport += "</td></tr>";
  7357. transport += localTransport + "</td></tr>";
  7358. transport +="<tr>" +
  7359. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7360. translate("connectionindicator.transport") + "</span></td>" +
  7361. "<td>" + this.transport[0].type + "</td></tr>";
  7362. }
  7363. result += "<table style='width:100%'>" +
  7364. "<tr>" +
  7365. "<td>" +
  7366. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7367. translate("connectionindicator.bandwidth") + "</span>" +
  7368. "</td><td>" +
  7369. "<span class='jitsipopover_green'>&darr;</span>" +
  7370. downloadBandwidth +
  7371. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7372. uploadBandwidth + "</td></tr>";
  7373. result += transport + "</table>";
  7374. }
  7375. return result;
  7376. };
  7377. /**
  7378. * Shows or hide the additional information.
  7379. */
  7380. ConnectionIndicator.prototype.showMore = function () {
  7381. this.showMoreValue = !this.showMoreValue;
  7382. this.updatePopoverData();
  7383. };
  7384. function createIcon(classes) {
  7385. var icon = document.createElement("span");
  7386. for(var i in classes) {
  7387. icon.classList.add(classes[i]);
  7388. }
  7389. icon.appendChild(
  7390. document.createElement("i")).classList.add("icon-connection");
  7391. return icon;
  7392. }
  7393. /**
  7394. * Creates the indicator
  7395. */
  7396. ConnectionIndicator.prototype.create = function () {
  7397. this.connectionIndicatorContainer = document.createElement("div");
  7398. this.connectionIndicatorContainer.className = "connectionindicator";
  7399. this.connectionIndicatorContainer.style.display = "none";
  7400. this.videoContainer.container.appendChild(
  7401. this.connectionIndicatorContainer);
  7402. this.popover = new JitsiPopover(
  7403. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7404. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7405. APP.translation.translateString("connectionindicator.na") + "</div>",
  7406. skin: "black"});
  7407. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7408. createIcon(["connection", "connection_empty"]));
  7409. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7410. createIcon(["connection", "connection_full"]));
  7411. };
  7412. /**
  7413. * Removes the indicator
  7414. */
  7415. ConnectionIndicator.prototype.remove = function() {
  7416. if (this.connectionIndicatorContainer.parentNode) {
  7417. this.connectionIndicatorContainer.parentNode.removeChild(
  7418. this.connectionIndicatorContainer);
  7419. }
  7420. this.popover.forceHide();
  7421. };
  7422. /**
  7423. * Updates the data of the indicator
  7424. * @param percent the percent of connection quality
  7425. * @param object the statistics data.
  7426. */
  7427. ConnectionIndicator.prototype.updateConnectionQuality =
  7428. function (percent, object) {
  7429. if (percent === null) {
  7430. this.connectionIndicatorContainer.style.display = "none";
  7431. this.popover.forceHide();
  7432. return;
  7433. } else {
  7434. if(this.connectionIndicatorContainer.style.display == "none") {
  7435. this.connectionIndicatorContainer.style.display = "block";
  7436. this.videoContainer.updateIconPositions();
  7437. }
  7438. }
  7439. this.bandwidth = object.bandwidth;
  7440. this.bitrate = object.bitrate;
  7441. this.packetLoss = object.packetLoss;
  7442. this.transport = object.transport;
  7443. if (object.resolution) {
  7444. this.resolution = object.resolution;
  7445. }
  7446. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7447. if (percent >= quality) {
  7448. this.fullIcon.style.width =
  7449. ConnectionIndicator.connectionQualityValues[quality];
  7450. }
  7451. }
  7452. this.updatePopoverData();
  7453. };
  7454. /**
  7455. * Updates the resolution
  7456. * @param resolution the new resolution
  7457. */
  7458. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7459. this.resolution = resolution;
  7460. this.updatePopoverData();
  7461. };
  7462. /**
  7463. * Updates the content of the popover
  7464. */
  7465. ConnectionIndicator.prototype.updatePopoverData = function () {
  7466. this.popover.updateContent(
  7467. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7468. APP.translation.translateElement($(".connection_info"));
  7469. };
  7470. /**
  7471. * Hides the popover
  7472. */
  7473. ConnectionIndicator.prototype.hide = function () {
  7474. this.popover.forceHide();
  7475. };
  7476. /**
  7477. * Hides the indicator
  7478. */
  7479. ConnectionIndicator.prototype.hideIndicator = function () {
  7480. this.connectionIndicatorContainer.style.display = "none";
  7481. if(this.popover)
  7482. this.popover.forceHide();
  7483. };
  7484. module.exports = ConnectionIndicator;
  7485. },{"../util/JitsiPopover":32}],37:[function(require,module,exports){
  7486. /* global $, APP, Strophe, interfaceConfig */
  7487. var Avatar = require("../avatar/Avatar");
  7488. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7489. var UIUtil = require("../util/UIUtil");
  7490. var UIEvents = require("../../../service/UI/UIEvents");
  7491. var xmpp = require("../../xmpp/xmpp");
  7492. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7493. // FIXME: With Temasys we have to re-select everytime
  7494. //var video = $('#largeVideo');
  7495. var currentVideoWidth = null;
  7496. var currentVideoHeight = null;
  7497. // By default we use camera
  7498. var getVideoSize = getCameraVideoSize;
  7499. var getVideoPosition = getCameraVideoPosition;
  7500. /**
  7501. * The small video instance that is displayed in the large video
  7502. * @type {SmallVideo}
  7503. */
  7504. var currentSmallVideo = null;
  7505. /**
  7506. * Indicates whether the large video is enabled.
  7507. * @type {boolean}
  7508. */
  7509. var isEnabled = true;
  7510. /**
  7511. * Current large video state.
  7512. * Possible values - video, prezi or etherpad.
  7513. * @type {string}
  7514. */
  7515. var state = "video";
  7516. /**
  7517. * Returns the html element associated with the passed state of large video
  7518. * @param state the state.
  7519. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7520. */
  7521. function getContainerByState(state)
  7522. {
  7523. var selector = null;
  7524. switch (state)
  7525. {
  7526. case "video":
  7527. selector = "#largeVideoWrapper";
  7528. break;
  7529. case "etherpad":
  7530. selector = "#etherpad>iframe";
  7531. break;
  7532. case "prezi":
  7533. selector = "#presentation>iframe";
  7534. break;
  7535. }
  7536. return (selector !== null)? $(selector) : null;
  7537. }
  7538. /**
  7539. * Sets the size and position of the given video element.
  7540. *
  7541. * @param video the video element to position
  7542. * @param width the desired video width
  7543. * @param height the desired video height
  7544. * @param horizontalIndent the left and right indent
  7545. * @param verticalIndent the top and bottom indent
  7546. */
  7547. function positionVideo(video,
  7548. width,
  7549. height,
  7550. horizontalIndent,
  7551. verticalIndent,
  7552. animate) {
  7553. if (animate) {
  7554. video.animate({
  7555. width: width,
  7556. height: height,
  7557. top: verticalIndent,
  7558. bottom: verticalIndent,
  7559. left: horizontalIndent,
  7560. right: horizontalIndent
  7561. },
  7562. {
  7563. queue: false,
  7564. duration: 500
  7565. });
  7566. } else {
  7567. video.width(width);
  7568. video.height(height);
  7569. video.css({ top: verticalIndent + 'px',
  7570. bottom: verticalIndent + 'px',
  7571. left: horizontalIndent + 'px',
  7572. right: horizontalIndent + 'px'});
  7573. }
  7574. }
  7575. /**
  7576. * Returns an array of the video dimensions, so that it keeps it's aspect
  7577. * ratio and fits available area with it's larger dimension. This method
  7578. * ensures that whole video will be visible and can leave empty areas.
  7579. *
  7580. * @return an array with 2 elements, the video width and the video height
  7581. */
  7582. function getDesktopVideoSize(videoWidth,
  7583. videoHeight,
  7584. videoSpaceWidth,
  7585. videoSpaceHeight) {
  7586. if (!videoWidth)
  7587. videoWidth = currentVideoWidth;
  7588. if (!videoHeight)
  7589. videoHeight = currentVideoHeight;
  7590. var aspectRatio = videoWidth / videoHeight;
  7591. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7592. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7593. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7594. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7595. {
  7596. availableHeight = videoSpaceHeight;
  7597. availableWidth = availableHeight * aspectRatio;
  7598. }
  7599. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7600. {
  7601. availableWidth = videoSpaceWidth;
  7602. availableHeight = availableWidth / aspectRatio;
  7603. }
  7604. return [availableWidth, availableHeight];
  7605. }
  7606. /**
  7607. * Returns an array of the video horizontal and vertical indents,
  7608. * so that if fits its parent.
  7609. *
  7610. * @return an array with 2 elements, the horizontal indent and the vertical
  7611. * indent
  7612. */
  7613. function getCameraVideoPosition(videoWidth,
  7614. videoHeight,
  7615. videoSpaceWidth,
  7616. videoSpaceHeight) {
  7617. // Parent height isn't completely calculated when we position the video in
  7618. // full screen mode and this is why we use the screen height in this case.
  7619. // Need to think it further at some point and implement it properly.
  7620. var isFullScreen = document.fullScreen ||
  7621. document.mozFullScreen ||
  7622. document.webkitIsFullScreen;
  7623. if (isFullScreen)
  7624. videoSpaceHeight = window.innerHeight;
  7625. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7626. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7627. return [horizontalIndent, verticalIndent];
  7628. }
  7629. /**
  7630. * Returns an array of the video horizontal and vertical indents.
  7631. * Centers horizontally and top aligns vertically.
  7632. *
  7633. * @return an array with 2 elements, the horizontal indent and the vertical
  7634. * indent
  7635. */
  7636. function getDesktopVideoPosition(videoWidth,
  7637. videoHeight,
  7638. videoSpaceWidth,
  7639. videoSpaceHeight) {
  7640. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7641. var verticalIndent = 0;// Top aligned
  7642. return [horizontalIndent, verticalIndent];
  7643. }
  7644. /**
  7645. * Returns an array of the video dimensions, so that it covers the screen.
  7646. * It leaves no empty areas, but some parts of the video might not be visible.
  7647. *
  7648. * @return an array with 2 elements, the video width and the video height
  7649. */
  7650. function getCameraVideoSize(videoWidth,
  7651. videoHeight,
  7652. videoSpaceWidth,
  7653. videoSpaceHeight) {
  7654. if (!videoWidth)
  7655. videoWidth = currentVideoWidth;
  7656. if (!videoHeight)
  7657. videoHeight = currentVideoHeight;
  7658. var aspectRatio = videoWidth / videoHeight;
  7659. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7660. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7661. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7662. availableHeight = videoSpaceHeight;
  7663. availableWidth = availableHeight * aspectRatio;
  7664. }
  7665. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7666. availableWidth = videoSpaceWidth;
  7667. availableHeight = availableWidth / aspectRatio;
  7668. }
  7669. return [availableWidth, availableHeight];
  7670. }
  7671. /**
  7672. * Updates the src of the active speaker avatar
  7673. * @param jid of the current active speaker
  7674. */
  7675. function updateActiveSpeakerAvatarSrc() {
  7676. var avatar = $("#activeSpeakerAvatar")[0];
  7677. var jid = currentSmallVideo.peerJid;
  7678. var url = Avatar.getActiveSpeakerUrl(jid);
  7679. if (avatar.src === url)
  7680. return;
  7681. if (jid) {
  7682. avatar.src = url;
  7683. currentSmallVideo.showAvatar();
  7684. }
  7685. }
  7686. /**
  7687. * Change the video source of the large video.
  7688. * @param isVisible
  7689. */
  7690. function changeVideo(isVisible) {
  7691. if (!currentSmallVideo) {
  7692. console.error("Unable to change large video - no 'currentSmallVideo'");
  7693. return;
  7694. }
  7695. updateActiveSpeakerAvatarSrc();
  7696. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7697. var videoTransform = document.getElementById('largeVideo')
  7698. .style.webkitTransform;
  7699. var flipX = currentSmallVideo.flipX;
  7700. if (flipX && videoTransform !== 'scaleX(-1)') {
  7701. document.getElementById('largeVideo').style.webkitTransform =
  7702. "scaleX(-1)";
  7703. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7704. document.getElementById('largeVideo').style.webkitTransform =
  7705. "none";
  7706. }
  7707. var isDesktop = currentSmallVideo.getVideoType() === 'screen';
  7708. // Change the way we'll be measuring and positioning large video
  7709. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7710. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7711. getCameraVideoPosition;
  7712. // Only if the large video is currently visible.
  7713. if (isVisible) {
  7714. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7715. $('#largeVideoWrapper').fadeTo(300, 1);
  7716. }
  7717. }
  7718. /**
  7719. * Creates the html elements for the large video.
  7720. */
  7721. function createLargeVideoHTML()
  7722. {
  7723. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7724. html += '<div id="presentation"></div>' +
  7725. '<div id="etherpad"></div>' +
  7726. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7727. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7728. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7729. '<span data-i18n="poweredby"></span> jitsi.org' +
  7730. '</a>'+
  7731. '<div id="activeSpeaker">' +
  7732. '<img id="activeSpeakerAvatar" src=""/>' +
  7733. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7734. '</div>' +
  7735. '<div id="largeVideoWrapper">' +
  7736. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7737. '</div id="largeVideoWrapper">' +
  7738. '<span id="videoConnectionMessage"></span>';
  7739. html += '</div>';
  7740. $(html).prependTo("#videospace");
  7741. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7742. var leftWatermarkDiv
  7743. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7744. leftWatermarkDiv.css({display: 'block'});
  7745. leftWatermarkDiv.parent().get(0).href
  7746. = interfaceConfig.JITSI_WATERMARK_LINK;
  7747. }
  7748. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7749. var rightWatermarkDiv
  7750. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7751. rightWatermarkDiv.css({display: 'block'});
  7752. rightWatermarkDiv.parent().get(0).href
  7753. = interfaceConfig.BRAND_WATERMARK_LINK;
  7754. rightWatermarkDiv.get(0).style.backgroundImage
  7755. = "url(images/rightwatermark.png)";
  7756. }
  7757. if (interfaceConfig.SHOW_POWERED_BY) {
  7758. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7759. }
  7760. if (!RTCBrowserType.isIExplorer()) {
  7761. $('#largeVideo').volume = 0;
  7762. }
  7763. }
  7764. var LargeVideo = {
  7765. init: function (VideoLayout, emitter) {
  7766. if(!isEnabled)
  7767. return;
  7768. createLargeVideoHTML();
  7769. this.VideoLayout = VideoLayout;
  7770. this.eventEmitter = emitter;
  7771. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7772. var self = this;
  7773. // Listen for large video size updates
  7774. var largeVideo = $('#largeVideo')[0];
  7775. var onplaying = function (arg1, arg2, arg3) {
  7776. // re-select
  7777. if (RTCBrowserType.isTemasysPluginUsed())
  7778. largeVideo = $('#largeVideo')[0];
  7779. currentVideoWidth = largeVideo.videoWidth;
  7780. currentVideoHeight = largeVideo.videoHeight;
  7781. self.position(currentVideoWidth, currentVideoHeight);
  7782. };
  7783. largeVideo.onplaying = onplaying;
  7784. },
  7785. /**
  7786. * Indicates if the large video is currently visible.
  7787. *
  7788. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7789. */
  7790. isLargeVideoVisible: function() {
  7791. return $('#largeVideoWrapper').is(':visible');
  7792. },
  7793. /**
  7794. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7795. */
  7796. isCurrentlyOnLarge: function (resourceJid) {
  7797. return currentSmallVideo && resourceJid &&
  7798. currentSmallVideo.getResourceJid() === resourceJid;
  7799. },
  7800. /**
  7801. * Updates the large video with the given new video source.
  7802. */
  7803. updateLargeVideo: function (resourceJid, forceUpdate) {
  7804. if(!isEnabled)
  7805. return;
  7806. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7807. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7808. if (!newSmallVideo) {
  7809. console.error("Small video not found for: " + resourceJid);
  7810. return;
  7811. }
  7812. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7813. $('#activeSpeaker').css('visibility', 'hidden');
  7814. var oldSmallVideo = null;
  7815. if (currentSmallVideo) {
  7816. oldSmallVideo = currentSmallVideo;
  7817. }
  7818. currentSmallVideo = newSmallVideo;
  7819. var oldJid = null;
  7820. if (oldSmallVideo)
  7821. oldJid = oldSmallVideo.peerJid;
  7822. if (oldJid !== resourceJid) {
  7823. // we want the notification to trigger even if userJid is undefined,
  7824. // or null.
  7825. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7826. }
  7827. // We are doing fadeOut/fadeIn animations on parent div which wraps
  7828. // largeVideo, because when Temasys plugin is in use it replaces
  7829. // <video> elements with plugin <object> tag. In Safari jQuery is
  7830. // unable to store values on this plugin object which breaks all
  7831. // animation effects performed on it directly.
  7832. //
  7833. // If for any reason large video was hidden before calling fadeOut
  7834. // changeVideo will never be called, so we call show() in chain just
  7835. // to be sure
  7836. $('#largeVideoWrapper').show().fadeTo(300, 0,
  7837. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7838. } else {
  7839. if (currentSmallVideo) {
  7840. currentSmallVideo.showAvatar();
  7841. }
  7842. }
  7843. },
  7844. /**
  7845. * Shows/hides the large video.
  7846. */
  7847. setLargeVideoVisible: function(isVisible) {
  7848. if(!isEnabled)
  7849. return;
  7850. if (isVisible) {
  7851. $('#largeVideoWrapper').css({visibility: 'visible'});
  7852. $('.watermark').css({visibility: 'visible'});
  7853. if(currentSmallVideo)
  7854. currentSmallVideo.enableDominantSpeaker(true);
  7855. }
  7856. else {
  7857. $('#largeVideoWrapper').css({visibility: 'hidden'});
  7858. $('#activeSpeaker').css('visibility', 'hidden');
  7859. $('.watermark').css({visibility: 'hidden'});
  7860. if(currentSmallVideo)
  7861. currentSmallVideo.enableDominantSpeaker(false);
  7862. }
  7863. },
  7864. onVideoTypeChanged: function (resourceJid, newVideoType) {
  7865. if (!isEnabled)
  7866. return;
  7867. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7868. {
  7869. var isDesktop = newVideoType === 'screen';
  7870. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7871. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7872. : getCameraVideoPosition;
  7873. this.position(null, null, null, null, true);
  7874. }
  7875. },
  7876. /**
  7877. * Positions the large video.
  7878. *
  7879. * @param videoWidth the stream video width
  7880. * @param videoHeight the stream video height
  7881. */
  7882. position: function (videoWidth, videoHeight,
  7883. videoSpaceWidth, videoSpaceHeight, animate) {
  7884. if(!isEnabled)
  7885. return;
  7886. if(!videoSpaceWidth)
  7887. videoSpaceWidth = $('#videospace').width();
  7888. if(!videoSpaceHeight)
  7889. videoSpaceHeight = window.innerHeight;
  7890. var videoSize = getVideoSize(videoWidth,
  7891. videoHeight,
  7892. videoSpaceWidth,
  7893. videoSpaceHeight);
  7894. var largeVideoWidth = videoSize[0];
  7895. var largeVideoHeight = videoSize[1];
  7896. var videoPosition = getVideoPosition(largeVideoWidth,
  7897. largeVideoHeight,
  7898. videoSpaceWidth,
  7899. videoSpaceHeight);
  7900. var horizontalIndent = videoPosition[0];
  7901. var verticalIndent = videoPosition[1];
  7902. positionVideo($('#largeVideoWrapper'),
  7903. largeVideoWidth,
  7904. largeVideoHeight,
  7905. horizontalIndent, verticalIndent, animate);
  7906. },
  7907. /**
  7908. * Resizes the large html elements.
  7909. * @param animate boolean property that indicates whether the resize should be animated or not.
  7910. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  7911. * If that parameter is null the method will check the chat pannel visibility.
  7912. * @param completeFunction a function to be called when the video space is resized
  7913. * @returns {*[]} array with the current width and height values of the largeVideo html element.
  7914. */
  7915. resize: function (animate, isVisible, completeFunction) {
  7916. if(!isEnabled)
  7917. return;
  7918. var availableHeight = window.innerHeight;
  7919. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7920. if (availableWidth < 0 || availableHeight < 0) return;
  7921. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7922. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7923. $('#activeSpeaker').css('top', top);
  7924. this.VideoLayout.resizeVideoSpace(animate, isVisible, completeFunction);
  7925. if(animate) {
  7926. $('#largeVideoContainer').animate({
  7927. width: availableWidth,
  7928. height: availableHeight
  7929. },
  7930. {
  7931. queue: false,
  7932. duration: 500
  7933. });
  7934. } else {
  7935. $('#largeVideoContainer').width(availableWidth);
  7936. $('#largeVideoContainer').height(availableHeight);
  7937. }
  7938. return [availableWidth, availableHeight];
  7939. },
  7940. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7941. if(!isEnabled)
  7942. return;
  7943. var size = this.resize(true, isVisible, completeFunction);
  7944. this.position(null, null, size[0], size[1], true);
  7945. },
  7946. getResourceJid: function () {
  7947. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7948. },
  7949. updateAvatar: function (resourceJid) {
  7950. if(!isEnabled)
  7951. return;
  7952. if (resourceJid === this.getResourceJid()) {
  7953. updateActiveSpeakerAvatarSrc();
  7954. }
  7955. },
  7956. showAvatar: function (resourceJid, show) {
  7957. if (!isEnabled)
  7958. return;
  7959. if (this.getResourceJid() === resourceJid && state === "video") {
  7960. $("#largeVideoWrapper")
  7961. .css("visibility", show ? "hidden" : "visible");
  7962. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7963. return true;
  7964. }
  7965. return false;
  7966. },
  7967. /**
  7968. * Disables the large video
  7969. */
  7970. disable: function () {
  7971. isEnabled = false;
  7972. },
  7973. /**
  7974. * Enables the large video
  7975. */
  7976. enable: function () {
  7977. isEnabled = true;
  7978. },
  7979. /**
  7980. * Returns true if the video is enabled.
  7981. */
  7982. isEnabled: function () {
  7983. return isEnabled;
  7984. },
  7985. /**
  7986. * Creates the iframe used by the etherpad
  7987. * @param src the value for src attribute
  7988. * @param onloadHandler handler executed when the iframe loads it content
  7989. * @returns {HTMLElement} the iframe
  7990. */
  7991. createEtherpadIframe: function (src, onloadHandler) {
  7992. if(!isEnabled)
  7993. return;
  7994. var etherpadIFrame = document.createElement('iframe');
  7995. etherpadIFrame.src = src;
  7996. etherpadIFrame.frameBorder = 0;
  7997. etherpadIFrame.scrolling = "no";
  7998. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  7999. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  8000. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  8001. document.getElementById('etherpad').appendChild(etherpadIFrame);
  8002. etherpadIFrame.onload = onloadHandler;
  8003. return etherpadIFrame;
  8004. },
  8005. /**
  8006. * Changes the state of the large video.
  8007. * Possible values - video, prezi, etherpad.
  8008. * @param newState - the new state
  8009. */
  8010. setState: function (newState) {
  8011. if(state === newState)
  8012. return;
  8013. var currentContainer = getContainerByState(state);
  8014. if(!currentContainer)
  8015. return;
  8016. var self = this;
  8017. var oldState = state;
  8018. switch (newState)
  8019. {
  8020. case "etherpad":
  8021. $('#activeSpeaker').css('visibility', 'hidden');
  8022. currentContainer.fadeOut(300, function () {
  8023. if (oldState === "prezi") {
  8024. currentContainer.css({opacity: '0'});
  8025. $('#reloadPresentation').css({display: 'none'});
  8026. }
  8027. else {
  8028. self.setLargeVideoVisible(false);
  8029. }
  8030. });
  8031. $('#etherpad>iframe').fadeIn(300, function () {
  8032. document.body.style.background = '#eeeeee';
  8033. $('#etherpad>iframe').css({visibility: 'visible'});
  8034. $('#etherpad').css({zIndex: 2});
  8035. });
  8036. break;
  8037. case "prezi":
  8038. var prezi = $('#presentation>iframe');
  8039. currentContainer.fadeOut(300, function() {
  8040. document.body.style.background = 'black';
  8041. });
  8042. prezi.fadeIn(300, function() {
  8043. prezi.css({opacity:'1'});
  8044. ToolbarToggler.dockToolbar(true);//fix that
  8045. self.setLargeVideoVisible(false);
  8046. $('#etherpad>iframe').css({visibility: 'hidden'});
  8047. $('#etherpad').css({zIndex: 0});
  8048. });
  8049. $('#activeSpeaker').css('visibility', 'hidden');
  8050. break;
  8051. case "video":
  8052. currentContainer.fadeOut(300, function () {
  8053. $('#presentation>iframe').css({opacity:'0'});
  8054. $('#reloadPresentation').css({display:'none'});
  8055. $('#etherpad>iframe').css({visibility: 'hidden'});
  8056. $('#etherpad').css({zIndex: 0});
  8057. document.body.style.background = 'black';
  8058. ToolbarToggler.dockToolbar(false);//fix that
  8059. });
  8060. $('#largeVideoWrapper').fadeIn(300, function () {
  8061. self.setLargeVideoVisible(true);
  8062. });
  8063. break;
  8064. }
  8065. state = newState;
  8066. },
  8067. /**
  8068. * Returns the current state of the large video.
  8069. * @returns {string} the current state - video, prezi or etherpad.
  8070. */
  8071. getState: function () {
  8072. return state;
  8073. },
  8074. /**
  8075. * Sets hover handlers for the large video container div.
  8076. *
  8077. * @param inHandler
  8078. * @param outHandler
  8079. */
  8080. setHover: function(inHandler, outHandler)
  8081. {
  8082. $('#largeVideoContainer').hover(inHandler, outHandler);
  8083. },
  8084. /**
  8085. * Enables/disables the filter indicating a video problem to the user.
  8086. *
  8087. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  8088. */
  8089. enableVideoProblemFilter: function (enable) {
  8090. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  8091. }
  8092. };
  8093. module.exports = LargeVideo;
  8094. },{"../../../service/UI/UIEvents":168,"../../RTC/RTCBrowserType":10,"../../xmpp/xmpp":73,"../avatar/Avatar":18,"../toolbars/ToolbarToggler":31,"../util/UIUtil":35}],38:[function(require,module,exports){
  8095. /* global $, interfaceConfig, APP */
  8096. var SmallVideo = require("./SmallVideo");
  8097. var ConnectionIndicator = require("./ConnectionIndicator");
  8098. var NicknameHandler = require("../util/NicknameHandler");
  8099. var UIUtil = require("../util/UIUtil");
  8100. var LargeVideo = require("./LargeVideo");
  8101. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8102. function LocalVideo(VideoLayout) {
  8103. this.videoSpanId = "localVideoContainer";
  8104. this.container = $("#localVideoContainer").get(0);
  8105. this.bindHoverHandler();
  8106. this.VideoLayout = VideoLayout;
  8107. this.flipX = true;
  8108. this.isLocal = true;
  8109. this.peerJid = null;
  8110. }
  8111. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  8112. LocalVideo.prototype.constructor = LocalVideo;
  8113. /**
  8114. * Creates the edit display name button.
  8115. *
  8116. * @returns {object} the edit button
  8117. */
  8118. function createEditDisplayNameButton() {
  8119. var editButton = document.createElement('a');
  8120. editButton.className = 'displayname';
  8121. UIUtil.setTooltip(editButton,
  8122. "videothumbnail.editnickname",
  8123. "top");
  8124. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  8125. return editButton;
  8126. }
  8127. /**
  8128. * Sets the display name for the given video span id.
  8129. */
  8130. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  8131. if (!this.container) {
  8132. console.warn(
  8133. "Unable to set displayName - " + this.videoSpanId +
  8134. " does not exist");
  8135. return;
  8136. }
  8137. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8138. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  8139. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8140. var meHTML;
  8141. // If we already have a display name for this video.
  8142. if (nameSpan.length > 0) {
  8143. if (nameSpan.text() !== displayName) {
  8144. if (displayName && displayName.length > 0) {
  8145. meHTML = APP.translation.generateTranslationHTML("me");
  8146. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  8147. } else {
  8148. $('#localDisplayName').html(defaultLocalDisplayName);
  8149. }
  8150. }
  8151. } else {
  8152. var editButton = createEditDisplayNameButton();
  8153. nameSpan = document.createElement('span');
  8154. nameSpan.className = 'displayname';
  8155. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8156. if (displayName && displayName.length > 0) {
  8157. meHTML = APP.translation.generateTranslationHTML("me");
  8158. nameSpan.innerHTML = displayName + meHTML;
  8159. }
  8160. else {
  8161. nameSpan.innerHTML = defaultLocalDisplayName;
  8162. }
  8163. nameSpan.id = 'localDisplayName';
  8164. this.container.appendChild(editButton);
  8165. //translates popover of edit button
  8166. APP.translation.translateElement($("a.displayname"));
  8167. var editableText = document.createElement('input');
  8168. editableText.className = 'displayname';
  8169. editableText.type = 'text';
  8170. editableText.id = 'editDisplayName';
  8171. if (displayName && displayName.length) {
  8172. editableText.value = displayName;
  8173. }
  8174. var defaultNickname = APP.translation.translateString(
  8175. "defaultNickname", {name: "Jane Pink"});
  8176. editableText.setAttribute('style', 'display:none;');
  8177. editableText.setAttribute('data-18n',
  8178. '[placeholder]defaultNickname');
  8179. editableText.setAttribute("data-i18n-options",
  8180. JSON.stringify({name: "Jane Pink"}));
  8181. editableText.setAttribute("placeholder", defaultNickname);
  8182. this.container.appendChild(editableText);
  8183. var self = this;
  8184. $('#localVideoContainer .displayname')
  8185. .bind("click", function (e) {
  8186. var editDisplayName = $('#editDisplayName');
  8187. e.preventDefault();
  8188. e.stopPropagation();
  8189. $('#localDisplayName').hide();
  8190. editDisplayName.show();
  8191. editDisplayName.focus();
  8192. editDisplayName.select();
  8193. editDisplayName.one("focusout", function (e) {
  8194. self.VideoLayout.inputDisplayNameHandler(this.value);
  8195. });
  8196. editDisplayName.on('keydown', function (e) {
  8197. if (e.keyCode === 13) {
  8198. e.preventDefault();
  8199. self.VideoLayout.inputDisplayNameHandler(this.value);
  8200. }
  8201. });
  8202. });
  8203. }
  8204. };
  8205. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  8206. NicknameHandler.setNickname(name);
  8207. var localDisplayName = $('#localDisplayName');
  8208. if (!localDisplayName.is(":visible")) {
  8209. if (NicknameHandler.getNickname()) {
  8210. var meHTML = APP.translation.generateTranslationHTML("me");
  8211. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  8212. meHTML + ")");
  8213. } else {
  8214. var defaultHTML = APP.translation.generateTranslationHTML(
  8215. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8216. localDisplayName .html(defaultHTML);
  8217. }
  8218. localDisplayName.show();
  8219. }
  8220. $('#editDisplayName').hide();
  8221. };
  8222. LocalVideo.prototype.createConnectionIndicator = function() {
  8223. if(this.connectionIndicator)
  8224. return;
  8225. this.connectionIndicator = new ConnectionIndicator(this, null);
  8226. };
  8227. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  8228. var self = this;
  8229. function localVideoClick(event) {
  8230. // FIXME: with Temasys plugin event arg is not an event, but
  8231. // the clicked object itself, so we have to skip this call
  8232. if (event.stopPropagation) {
  8233. event.stopPropagation();
  8234. }
  8235. self.VideoLayout.handleVideoThumbClicked(
  8236. true,
  8237. APP.xmpp.myResource());
  8238. }
  8239. var localVideoContainerSelector = $('#localVideoContainer');
  8240. localVideoContainerSelector.off('click');
  8241. localVideoContainerSelector.on('click', localVideoClick);
  8242. if(isMuted) {
  8243. APP.UI.setVideoMute(true);
  8244. return;
  8245. }
  8246. this.flipX = stream.videoType != "screen";
  8247. var localVideo = document.createElement('video');
  8248. localVideo.id = 'localVideo_' +
  8249. APP.RTC.getStreamID(stream.getOriginalStream());
  8250. if (!RTCBrowserType.isIExplorer()) {
  8251. localVideo.autoplay = true;
  8252. localVideo.volume = 0; // is it required if audio is separated ?
  8253. }
  8254. localVideo.oncontextmenu = function () { return false; };
  8255. var localVideoContainer = document.getElementById('localVideoWrapper');
  8256. // Put the new video always in front
  8257. UIUtil.prependChild(localVideoContainer, localVideo);
  8258. var localVideoSelector = $('#' + localVideo.id);
  8259. // Add click handler to both video and video wrapper elements in case
  8260. // there's no video.
  8261. // onclick has to be used with Temasys plugin
  8262. localVideo.onclick = localVideoClick;
  8263. if (this.flipX) {
  8264. localVideoSelector.addClass("flipVideoX");
  8265. }
  8266. // Attach WebRTC stream
  8267. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  8268. // Add stream ended handler
  8269. stream.getOriginalStream().onended = function () {
  8270. // We have to re-select after attach when Temasys plugin is used,
  8271. // because <video> element is replaced with <object>
  8272. localVideo = $('#' + localVideo.id)[0];
  8273. localVideoContainer.removeChild(localVideo);
  8274. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  8275. };
  8276. };
  8277. LocalVideo.prototype.joined = function (jid) {
  8278. this.peerJid = jid;
  8279. };
  8280. LocalVideo.prototype.getResourceJid = function () {
  8281. var myResource = APP.xmpp.myResource();
  8282. if (!myResource) {
  8283. console.error("Requested local resource before we're in the MUC");
  8284. }
  8285. return myResource;
  8286. };
  8287. module.exports = LocalVideo;
  8288. },{"../../RTC/RTCBrowserType":10,"../util/NicknameHandler":34,"../util/UIUtil":35,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],39:[function(require,module,exports){
  8289. /* global $, APP, require, Strophe, interfaceConfig */
  8290. var ConnectionIndicator = require("./ConnectionIndicator");
  8291. var SmallVideo = require("./SmallVideo");
  8292. var AudioLevels = require("../audio_levels/AudioLevels");
  8293. var LargeVideo = require("./LargeVideo");
  8294. var Avatar = require("../avatar/Avatar");
  8295. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8296. var UIUtils = require("../util/UIUtil");
  8297. function RemoteVideo(peerJid, VideoLayout) {
  8298. this.peerJid = peerJid;
  8299. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  8300. this.videoSpanId = 'participant_' + this.resourceJid;
  8301. this.VideoLayout = VideoLayout;
  8302. this.addRemoteVideoContainer();
  8303. this.connectionIndicator = new ConnectionIndicator(
  8304. this, this.peerJid);
  8305. this.setDisplayName();
  8306. var nickfield = document.createElement('span');
  8307. nickfield.className = "nick";
  8308. nickfield.appendChild(document.createTextNode(this.resourceJid));
  8309. this.container.appendChild(nickfield);
  8310. this.bindHoverHandler();
  8311. this.flipX = false;
  8312. this.isLocal = false;
  8313. }
  8314. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  8315. RemoteVideo.prototype.constructor = RemoteVideo;
  8316. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  8317. this.container = RemoteVideo.createContainer(this.videoSpanId);
  8318. if (APP.xmpp.isModerator())
  8319. this.addRemoteVideoMenu();
  8320. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  8321. return this.container;
  8322. };
  8323. /**
  8324. * Adds the remote video menu element for the given <tt>jid</tt> in the
  8325. * given <tt>parentElement</tt>.
  8326. *
  8327. * @param jid the jid indicating the video for which we're adding a menu.
  8328. * @param parentElement the parent element where this menu will be added
  8329. */
  8330. if (!interfaceConfig.filmStripOnly) {
  8331. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  8332. var spanElement = document.createElement('span');
  8333. spanElement.className = 'remotevideomenu';
  8334. this.container.appendChild(spanElement);
  8335. var menuElement = document.createElement('i');
  8336. menuElement.className = 'fa fa-angle-down';
  8337. menuElement.title = 'Remote user controls';
  8338. spanElement.appendChild(menuElement);
  8339. var popupmenuElement = document.createElement('ul');
  8340. popupmenuElement.className = 'popupmenu';
  8341. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  8342. spanElement.appendChild(popupmenuElement);
  8343. var muteMenuItem = document.createElement('li');
  8344. var muteLinkItem = document.createElement('a');
  8345. var mutedIndicator = "<i style='float:left;' " +
  8346. "class='icon-mic-disabled'></i>";
  8347. if (!this.isMuted) {
  8348. muteLinkItem.innerHTML = mutedIndicator +
  8349. " <div style='width: 90px;margin-left: 20px;' " +
  8350. "data-i18n='videothumbnail.domute'></div>";
  8351. muteLinkItem.className = 'mutelink';
  8352. }
  8353. else {
  8354. muteLinkItem.innerHTML = mutedIndicator +
  8355. " <div style='width: 90px;margin-left: 20px;' " +
  8356. "data-i18n='videothumbnail.muted'></div>";
  8357. muteLinkItem.className = 'mutelink disabled';
  8358. }
  8359. var self = this;
  8360. muteLinkItem.onclick = function(){
  8361. if ($(this).attr('disabled') != undefined) {
  8362. event.preventDefault();
  8363. }
  8364. var isMute = self.isMuted == true;
  8365. APP.xmpp.setMute(self.peerJid, !isMute);
  8366. popupmenuElement.setAttribute('style', 'display:none;');
  8367. if (isMute) {
  8368. this.innerHTML = mutedIndicator +
  8369. " <div style='width: 90px;margin-left: 20px;' " +
  8370. "data-i18n='videothumbnail.muted'></div>";
  8371. this.className = 'mutelink disabled';
  8372. }
  8373. else {
  8374. this.innerHTML = mutedIndicator +
  8375. " <div style='width: 90px;margin-left: 20px;' " +
  8376. "data-i18n='videothumbnail.domute'></div>";
  8377. this.className = 'mutelink';
  8378. }
  8379. };
  8380. muteMenuItem.appendChild(muteLinkItem);
  8381. popupmenuElement.appendChild(muteMenuItem);
  8382. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8383. var ejectMenuItem = document.createElement('li');
  8384. var ejectLinkItem = document.createElement('a');
  8385. var ejectText = "<div style='width: 90px;margin-left: 20px;' " +
  8386. "data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8387. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8388. ejectLinkItem.onclick = function(){
  8389. APP.xmpp.eject(self.peerJid);
  8390. popupmenuElement.setAttribute('style', 'display:none;');
  8391. };
  8392. ejectMenuItem.appendChild(ejectLinkItem);
  8393. popupmenuElement.appendChild(ejectMenuItem);
  8394. var paddingSpan = document.createElement('span');
  8395. paddingSpan.className = 'popupmenuPadding';
  8396. popupmenuElement.appendChild(paddingSpan);
  8397. APP.translation.translateElement(
  8398. $("#" + popupmenuElement.id + " > li > a > div"));
  8399. };
  8400. } else {
  8401. RemoteVideo.prototype.addRemoteVideoMenu = function() {}
  8402. }
  8403. /**
  8404. * Removes the remote stream element corresponding to the given stream and
  8405. * parent container.
  8406. *
  8407. * @param stream the stream
  8408. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8409. */
  8410. RemoteVideo.prototype.removeRemoteStreamElement =
  8411. function (stream, isVideo, id) {
  8412. if (!this.container)
  8413. return false;
  8414. var select = null;
  8415. if (isVideo) {
  8416. select = $('#' + id);
  8417. }
  8418. else
  8419. select = $('#' + this.videoSpanId + '>audio');
  8420. select.remove();
  8421. console.info((isVideo ? "Video" : "Audio") +
  8422. " removed " + this.getResourceJid(), select);
  8423. if (isVideo)
  8424. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8425. };
  8426. /**
  8427. * Removes RemoteVideo from the page.
  8428. */
  8429. RemoteVideo.prototype.remove = function () {
  8430. console.log("Remove thumbnail", this.peerJid);
  8431. this.removeConnectionIndicator();
  8432. // Remove whole container
  8433. if (this.container.parentNode)
  8434. this.container.parentNode.removeChild(this.container);
  8435. };
  8436. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8437. var isVideo = stream.getVideoTracks().length > 0;
  8438. if (!isVideo || stream.id === 'mixedmslabel') {
  8439. return;
  8440. }
  8441. var self = this;
  8442. var resourceJid = this.getResourceJid();
  8443. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8444. // when video playback starts
  8445. var onPlayingHandler = function () {
  8446. // FIXME: why do i have to do this for FF?
  8447. if (RTCBrowserType.isFirefox()) {
  8448. APP.RTC.attachMediaStream(sel, stream);
  8449. }
  8450. if (RTCBrowserType.isTemasysPluginUsed()) {
  8451. sel = self.selectVideoElement();
  8452. }
  8453. self.VideoLayout.videoactive(sel, resourceJid);
  8454. sel[0].onplaying = null;
  8455. if (RTCBrowserType.isTemasysPluginUsed()) {
  8456. // 'currentTime' is used to check if the video has started
  8457. // and the value is not set by the plugin, so we do it
  8458. sel[0].currentTime = 1;
  8459. }
  8460. };
  8461. sel[0].onplaying = onPlayingHandler;
  8462. };
  8463. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8464. if (!this.container)
  8465. return;
  8466. var self = this;
  8467. var isVideo = stream.getVideoTracks().length > 0;
  8468. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8469. var newElementId = streamElement.id;
  8470. // Put new stream element always in front
  8471. UIUtils.prependChild(this.container, streamElement);
  8472. var sel = $('#' + newElementId);
  8473. sel.hide();
  8474. // If the container is currently visible we attach the stream.
  8475. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8476. this.waitForPlayback(sel, stream);
  8477. APP.RTC.attachMediaStream(sel, stream);
  8478. }
  8479. stream.onended = function () {
  8480. console.log('stream ended', this);
  8481. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8482. };
  8483. // Add click handler.
  8484. var onClickHandler = function (event) {
  8485. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8486. // On IE we need to populate this handler on video <object>
  8487. // and it does not give event instance as an argument,
  8488. // so we check here for methods.
  8489. if (event.stopPropagation && event.preventDefault) {
  8490. event.stopPropagation();
  8491. event.preventDefault();
  8492. }
  8493. return false;
  8494. };
  8495. this.container.onclick = onClickHandler;
  8496. // reselect
  8497. if (RTCBrowserType.isTemasysPluginUsed())
  8498. sel = $('#' + newElementId);
  8499. sel[0].onclick = onClickHandler;
  8500. },
  8501. /**
  8502. * Show/hide peer container for the given resourceJid.
  8503. */
  8504. RemoteVideo.prototype.showPeerContainer = function (state) {
  8505. if (!this.container)
  8506. return;
  8507. var isHide = state === 'hide';
  8508. var resizeThumbnails = false;
  8509. if (!isHide) {
  8510. if (!$(this.container).is(':visible')) {
  8511. resizeThumbnails = true;
  8512. $(this.container).show();
  8513. }
  8514. this.showAvatar(state !== 'show');
  8515. }
  8516. else if ($(this.container).is(':visible') && isHide)
  8517. {
  8518. resizeThumbnails = true;
  8519. $(this.container).hide();
  8520. if(this.connectionIndicator)
  8521. this.connectionIndicator.hide();
  8522. }
  8523. if (resizeThumbnails) {
  8524. this.VideoLayout.resizeThumbnails();
  8525. }
  8526. // We want to be able to pin a participant from the contact list, even
  8527. // if he's not in the lastN set!
  8528. // ContactList.setClickable(resourceJid, !isHide);
  8529. };
  8530. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8531. if (this.connectionIndicator)
  8532. this.connectionIndicator.remove();
  8533. };
  8534. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8535. if (this.connectionIndicator)
  8536. this.connectionIndicator.hide();
  8537. };
  8538. /**
  8539. * Updates the remote video menu.
  8540. *
  8541. * @param jid the jid indicating the video for which we're adding a menu.
  8542. * @param isMuted indicates the current mute state
  8543. */
  8544. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8545. var muteMenuItem
  8546. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8547. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8548. if (muteMenuItem.length) {
  8549. var muteLink = muteMenuItem.get(0);
  8550. if (isMuted === 'true') {
  8551. muteLink.innerHTML = mutedIndicator + ' Muted';
  8552. muteLink.className = 'mutelink disabled';
  8553. }
  8554. else {
  8555. muteLink.innerHTML = mutedIndicator + ' Mute';
  8556. muteLink.className = 'mutelink';
  8557. }
  8558. }
  8559. };
  8560. /**
  8561. * Sets the display name for the given video span id.
  8562. */
  8563. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8564. if (!this.container) {
  8565. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8566. " does not exist");
  8567. return;
  8568. }
  8569. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8570. // If we already have a display name for this video.
  8571. if (nameSpan.length > 0) {
  8572. if (displayName && displayName.length > 0) {
  8573. $('#' + this.videoSpanId + '_name').html(displayName);
  8574. }
  8575. else if (key && key.length > 0) {
  8576. var nameHtml = APP.translation.generateTranslationHTML(key);
  8577. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8578. }
  8579. else
  8580. $('#' + this.videoSpanId + '_name').text(
  8581. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8582. } else {
  8583. nameSpan = document.createElement('span');
  8584. nameSpan.className = 'displayname';
  8585. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8586. if (displayName && displayName.length > 0) {
  8587. nameSpan.innerText = displayName;
  8588. }
  8589. else
  8590. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8591. nameSpan.id = this.videoSpanId + '_name';
  8592. }
  8593. };
  8594. /**
  8595. * Removes remote video menu element from video element identified by
  8596. * given <tt>videoElementId</tt>.
  8597. *
  8598. * @param videoElementId the id of local or remote video element.
  8599. */
  8600. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8601. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8602. if (menuSpan.length) {
  8603. menuSpan.remove();
  8604. }
  8605. };
  8606. RemoteVideo.prototype.getResourceJid = function () {
  8607. if (!this.resourceJid) {
  8608. console.error("Undefined resource jid");
  8609. }
  8610. return this.resourceJid;
  8611. };
  8612. RemoteVideo.createContainer = function (spanId) {
  8613. var container = document.createElement('span');
  8614. container.id = spanId;
  8615. container.className = 'videocontainer';
  8616. var remotes = document.getElementById('remoteVideos');
  8617. return remotes.appendChild(container);
  8618. };
  8619. module.exports = RemoteVideo;
  8620. },{"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../avatar/Avatar":18,"../util/UIUtil":35,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],40:[function(require,module,exports){
  8621. /* global $, APP, require */
  8622. var Avatar = require("../avatar/Avatar");
  8623. var UIUtil = require("../util/UIUtil");
  8624. var LargeVideo = require("./LargeVideo");
  8625. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8626. function SmallVideo() {
  8627. this.isMuted = false;
  8628. this.hasAvatar = false;
  8629. }
  8630. function setVisibility(selector, show) {
  8631. if (selector && selector.length > 0) {
  8632. selector.css("visibility", show ? "visible" : "hidden");
  8633. }
  8634. }
  8635. SmallVideo.prototype.showDisplayName = function(isShow) {
  8636. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8637. if (isShow) {
  8638. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8639. nameSpan.setAttribute("style", "display:inline-block;");
  8640. }
  8641. else {
  8642. if (nameSpan)
  8643. nameSpan.setAttribute("style", "display:none;");
  8644. }
  8645. };
  8646. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8647. if(!this.container)
  8648. return;
  8649. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8650. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8651. noMic.remove();
  8652. noVideo.remove();
  8653. if (!devices.audio) {
  8654. this.container.appendChild(
  8655. document.createElement("div")).setAttribute("class", "noMic");
  8656. }
  8657. if (!devices.video) {
  8658. this.container.appendChild(
  8659. document.createElement("div")).setAttribute("class", "noVideo");
  8660. }
  8661. if (!devices.audio && !devices.video) {
  8662. noMic.css("background-position", "75%");
  8663. noVideo.css("background-position", "25%");
  8664. noVideo.css("background-color", "transparent");
  8665. }
  8666. };
  8667. /**
  8668. * Sets the type of the video displayed by this instance.
  8669. * @param videoType 'camera' or 'screen'
  8670. */
  8671. SmallVideo.prototype.setVideoType = function (videoType) {
  8672. this.videoType = videoType;
  8673. };
  8674. /**
  8675. * Returns the type of the video displayed by this instance.
  8676. * @returns {String} 'camera', 'screen' or undefined.
  8677. */
  8678. SmallVideo.prototype.getVideoType = function () {
  8679. return this.videoType;
  8680. };
  8681. /**
  8682. * Shows the presence status message for the given video.
  8683. */
  8684. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8685. if (!this.container) {
  8686. // No container
  8687. return;
  8688. }
  8689. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8690. if (!statusSpan.length) {
  8691. //Add status span
  8692. statusSpan = document.createElement('span');
  8693. statusSpan.className = 'status';
  8694. statusSpan.id = this.videoSpanId + '_status';
  8695. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8696. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8697. }
  8698. // Display status
  8699. if (statusMsg && statusMsg.length) {
  8700. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8701. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8702. }
  8703. else {
  8704. // Hide
  8705. statusSpan.get(0).setAttribute("style", "display:none;");
  8706. }
  8707. };
  8708. /**
  8709. * Creates an audio or video stream element.
  8710. */
  8711. SmallVideo.createStreamElement = function (sid, stream) {
  8712. var isVideo = stream.getVideoTracks().length > 0;
  8713. var element = isVideo ? document.createElement('video')
  8714. : document.createElement('audio');
  8715. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8716. APP.RTC.getStreamID(stream);
  8717. element.id = id;
  8718. if (!RTCBrowserType.isIExplorer()) {
  8719. element.autoplay = true;
  8720. }
  8721. element.oncontextmenu = function () { return false; };
  8722. return element;
  8723. };
  8724. /**
  8725. * Configures hoverIn/hoverOut handlers.
  8726. */
  8727. SmallVideo.prototype.bindHoverHandler = function () {
  8728. // Add hover handler
  8729. var self = this;
  8730. $(this.container).hover(
  8731. function () {
  8732. self.showDisplayName(true);
  8733. },
  8734. function () {
  8735. // If the video has been "pinned" by the user we want to
  8736. // keep the display name on place.
  8737. if (!LargeVideo.isLargeVideoVisible() ||
  8738. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8739. self.showDisplayName(false);
  8740. }
  8741. );
  8742. };
  8743. /**
  8744. * Updates the data for the indicator
  8745. * @param id the id of the indicator
  8746. * @param percent the percent for connection quality
  8747. * @param object the data
  8748. */
  8749. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8750. if(this.connectionIndicator)
  8751. this.connectionIndicator.updateConnectionQuality(percent, object);
  8752. };
  8753. SmallVideo.prototype.hideIndicator = function () {
  8754. if(this.connectionIndicator)
  8755. this.connectionIndicator.hideIndicator();
  8756. };
  8757. /**
  8758. * Shows audio muted indicator over small videos.
  8759. * @param {string} isMuted
  8760. */
  8761. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8762. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8763. if (!isMuted) {
  8764. if (audioMutedSpan.length > 0) {
  8765. audioMutedSpan.popover('hide');
  8766. audioMutedSpan.remove();
  8767. }
  8768. }
  8769. else {
  8770. if(audioMutedSpan.length == 0 ) {
  8771. audioMutedSpan = document.createElement('span');
  8772. audioMutedSpan.className = 'audioMuted';
  8773. UIUtil.setTooltip(audioMutedSpan,
  8774. "videothumbnail.mute",
  8775. "top");
  8776. this.container.appendChild(audioMutedSpan);
  8777. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8778. var mutedIndicator = document.createElement('i');
  8779. mutedIndicator.className = 'icon-mic-disabled';
  8780. audioMutedSpan.appendChild(mutedIndicator);
  8781. }
  8782. this.updateIconPositions();
  8783. }
  8784. this.isMuted = isMuted;
  8785. };
  8786. /**
  8787. * Shows video muted indicator over small videos.
  8788. */
  8789. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8790. this.showAvatar(isMuted);
  8791. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8792. if (isMuted === false) {
  8793. if (videoMutedSpan.length > 0) {
  8794. videoMutedSpan.remove();
  8795. }
  8796. }
  8797. else {
  8798. if(videoMutedSpan.length == 0) {
  8799. videoMutedSpan = document.createElement('span');
  8800. videoMutedSpan.className = 'videoMuted';
  8801. this.container.appendChild(videoMutedSpan);
  8802. var mutedIndicator = document.createElement('i');
  8803. mutedIndicator.className = 'icon-camera-disabled';
  8804. UIUtil.setTooltip(mutedIndicator,
  8805. "videothumbnail.videomute",
  8806. "top");
  8807. videoMutedSpan.appendChild(mutedIndicator);
  8808. //translate texts for muted indicator
  8809. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8810. }
  8811. this.updateIconPositions();
  8812. }
  8813. };
  8814. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8815. var resourceJid = this.getResourceJid();
  8816. var displayName = resourceJid;
  8817. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8818. if (nameSpan.length > 0)
  8819. displayName = nameSpan.html();
  8820. console.log("UI enable dominant speaker",
  8821. displayName,
  8822. resourceJid,
  8823. isEnable);
  8824. if (!this.container) {
  8825. return;
  8826. }
  8827. if (isEnable) {
  8828. this.showDisplayName(LargeVideo.getState() === "video");
  8829. if (!this.container.classList.contains("dominantspeaker"))
  8830. this.container.classList.add("dominantspeaker");
  8831. }
  8832. else {
  8833. this.showDisplayName(false);
  8834. if (this.container.classList.contains("dominantspeaker"))
  8835. this.container.classList.remove("dominantspeaker");
  8836. }
  8837. this.showAvatar();
  8838. };
  8839. SmallVideo.prototype.updateIconPositions = function () {
  8840. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8841. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8842. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8843. if(connectionIndicator.length > 0 &&
  8844. connectionIndicator[0].style.display != "none") {
  8845. audioMutedSpan.css({right: "23px"});
  8846. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8847. } else {
  8848. audioMutedSpan.css({right: "0px"});
  8849. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8850. }
  8851. };
  8852. /**
  8853. * Creates the element indicating the moderator(owner) of the conference.
  8854. *
  8855. * @param parentElement the parent element where the owner indicator will
  8856. * be added
  8857. */
  8858. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8859. // Show moderator indicator
  8860. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8861. if (!indicatorSpan || indicatorSpan.length === 0) {
  8862. indicatorSpan = document.createElement('span');
  8863. indicatorSpan.className = 'focusindicator';
  8864. this.container.appendChild(indicatorSpan);
  8865. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8866. }
  8867. if (indicatorSpan.children().length !== 0)
  8868. return;
  8869. var moderatorIndicator = document.createElement('i');
  8870. moderatorIndicator.className = 'fa fa-star';
  8871. indicatorSpan[0].appendChild(moderatorIndicator);
  8872. UIUtil.setTooltip(indicatorSpan[0],
  8873. "videothumbnail.moderator",
  8874. "top");
  8875. //translates text in focus indicators
  8876. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8877. };
  8878. SmallVideo.prototype.selectVideoElement = function () {
  8879. var videoElem = APP.RTC.getVideoElementName();
  8880. if (!RTCBrowserType.isTemasysPluginUsed()) {
  8881. return $('#' + this.videoSpanId).find(videoElem);
  8882. } else {
  8883. return $('#' + this.videoSpanId +
  8884. (this.isLocal ? '>>' : '>') +
  8885. videoElem + '>param[value="video"]').parent();
  8886. }
  8887. };
  8888. SmallVideo.prototype.getSrc = function () {
  8889. var videoElement = this.selectVideoElement().get(0);
  8890. return APP.RTC.getVideoSrc(videoElement);
  8891. };
  8892. SmallVideo.prototype.focus = function(isFocused) {
  8893. if(!isFocused) {
  8894. this.container.classList.remove("videoContainerFocused");
  8895. } else {
  8896. this.container.classList.add("videoContainerFocused");
  8897. }
  8898. };
  8899. SmallVideo.prototype.hasVideo = function () {
  8900. return this.selectVideoElement().length !== 0;
  8901. };
  8902. /**
  8903. * Hides or shows the user's avatar
  8904. * @param show whether we should show the avatar or not
  8905. * video because there is no dominant speaker and no focused speaker
  8906. */
  8907. SmallVideo.prototype.showAvatar = function (show) {
  8908. if (!this.hasAvatar) {
  8909. if (this.peerJid) {
  8910. // Init avatar
  8911. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8912. } else {
  8913. console.error("Unable to init avatar - no peerjid", this);
  8914. return;
  8915. }
  8916. }
  8917. var resourceJid = this.getResourceJid();
  8918. var video = this.selectVideoElement();
  8919. var avatar = $('#avatar_' + resourceJid);
  8920. if (show === undefined || show === null) {
  8921. if (!this.isLocal &&
  8922. !this.VideoLayout.isInLastN(resourceJid)) {
  8923. show = true;
  8924. } else {
  8925. // We want to show the avatar when the video is muted or not exists
  8926. // that is when 'true' or 'null' is returned
  8927. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8928. }
  8929. }
  8930. if (LargeVideo.showAvatar(resourceJid, show)) {
  8931. setVisibility(avatar, false);
  8932. setVisibility(video, false);
  8933. } else {
  8934. if (video && video.length > 0) {
  8935. setVisibility(video, !show);
  8936. }
  8937. setVisibility(avatar, show);
  8938. }
  8939. };
  8940. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8941. var thumbnail = $('#' + this.videoSpanId);
  8942. var resourceJid = this.getResourceJid();
  8943. var avatar = $('#avatar_' + resourceJid);
  8944. this.hasAvatar = true;
  8945. // set the avatar in the thumbnail
  8946. if (avatar && avatar.length > 0) {
  8947. avatar[0].src = thumbUrl;
  8948. } else {
  8949. if (thumbnail && thumbnail.length > 0) {
  8950. avatar = document.createElement('img');
  8951. avatar.id = 'avatar_' + resourceJid;
  8952. avatar.className = 'userAvatar';
  8953. avatar.src = thumbUrl;
  8954. thumbnail.append(avatar);
  8955. }
  8956. }
  8957. };
  8958. module.exports = SmallVideo;
  8959. },{"../../RTC/RTCBrowserType":10,"../avatar/Avatar":18,"../util/UIUtil":35,"./LargeVideo":37}],41:[function(require,module,exports){
  8960. /* global config, APP, $, Strophe, require, interfaceConfig */
  8961. var AudioLevels = require("../audio_levels/AudioLevels");
  8962. var ContactList = require("../side_pannels/contactlist/ContactList");
  8963. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8964. var UIEvents = require("../../../service/UI/UIEvents");
  8965. var UIUtil = require("../util/UIUtil");
  8966. var RTC = require("../../RTC/RTC");
  8967. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8968. var RemoteVideo = require("./RemoteVideo");
  8969. var LargeVideo = require("./LargeVideo");
  8970. var LocalVideo = require("./LocalVideo");
  8971. var remoteVideos = {};
  8972. var remoteVideoTypes = {};
  8973. var localVideoThumbnail = null;
  8974. var currentDominantSpeaker = null;
  8975. var lastNCount = config.channelLastN;
  8976. var localLastNCount = config.channelLastN;
  8977. var localLastNSet = [];
  8978. var lastNEndpointsCache = [];
  8979. var lastNPickupJid = null;
  8980. var eventEmitter = null;
  8981. /**
  8982. * Currently focused video jid
  8983. * @type {String}
  8984. */
  8985. var focusedVideoResourceJid = null;
  8986. var VideoLayout = (function (my) {
  8987. my.init = function (emitter) {
  8988. eventEmitter = emitter;
  8989. localVideoThumbnail = new LocalVideo(VideoLayout);
  8990. if (interfaceConfig.filmStripOnly) {
  8991. LargeVideo.disable();
  8992. } else {
  8993. LargeVideo.init(VideoLayout, emitter);
  8994. }
  8995. VideoLayout.resizeLargeVideoContainer();
  8996. };
  8997. my.isInLastN = function(resource) {
  8998. return lastNCount < 0 || // lastN is disabled
  8999. // lastNEndpoints cache not built yet
  9000. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  9001. (lastNEndpointsCache &&
  9002. lastNEndpointsCache.indexOf(resource) !== -1);
  9003. };
  9004. my.changeLocalStream = function (stream, isMuted) {
  9005. VideoLayout.changeLocalVideo(stream, isMuted);
  9006. };
  9007. my.changeLocalAudio = function(stream, isMuted) {
  9008. if (isMuted)
  9009. APP.UI.setAudioMuted(true, true);
  9010. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  9011. var localAudio = document.getElementById('localAudio');
  9012. // Writing volume not allowed in IE
  9013. if (!RTCBrowserType.isIExplorer()) {
  9014. localAudio.autoplay = true;
  9015. localAudio.volume = 0;
  9016. }
  9017. // Now when Temasys plugin is converting also <audio> elements to
  9018. // plugin's <object>s, in current layout it will capture click events
  9019. // before it reaches the local video object. We hide it here in order
  9020. // to prevent that.
  9021. if (RTCBrowserType.isIExplorer()) {
  9022. // The issue is not present on Safari. Also if we hide it in Safari
  9023. // then the local audio track will have 'enabled' flag set to false
  9024. // which will result in audio mute issues
  9025. $('#localAudio').hide();
  9026. }
  9027. };
  9028. my.changeLocalVideo = function(stream, isMuted) {
  9029. // Set default display name.
  9030. localVideoThumbnail.setDisplayName();
  9031. localVideoThumbnail.createConnectionIndicator();
  9032. this.onVideoTypeChanged(APP.xmpp.myResource(), stream.videoType);
  9033. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  9034. localVideoThumbnail.changeVideo(stream, isMuted);
  9035. /* force update if we're currently being displayed */
  9036. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  9037. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  9038. }
  9039. };
  9040. my.mucJoined = function () {
  9041. var myResourceJid = APP.xmpp.myResource();
  9042. localVideoThumbnail.joined(APP.xmpp.myJid());
  9043. if (!LargeVideo.getResourceJid())
  9044. LargeVideo.updateLargeVideo(myResourceJid, true);
  9045. };
  9046. /**
  9047. * Adds or removes icons for not available camera and microphone.
  9048. * @param resourceJid the jid of user
  9049. * @param devices available devices
  9050. */
  9051. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  9052. if(!devices)
  9053. return;
  9054. if(!resourceJid) {
  9055. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  9056. } else {
  9057. if(remoteVideos[resourceJid])
  9058. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  9059. }
  9060. };
  9061. /**
  9062. * Checks if removed video is currently displayed and tries to display
  9063. * another one instead.
  9064. * @param removedVideoSrc src stream identifier of the video.
  9065. */
  9066. my.updateRemovedVideo = function(resourceJid) {
  9067. if (resourceJid === LargeVideo.getResourceJid()) {
  9068. var newResourceJid;
  9069. // We'll show user's avatar if he is the dominant speaker or if
  9070. // his video thumbnail is pinned
  9071. if (remoteVideos[resourceJid] &&
  9072. resourceJid === focusedVideoResourceJid ||
  9073. resourceJid === currentDominantSpeaker) {
  9074. newResourceJid = resourceJid;
  9075. } else {
  9076. // Otherwise select last visible video
  9077. newResourceJid = this.electLastVisibleVideo();
  9078. }
  9079. LargeVideo.updateLargeVideo(newResourceJid);
  9080. }
  9081. };
  9082. my.electLastVisibleVideo = function () {
  9083. // pick the last visible video in the row
  9084. // if nobody else is left, this picks the local video
  9085. var jid;
  9086. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last');
  9087. if (pick.length) {
  9088. jid = VideoLayout.getPeerContainerResourceJid(pick[0]);
  9089. } else {
  9090. console.info("Last visible video no longer exists");
  9091. pick = $('#remoteVideos>span[id!="mixedstream"]');
  9092. if (pick.length) {
  9093. jid = VideoLayout.getPeerContainerResourceJid(pick[0]);
  9094. }
  9095. if (!jid) {
  9096. // Go with local video
  9097. console.info("Fallback to local video...");
  9098. jid = APP.xmpp.myResource();
  9099. }
  9100. }
  9101. console.info("electLastVisibleVideo: " + jid);
  9102. return jid;
  9103. };
  9104. my.onRemoteStreamAdded = function (stream) {
  9105. if (stream.peerjid) {
  9106. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  9107. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  9108. remoteVideos[resourceJid].addRemoteStreamElement(
  9109. stream.sid,
  9110. stream.getOriginalStream(),
  9111. stream.ssrc);
  9112. }
  9113. };
  9114. my.getLargeVideoResource = function () {
  9115. return LargeVideo.getResourceJid();
  9116. };
  9117. /**
  9118. * Called when large video update is finished
  9119. * @param currentSmallVideo small video currently displayed on large video
  9120. */
  9121. my.largeVideoUpdated = function (currentSmallVideo) {
  9122. // Makes sure that dominant speaker UI
  9123. // is enabled only on current small video
  9124. localVideoThumbnail.enableDominantSpeaker(
  9125. localVideoThumbnail === currentSmallVideo);
  9126. Object.keys(remoteVideos).forEach(
  9127. function (resourceJid) {
  9128. var remoteVideo = remoteVideos[resourceJid];
  9129. if (remoteVideo) {
  9130. remoteVideo.enableDominantSpeaker(
  9131. remoteVideo === currentSmallVideo);
  9132. }
  9133. }
  9134. );
  9135. };
  9136. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  9137. resourceJid) {
  9138. if(focusedVideoResourceJid) {
  9139. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9140. if (oldSmallVideo && !interfaceConfig.filmStripOnly)
  9141. oldSmallVideo.focus(false);
  9142. }
  9143. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9144. // Unlock current focused.
  9145. if (focusedVideoResourceJid === resourceJid)
  9146. {
  9147. focusedVideoResourceJid = null;
  9148. // Enable the currently set dominant speaker.
  9149. if (currentDominantSpeaker) {
  9150. if(smallVideo && smallVideo.hasVideo()) {
  9151. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  9152. }
  9153. }
  9154. if (!noPinnedEndpointChangedEvent) {
  9155. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  9156. }
  9157. return;
  9158. }
  9159. // Lock new video
  9160. focusedVideoResourceJid = resourceJid;
  9161. // Update focused/pinned interface.
  9162. if (resourceJid) {
  9163. if (smallVideo && !interfaceConfig.filmStripOnly)
  9164. smallVideo.focus(true);
  9165. if (!noPinnedEndpointChangedEvent) {
  9166. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  9167. }
  9168. }
  9169. LargeVideo.setState("video");
  9170. LargeVideo.updateLargeVideo(resourceJid);
  9171. // Writing volume not allowed in IE
  9172. if (!RTCBrowserType.isIExplorer()) {
  9173. $('audio').each(function (idx, el) {
  9174. el.volume = 0;
  9175. el.volume = 1;
  9176. });
  9177. }
  9178. };
  9179. /**
  9180. * Checks if container for participant identified by given peerJid exists
  9181. * in the document and creates it eventually.
  9182. *
  9183. * @param peerJid peer Jid to check.
  9184. *
  9185. * @return Returns <tt>true</tt> if the peer container exists,
  9186. * <tt>false</tt> - otherwise
  9187. */
  9188. my.ensurePeerContainerExists = function(peerJid) {
  9189. ContactList.ensureAddContact(peerJid);
  9190. var resourceJid = Strophe.getResourceFromJid(peerJid);
  9191. if (!remoteVideos[resourceJid]) {
  9192. var remoteVideo = new RemoteVideo(peerJid, VideoLayout);
  9193. remoteVideos[resourceJid] = remoteVideo;
  9194. var videoType = remoteVideoTypes[resourceJid];
  9195. if (videoType) {
  9196. remoteVideo.setVideoType(videoType);
  9197. }
  9198. // In case this is not currently in the last n we don't show it.
  9199. if (localLastNCount &&
  9200. localLastNCount > 0 &&
  9201. $('#remoteVideos>span').length >= localLastNCount + 2) {
  9202. remoteVideo.showPeerContainer('hide');
  9203. }
  9204. else
  9205. VideoLayout.resizeThumbnails();
  9206. }
  9207. };
  9208. my.inputDisplayNameHandler = function (name) {
  9209. localVideoThumbnail.inputDisplayNameHandler(name);
  9210. };
  9211. my.videoactive = function (videoelem, resourceJid) {
  9212. console.info(resourceJid + " video is now active");
  9213. videoelem.show();
  9214. VideoLayout.resizeThumbnails();
  9215. // Update the large video to the last added video only if there's no
  9216. // current dominant, focused speaker or prezi playing or update it to
  9217. // the current dominant speaker.
  9218. if ((!focusedVideoResourceJid &&
  9219. !currentDominantSpeaker &&
  9220. !require("../prezi/Prezi").isPresentationVisible()) ||
  9221. focusedVideoResourceJid === resourceJid ||
  9222. (resourceJid &&
  9223. currentDominantSpeaker === resourceJid)) {
  9224. LargeVideo.updateLargeVideo(resourceJid, true);
  9225. }
  9226. };
  9227. /**
  9228. * Shows the presence status message for the given video.
  9229. */
  9230. my.setPresenceStatus = function (resourceJid, statusMsg) {
  9231. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  9232. };
  9233. /**
  9234. * Shows a visual indicator for the moderator of the conference.
  9235. */
  9236. my.showModeratorIndicator = function () {
  9237. var isModerator = APP.xmpp.isModerator();
  9238. if (isModerator) {
  9239. localVideoThumbnail.createModeratorIndicatorElement();
  9240. }
  9241. var members = APP.xmpp.getMembers();
  9242. Object.keys(members).forEach(function (jid) {
  9243. if (Strophe.getResourceFromJid(jid) === 'focus') {
  9244. // Skip server side focus
  9245. return;
  9246. }
  9247. var resourceJid = Strophe.getResourceFromJid(jid);
  9248. var member = members[jid];
  9249. if (member.role === 'moderator') {
  9250. remoteVideos[resourceJid].removeRemoteVideoMenu();
  9251. remoteVideos[resourceJid].createModeratorIndicatorElement();
  9252. } else if (isModerator) {
  9253. // We are moderator, but user is not - add menu
  9254. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  9255. remoteVideos[resourceJid].addRemoteVideoMenu();
  9256. }
  9257. }
  9258. });
  9259. };
  9260. /*
  9261. * Shows or hides the audio muted indicator over the local thumbnail video.
  9262. * @param {boolean} isMuted
  9263. */
  9264. my.showLocalAudioIndicator = function(isMuted) {
  9265. localVideoThumbnail.showAudioIndicator(isMuted);
  9266. };
  9267. /**
  9268. * Resizes the large video container.
  9269. */
  9270. my.resizeLargeVideoContainer = function () {
  9271. if(LargeVideo.isEnabled()) {
  9272. LargeVideo.resize();
  9273. } else {
  9274. VideoLayout.resizeVideoSpace();
  9275. }
  9276. VideoLayout.resizeThumbnails();
  9277. LargeVideo.position();
  9278. };
  9279. /**
  9280. * Resizes thumbnails.
  9281. */
  9282. my.resizeThumbnails = function(animate) {
  9283. var videoSpaceWidth = $('#remoteVideos').width();
  9284. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  9285. var width = thumbnailSize[0];
  9286. var height = thumbnailSize[1];
  9287. $('.userAvatar').css('left', (width - height) / 2);
  9288. if(animate) {
  9289. $('#remoteVideos').animate({
  9290. height: height + 2 // adds 2 px because of small video 1px border
  9291. },
  9292. {
  9293. queue: false,
  9294. duration: 500
  9295. });
  9296. $('#remoteVideos>span').animate({
  9297. height: height,
  9298. width: width
  9299. },
  9300. {
  9301. queue: false,
  9302. duration: 500,
  9303. complete: function () {
  9304. $(document).trigger(
  9305. "remotevideo.resized",
  9306. [width,
  9307. height]);
  9308. }
  9309. });
  9310. } else {
  9311. // size videos so that while keeping AR and max height, we have a
  9312. // nice fit
  9313. $('#remoteVideos').height(height + 2);// adds 2 px because of small video 1px border
  9314. $('#remoteVideos>span').width(width);
  9315. $('#remoteVideos>span').height(height);
  9316. $(document).trigger("remotevideo.resized", [width, height]);
  9317. }
  9318. };
  9319. /**
  9320. * Calculates the thumbnail size.
  9321. *
  9322. * @param videoSpaceWidth the width of the video space
  9323. */
  9324. my.calculateThumbnailSize = function (videoSpaceWidth) {
  9325. // Calculate the available height, which is the inner window height minus
  9326. // 39px for the header minus 2px for the delimiter lines on the top and
  9327. // bottom of the large video, minus the 36px space inside the remoteVideos
  9328. // container used for highlighting shadow.
  9329. var availableHeight = 100;
  9330. var numvids = $('#remoteVideos>span:visible').length;
  9331. if (localLastNCount && localLastNCount > 0) {
  9332. numvids = Math.min(localLastNCount + 1, numvids);
  9333. }
  9334. // Remove the 3px borders arround videos and border around the remote
  9335. // videos area and the 4 pixels between the local video and the others
  9336. //TODO: Find out where the 4 pixels come from and remove them
  9337. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  9338. var availableWidth = availableWinWidth / numvids;
  9339. var aspectRatio = 16.0 / 9.0;
  9340. var maxHeight = Math.min(160, availableHeight);
  9341. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio, window.innerHeight - 18);
  9342. if (availableHeight < availableWidth / aspectRatio) {
  9343. availableWidth = Math.floor(availableHeight * aspectRatio);
  9344. }
  9345. return [availableWidth, availableHeight];
  9346. };
  9347. /**
  9348. * Returns the corresponding resource jid to the given peer container
  9349. * DOM element.
  9350. *
  9351. * @return the corresponding resource jid to the given peer container
  9352. * DOM element
  9353. */
  9354. my.getPeerContainerResourceJid = function (containerElement) {
  9355. if (localVideoThumbnail.container === containerElement) {
  9356. return localVideoThumbnail.getResourceJid();
  9357. }
  9358. var i = containerElement.id.indexOf('participant_');
  9359. if (i >= 0)
  9360. return containerElement.id.substring(i + 12);
  9361. };
  9362. /**
  9363. * On contact list item clicked.
  9364. */
  9365. $(ContactList).bind('contactclicked', function(event, jid) {
  9366. if (!jid) {
  9367. return;
  9368. }
  9369. if (jid === APP.xmpp.myJid()) {
  9370. $("#localVideoContainer").click();
  9371. return;
  9372. }
  9373. var resource = Strophe.getResourceFromJid(jid);
  9374. var remoteVideo = remoteVideos[resource];
  9375. if (remoteVideo && remoteVideo.selectVideoElement().length) {
  9376. var videoThumb = remoteVideo.selectVideoElement()[0];
  9377. // It is not always the case that a videoThumb exists (if there is
  9378. // no actual video).
  9379. if (RTC.getVideoSrc(videoThumb)) {
  9380. // We have a video src, great! Let's update the large video
  9381. // now.
  9382. VideoLayout.handleVideoThumbClicked(
  9383. false,
  9384. Strophe.getResourceFromJid(jid));
  9385. } else {
  9386. // If we don't have a video src for jid, there's absolutely
  9387. // no point in calling handleVideoThumbClicked; Quite
  9388. // simply, it won't work because it needs an src to attach
  9389. // to the large video.
  9390. //
  9391. // Instead, we trigger the pinned endpoint changed event to
  9392. // let the bridge adjust its lastN set for myjid and store
  9393. // the pinned user in the lastNPickupJid variable to be
  9394. // picked up later by the lastN changed event handler.
  9395. lastNPickupJid = jid;
  9396. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  9397. Strophe.getResourceFromJid(jid));
  9398. }
  9399. }
  9400. });
  9401. /**
  9402. * On audio muted event.
  9403. */
  9404. my.onAudioMute = function (jid, isMuted) {
  9405. var resourceJid = Strophe.getResourceFromJid(jid);
  9406. if (resourceJid === APP.xmpp.myResource()) {
  9407. localVideoThumbnail.showAudioIndicator(isMuted);
  9408. } else {
  9409. VideoLayout.ensurePeerContainerExists(jid);
  9410. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9411. if (APP.xmpp.isModerator()) {
  9412. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9413. }
  9414. }
  9415. };
  9416. /**
  9417. * On video muted event.
  9418. */
  9419. my.onVideoMute = function (jid, value) {
  9420. if (jid !== APP.xmpp.myJid() &&
  9421. !APP.RTC.muteRemoteVideoStream(jid, value))
  9422. return;
  9423. if (jid === APP.xmpp.myJid()) {
  9424. localVideoThumbnail.showVideoIndicator(value);
  9425. } else {
  9426. var resource = Strophe.getResourceFromJid(jid);
  9427. VideoLayout.ensurePeerContainerExists(jid);
  9428. var remoteVideo = remoteVideos[resource];
  9429. remoteVideo.showVideoIndicator(value);
  9430. var el = remoteVideo.selectVideoElement();
  9431. if (!value)
  9432. el.show();
  9433. else
  9434. el.hide();
  9435. }
  9436. };
  9437. /**
  9438. * Display name changed.
  9439. */
  9440. my.onDisplayNameChanged =
  9441. function (jid, displayName, status) {
  9442. if (jid === 'localVideoContainer' ||
  9443. jid === APP.xmpp.myJid()) {
  9444. localVideoThumbnail.setDisplayName(displayName);
  9445. } else {
  9446. VideoLayout.ensurePeerContainerExists(jid);
  9447. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9448. displayName,
  9449. status);
  9450. }
  9451. };
  9452. /**
  9453. * On dominant speaker changed event.
  9454. */
  9455. my.onDominantSpeakerChanged = function (resourceJid) {
  9456. // We ignore local user events.
  9457. if (resourceJid === APP.xmpp.myResource())
  9458. return;
  9459. var remoteVideo = remoteVideos[resourceJid];
  9460. var members = APP.xmpp.getMembers();
  9461. // Update the current dominant speaker.
  9462. if (resourceJid !== currentDominantSpeaker) {
  9463. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9464. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9465. if (currentDominantSpeaker && (!members || !members[currentJID] ||
  9466. !members[currentJID].displayName) && remoteVideo) {
  9467. remoteVideo.setDisplayName(null);
  9468. }
  9469. if (resourceJid && (!members || !members[newJID] ||
  9470. !members[newJID].displayName) && remoteVideo) {
  9471. remoteVideo.setDisplayName(null,
  9472. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9473. }
  9474. currentDominantSpeaker = resourceJid;
  9475. } else {
  9476. return;
  9477. }
  9478. if (!remoteVideo)
  9479. return;
  9480. // Obtain container for new dominant speaker.
  9481. var videoSel = remoteVideo.selectVideoElement();
  9482. // Local video will not have container found, but that's ok
  9483. // since we don't want to switch to local video.
  9484. if (!focusedVideoResourceJid && videoSel.length) {
  9485. // Update the large video if the video source is already available,
  9486. // otherwise wait for the "videoactive.jingle" event.
  9487. if (videoSel[0].currentTime > 0) {
  9488. LargeVideo.updateLargeVideo(resourceJid);
  9489. }
  9490. }
  9491. };
  9492. /**
  9493. * On last N change event.
  9494. *
  9495. * @param lastNEndpoints the list of last N endpoints
  9496. * @param endpointsEnteringLastN the list currently entering last N
  9497. * endpoints
  9498. */
  9499. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9500. endpointsEnteringLastN,
  9501. stream) {
  9502. if (lastNCount !== lastNEndpoints.length)
  9503. lastNCount = lastNEndpoints.length;
  9504. lastNEndpointsCache = lastNEndpoints;
  9505. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9506. //
  9507. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9508. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9509. // so E sees them. C is only in E's local LastN set.
  9510. //
  9511. // If F starts talking and LastN = 3, then E should see thumbnails for
  9512. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9513. // enters E's local LastN ejecting C.
  9514. // Increase the local LastN set size, if necessary.
  9515. if (lastNCount > localLastNCount) {
  9516. localLastNCount = lastNCount;
  9517. }
  9518. // Update the local LastN set preserving the order in which the
  9519. // endpoints appeared in the LastN/local LastN set.
  9520. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9521. for (var i = 0; i < localLastNSet.length; i++) {
  9522. if (nextLocalLastNSet.length >= localLastNCount) {
  9523. break;
  9524. }
  9525. var resourceJid = localLastNSet[i];
  9526. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9527. nextLocalLastNSet.push(resourceJid);
  9528. }
  9529. }
  9530. localLastNSet = nextLocalLastNSet;
  9531. var updateLargeVideo = false;
  9532. // Handle LastN/local LastN changes.
  9533. $('#remoteVideos>span').each(function( index, element ) {
  9534. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9535. var isReceived = true;
  9536. if (resourceJid &&
  9537. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9538. localLastNSet.indexOf(resourceJid) < 0) {
  9539. console.log("Remove from last N", resourceJid);
  9540. if (remoteVideos[resourceJid])
  9541. remoteVideos[resourceJid].showPeerContainer('hide');
  9542. else if (APP.xmpp.myResource() !== resourceJid)
  9543. console.error("No remote video for: " + resourceJid);
  9544. isReceived = false;
  9545. } else if (resourceJid &&
  9546. $('#participant_' + resourceJid).is(':visible') &&
  9547. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9548. localLastNSet.indexOf(resourceJid) >= 0) {
  9549. if (remoteVideos[resourceJid])
  9550. remoteVideos[resourceJid].showPeerContainer('avatar');
  9551. else if (APP.xmpp.myResource() !== resourceJid)
  9552. console.error("No remote video for: " + resourceJid);
  9553. isReceived = false;
  9554. }
  9555. if (!isReceived) {
  9556. // resourceJid has dropped out of the server side lastN set, so
  9557. // it is no longer being received. If resourceJid was being
  9558. // displayed in the large video we have to switch to another
  9559. // user.
  9560. if (!updateLargeVideo &&
  9561. resourceJid === LargeVideo.getResourceJid()) {
  9562. updateLargeVideo = true;
  9563. }
  9564. }
  9565. });
  9566. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9567. endpointsEnteringLastN = lastNEndpoints;
  9568. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9569. endpointsEnteringLastN.forEach(function (resourceJid) {
  9570. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9571. var remoteVideo = remoteVideos[resourceJid];
  9572. remoteVideo.showPeerContainer('show');
  9573. if (!isVisible) {
  9574. console.log("Add to last N", resourceJid);
  9575. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9576. var mediaStream =
  9577. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9578. var sel = remoteVideo.selectVideoElement();
  9579. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9580. if (lastNPickupJid == mediaStream.peerjid) {
  9581. // Clean up the lastN pickup jid.
  9582. lastNPickupJid = null;
  9583. // Don't fire the events again, they've already
  9584. // been fired in the contact list click handler.
  9585. VideoLayout.handleVideoThumbClicked(
  9586. false,
  9587. Strophe.getResourceFromJid(mediaStream.peerjid));
  9588. updateLargeVideo = false;
  9589. }
  9590. remoteVideos[resourceJid].
  9591. waitForPlayback(sel, mediaStream.stream);
  9592. }
  9593. });
  9594. }
  9595. // The endpoint that was being shown in the large video has dropped out
  9596. // of the lastN set and there was no lastN pickup jid. We need to update
  9597. // the large video now.
  9598. if (updateLargeVideo) {
  9599. var resource;
  9600. var myResource
  9601. = APP.xmpp.myResource();
  9602. // Find out which endpoint to show in the large video.
  9603. for (i = 0; i < lastNEndpoints.length; i++) {
  9604. resource = lastNEndpoints[i];
  9605. if (!resource || resource === myResource)
  9606. continue;
  9607. // videoSrcToSsrc needs to be update for this call to succeed.
  9608. LargeVideo.updateLargeVideo(resource);
  9609. break;
  9610. }
  9611. }
  9612. };
  9613. /**
  9614. * Updates local stats
  9615. * @param percent
  9616. * @param object
  9617. */
  9618. my.updateLocalConnectionStats = function (percent, object) {
  9619. var resolution = null;
  9620. if (object.resolution !== null) {
  9621. resolution = object.resolution;
  9622. object.resolution = resolution[APP.xmpp.myJid()];
  9623. delete resolution[APP.xmpp.myJid()];
  9624. }
  9625. localVideoThumbnail.updateStatsIndicator(percent, object);
  9626. for (var jid in resolution) {
  9627. if (resolution[jid] === null)
  9628. continue;
  9629. var resourceJid = Strophe.getResourceFromJid(jid);
  9630. if (remoteVideos[resourceJid] &&
  9631. remoteVideos[resourceJid].connectionIndicator) {
  9632. remoteVideos[resourceJid].connectionIndicator.
  9633. updateResolution(resolution[jid]);
  9634. }
  9635. }
  9636. };
  9637. /**
  9638. * Updates remote stats.
  9639. * @param jid the jid associated with the stats
  9640. * @param percent the connection quality percent
  9641. * @param object the stats data
  9642. */
  9643. my.updateConnectionStats = function (jid, percent, object) {
  9644. var resourceJid = Strophe.getResourceFromJid(jid);
  9645. if (remoteVideos[resourceJid])
  9646. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9647. };
  9648. /**
  9649. * Hides the connection indicator
  9650. * @param jid
  9651. */
  9652. my.hideConnectionIndicator = function (jid) {
  9653. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9654. };
  9655. /**
  9656. * Hides all the indicators
  9657. */
  9658. my.onStatsStop = function () {
  9659. for(var video in remoteVideos) {
  9660. remoteVideos[video].hideIndicator();
  9661. }
  9662. localVideoThumbnail.hideIndicator();
  9663. };
  9664. my.participantLeft = function (jid) {
  9665. // Unlock large video
  9666. var resourceJid = Strophe.getResourceFromJid(jid);
  9667. if (focusedVideoResourceJid === resourceJid) {
  9668. console.info("Focused video owner has left the conference");
  9669. focusedVideoResourceJid = null;
  9670. }
  9671. if (currentDominantSpeaker === resourceJid)
  9672. {
  9673. console.info("Dominant speaker has left the conference");
  9674. currentDominantSpeaker = null;
  9675. }
  9676. var remoteVideo = remoteVideos[resourceJid];
  9677. if (remoteVideo) {
  9678. // Remove remote video
  9679. console.info("Removing remote video: " + resourceJid);
  9680. remoteVideo.remove();
  9681. delete remoteVideos[resourceJid];
  9682. } else {
  9683. console.warn("No remote video for " + resourceJid);
  9684. }
  9685. VideoLayout.resizeThumbnails();
  9686. };
  9687. my.onVideoTypeChanged = function (resourceJid, newVideoType) {
  9688. if (remoteVideoTypes[resourceJid] === newVideoType) {
  9689. return;
  9690. }
  9691. console.info("Peer video type changed: ", resourceJid, newVideoType);
  9692. remoteVideoTypes[resourceJid] = newVideoType;
  9693. var smallVideo;
  9694. if (resourceJid === APP.xmpp.myResource()) {
  9695. if (!localVideoThumbnail) {
  9696. console.warn("Local video not ready yet");
  9697. return;
  9698. }
  9699. smallVideo = localVideoThumbnail;
  9700. } else if (remoteVideos[resourceJid]) {
  9701. smallVideo = remoteVideos[resourceJid];
  9702. } else {
  9703. return;
  9704. }
  9705. smallVideo.setVideoType(newVideoType);
  9706. LargeVideo.onVideoTypeChanged(resourceJid, newVideoType);
  9707. };
  9708. my.showMore = function (jid) {
  9709. if (jid === 'local') {
  9710. localVideoThumbnail.connectionIndicator.showMore();
  9711. } else {
  9712. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9713. if (remoteVideo) {
  9714. remoteVideo.connectionIndicator.showMore();
  9715. } else {
  9716. console.info("Error - no remote video for jid: " + jid);
  9717. }
  9718. }
  9719. };
  9720. my.addPreziContainer = function (id) {
  9721. var container = RemoteVideo.createContainer(id);
  9722. VideoLayout.resizeThumbnails();
  9723. return container;
  9724. };
  9725. my.setLargeVideoVisible = function (isVisible) {
  9726. LargeVideo.setLargeVideoVisible(isVisible);
  9727. if(!isVisible && focusedVideoResourceJid) {
  9728. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9729. if(smallVideo) {
  9730. smallVideo.focus(false);
  9731. smallVideo.showAvatar();
  9732. }
  9733. focusedVideoResourceJid = null;
  9734. }
  9735. };
  9736. /**
  9737. * Resizes the video area
  9738. * @param callback a function to be called when the video space is
  9739. * resized.
  9740. */
  9741. my.resizeVideoArea = function(isVisible, callback) {
  9742. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9743. VideoLayout.resizeThumbnails(true);
  9744. };
  9745. /**
  9746. * Resizes the #videospace html element
  9747. * @param animate boolean property that indicates whether the resize should be animated or not.
  9748. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  9749. * If that parameter is null the method will check the chat pannel visibility.
  9750. * @param completeFunction a function to be called when the video space is resized
  9751. */
  9752. my.resizeVideoSpace = function (animate, isChatVisible, completeFunction) {
  9753. var availableHeight = window.innerHeight;
  9754. var availableWidth = UIUtil.getAvailableVideoWidth(isChatVisible);
  9755. if (availableWidth < 0 || availableHeight < 0) return;
  9756. if(animate) {
  9757. $('#videospace').animate({
  9758. right: window.innerWidth - availableWidth,
  9759. width: availableWidth,
  9760. height: availableHeight
  9761. },
  9762. {
  9763. queue: false,
  9764. duration: 500,
  9765. complete: completeFunction
  9766. });
  9767. } else {
  9768. $('#videospace').width(availableWidth);
  9769. $('#videospace').height(availableHeight);
  9770. }
  9771. };
  9772. my.getSmallVideo = function (resourceJid) {
  9773. if(resourceJid == APP.xmpp.myResource()) {
  9774. return localVideoThumbnail;
  9775. } else {
  9776. if(!remoteVideos[resourceJid])
  9777. return null;
  9778. return remoteVideos[resourceJid];
  9779. }
  9780. };
  9781. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9782. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9783. if(smallVideo)
  9784. smallVideo.avatarChanged(thumbUrl);
  9785. else
  9786. console.warn(
  9787. "Missed avatar update - no small video yet for " + resourceJid);
  9788. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9789. };
  9790. my.createEtherpadIframe = function(src, onloadHandler)
  9791. {
  9792. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9793. };
  9794. my.setLargeVideoState = function (state) {
  9795. LargeVideo.setState(state);
  9796. };
  9797. my.getLargeVideoState = function () {
  9798. return LargeVideo.getState();
  9799. };
  9800. my.setLargeVideoHover = function (inHandler, outHandler) {
  9801. LargeVideo.setHover(inHandler, outHandler);
  9802. };
  9803. /**
  9804. * Indicates that the video has been interrupted.
  9805. */
  9806. my.onVideoInterrupted = function () {
  9807. LargeVideo.enableVideoProblemFilter(true);
  9808. var reconnectingKey = "connection.RECONNECTING";
  9809. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9810. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9811. $('#videoConnectionMessage').css({display: "block"});
  9812. };
  9813. /**
  9814. * Indicates that the video has been restored.
  9815. */
  9816. my.onVideoRestored = function () {
  9817. LargeVideo.enableVideoProblemFilter(false);
  9818. $('#videoConnectionMessage').css({display: "none"});
  9819. };
  9820. return my;
  9821. }(VideoLayout || {}));
  9822. module.exports = VideoLayout;
  9823. },{"../../../service/RTC/MediaStreamTypes":164,"../../../service/UI/UIEvents":168,"../../RTC/RTC":9,"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../prezi/Prezi":20,"../side_pannels/contactlist/ContactList":27,"../util/UIUtil":35,"./LargeVideo":37,"./LocalVideo":38,"./RemoteVideo":39}],42:[function(require,module,exports){
  9824. //var nouns = [
  9825. //];
  9826. var pluralNouns = [
  9827. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9828. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9829. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9830. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9831. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9832. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9833. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9834. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9835. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9836. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9837. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9838. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9839. ];
  9840. //var places = [
  9841. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9842. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9843. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9844. // "Bridge"
  9845. //];
  9846. var verbs = [
  9847. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9848. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9849. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9850. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9851. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9852. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9853. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9854. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9855. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9856. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9857. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9858. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9859. ];
  9860. var adverbs = [
  9861. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9862. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9863. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9864. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9865. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9866. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9867. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9868. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9869. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9870. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9871. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9872. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9873. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9874. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9875. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9876. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9877. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9878. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9879. ];
  9880. var adjectives = [
  9881. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9882. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9883. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9884. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9885. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9886. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9887. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9888. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9889. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9890. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9891. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9892. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9893. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9894. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9895. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9896. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9897. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9898. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9899. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9900. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9901. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9902. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9903. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9904. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9905. "Zealous"
  9906. ];
  9907. //var pronouns = [
  9908. //];
  9909. //var conjunctions = [
  9910. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9911. //];
  9912. /*
  9913. * Maps a string (category name) to the array of words from that category.
  9914. */
  9915. var CATEGORIES =
  9916. {
  9917. //"_NOUN_": nouns,
  9918. "_PLURALNOUN_": pluralNouns,
  9919. //"_PLACE_": places,
  9920. "_VERB_": verbs,
  9921. "_ADVERB_": adverbs,
  9922. "_ADJECTIVE_": adjectives
  9923. //"_PRONOUN_": pronouns,
  9924. //"_CONJUNCTION_": conjunctions,
  9925. };
  9926. var PATTERNS = [
  9927. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9928. // BeautifulFungiOrSpaghetti
  9929. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9930. // AmazinglyScaryToy
  9931. //"_ADVERB__ADJECTIVE__NOUN_",
  9932. // NeitherTrashNorRifle
  9933. //"Neither_NOUN_Nor_NOUN_",
  9934. //"Either_NOUN_Or_NOUN_",
  9935. // EitherCopulateOrInvestigate
  9936. //"Either_VERB_Or_VERB_",
  9937. //"Neither_VERB_Nor_VERB_",
  9938. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9939. //"The_ADVERB__ADJECTIVE__NOUN_",
  9940. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9941. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9942. // WolvesComputeBadly
  9943. //"_PLURALNOUN__VERB__ADVERB_",
  9944. // UniteFacilitateAndMerge
  9945. //"_VERB__VERB_And_VERB_",
  9946. //NastyWitchesAtThePub
  9947. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9948. ];
  9949. /*
  9950. * Returns a random element from the array 'arr'
  9951. */
  9952. function randomElement(arr) {
  9953. return arr[Math.floor(Math.random() * arr.length)];
  9954. }
  9955. /*
  9956. * Returns true if the string 's' contains one of the
  9957. * template strings.
  9958. */
  9959. function hasTemplate(s) {
  9960. for (var template in CATEGORIES){
  9961. if (s.indexOf(template) >= 0){
  9962. return true;
  9963. }
  9964. }
  9965. }
  9966. /**
  9967. * Generates new room name.
  9968. */
  9969. var RoomNameGenerator = {
  9970. generateRoomWithoutSeparator: function() {
  9971. // Note that if more than one pattern is available, the choice of
  9972. // 'name' won't have a uniform distribution amongst all patterns (names
  9973. // from patterns with fewer options will have higher probability of
  9974. // being chosen that names from patterns with more options).
  9975. var name = randomElement(PATTERNS);
  9976. var word;
  9977. while (hasTemplate(name)) {
  9978. for (var template in CATEGORIES) {
  9979. word = randomElement(CATEGORIES[template]);
  9980. name = name.replace(template, word);
  9981. }
  9982. }
  9983. return name;
  9984. }
  9985. };
  9986. module.exports = RoomNameGenerator;
  9987. },{}],43:[function(require,module,exports){
  9988. /* global $, interfaceConfig */
  9989. var animateTimeout, updateTimeout;
  9990. var RoomNameGenerator = require("./RoomnameGenerator");
  9991. function enter_room() {
  9992. var val = $("#enter_room_field").val();
  9993. if(!val) {
  9994. val = $("#enter_room_field").attr("room_name");
  9995. }
  9996. if (val) {
  9997. window.location.pathname = "/" + val;
  9998. }
  9999. }
  10000. function animate(word) {
  10001. var currentVal = $("#enter_room_field").attr("placeholder");
  10002. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  10003. animateTimeout = setTimeout(function() {
  10004. animate(word.substring(1, word.length))
  10005. }, 70);
  10006. }
  10007. function update_roomname() {
  10008. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  10009. $("#enter_room_field").attr("room_name", word);
  10010. $("#enter_room_field").attr("placeholder", "");
  10011. clearTimeout(animateTimeout);
  10012. animate(word);
  10013. updateTimeout = setTimeout(update_roomname, 10000);
  10014. }
  10015. function setupWelcomePage() {
  10016. $("#videoconference_page").hide();
  10017. $("#domain_name").text(
  10018. window.location.protocol + "//" + window.location.host + "/");
  10019. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  10020. var leftWatermarkDiv =
  10021. $("#welcome_page_header div[class='watermark leftwatermark']");
  10022. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  10023. leftWatermarkDiv.css({display: 'block'});
  10024. leftWatermarkDiv.parent().get(0).href =
  10025. interfaceConfig.JITSI_WATERMARK_LINK;
  10026. }
  10027. }
  10028. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  10029. var rightWatermarkDiv =
  10030. $("#welcome_page_header div[class='watermark rightwatermark']");
  10031. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  10032. rightWatermarkDiv.css({display: 'block'});
  10033. rightWatermarkDiv.parent().get(0).href =
  10034. interfaceConfig.BRAND_WATERMARK_LINK;
  10035. rightWatermarkDiv.get(0).style.backgroundImage =
  10036. "url(images/rightwatermark.png)";
  10037. }
  10038. }
  10039. if (interfaceConfig.SHOW_POWERED_BY) {
  10040. $("#welcome_page_header>a[class='poweredby']")
  10041. .css({display: 'block'});
  10042. }
  10043. $("#enter_room_button").click(function() {
  10044. enter_room();
  10045. });
  10046. $("#enter_room_field").keydown(function (event) {
  10047. if (event.keyCode === 13 /* enter */) {
  10048. enter_room();
  10049. }
  10050. });
  10051. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  10052. var updateTimeout;
  10053. var animateTimeout;
  10054. var selector = $("#reload_roomname");
  10055. selector.click(function () {
  10056. clearTimeout(updateTimeout);
  10057. clearTimeout(animateTimeout);
  10058. update_roomname();
  10059. });
  10060. selector.show();
  10061. update_roomname();
  10062. }
  10063. $("#disable_welcome").click(function () {
  10064. window.localStorage.welcomePageDisabled =
  10065. $("#disable_welcome").is(":checked");
  10066. });
  10067. }
  10068. module.exports = setupWelcomePage;
  10069. },{"./RoomnameGenerator":42}],44:[function(require,module,exports){
  10070. /* global $, $iq, config, interfaceConfig */
  10071. var configUtil = require('./Util');
  10072. var HttpConfig = {
  10073. /**
  10074. * Sends HTTP POST request to specified <tt>endpoint</tt>. In request
  10075. * the name of the room is included in JSON format:
  10076. * {
  10077. * "rooomName": "someroom12345"
  10078. * }
  10079. * @param endpoint the name of HTTP endpoint to which HTTP POST request will
  10080. * be sent.
  10081. * @param roomName the name of the conference room for which config will be
  10082. * requested.
  10083. * @param complete
  10084. */
  10085. obtainConfig: function (endpoint, roomName, complete) {
  10086. console.info(
  10087. "Send config request to " + endpoint + " for room: " + roomName);
  10088. $.ajax(
  10089. endpoint,
  10090. {
  10091. method: 'POST',
  10092. contentType: 'application/json',
  10093. data: JSON.stringify({"roomName": roomName}),
  10094. dataType: 'json',
  10095. error: function(jqXHR, textStatus, errorThrown) {
  10096. console.error("Get config error: ", jqXHR, errorThrown)
  10097. error = "Get config response status: " + textStatus;
  10098. complete(false, error);
  10099. },
  10100. success: function(data, textStatus, jqXHR) {
  10101. try {
  10102. configUtil.overrideConfigJSON(
  10103. config, interfaceConfig, data);
  10104. complete(true);
  10105. return;
  10106. } catch (exception) {
  10107. console.error("Parse config error: ", exception);
  10108. error = exception;
  10109. complete(false, error);
  10110. }
  10111. }
  10112. }
  10113. );
  10114. }
  10115. };
  10116. module.exports = HttpConfig;
  10117. },{"./Util":46}],45:[function(require,module,exports){
  10118. /* global $, $iq, config, interfaceConfig */
  10119. var configUtils = require('./Util');
  10120. var params = {};
  10121. function getConfigParamsFromUrl() {
  10122. if (!location.hash)
  10123. return {};
  10124. var hash = location.hash.substr(1);
  10125. var result = {};
  10126. hash.split("&").forEach(function (part) {
  10127. var item = part.split("=");
  10128. result[item[0]] = JSON.parse(
  10129. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  10130. });
  10131. return result;
  10132. }
  10133. params = getConfigParamsFromUrl();
  10134. var URLProcessor = {
  10135. setConfigParametersFromUrl: function () {
  10136. // Convert 'params' to JSON object
  10137. // We have:
  10138. // {
  10139. // "config.disableAudioLevels": false,
  10140. // "config.channelLastN": -1,
  10141. // "interfaceConfig.APP_NAME": "Jitsi Meet"
  10142. // }
  10143. // We want to have:
  10144. // {
  10145. // "config": {
  10146. // "disableAudioLevels": false,
  10147. // "channelLastN": -1
  10148. // },
  10149. // interfaceConfig: {
  10150. // APP_NAME: "Jitsi Meet"
  10151. // }
  10152. // }
  10153. var configJSON = {
  10154. config: {},
  10155. interfaceConfig: {}
  10156. };
  10157. for (var key in params) {
  10158. if (typeof key !== "string") {
  10159. console.warn("Invalid config key: ", key);
  10160. continue;
  10161. }
  10162. var confObj = null, confKey;
  10163. if (key.indexOf("config.") === 0) {
  10164. confObj = configJSON.config;
  10165. confKey = key.substr("config.".length);
  10166. } else if (key.indexOf("interfaceConfig.") === 0) {
  10167. confObj = configJSON.interfaceConfig;
  10168. confKey = key.substr("interfaceConfig.".length);
  10169. }
  10170. if (!confObj)
  10171. continue;
  10172. confObj[confKey] = params[key];
  10173. }
  10174. configUtils.overrideConfigJSON(config, interfaceConfig, configJSON);
  10175. }
  10176. };
  10177. module.exports = URLProcessor;
  10178. },{"./Util":46}],46:[function(require,module,exports){
  10179. /* global $ */
  10180. var ConfigUtil = {
  10181. /**
  10182. * Method overrides JSON properties in <tt>config</tt> and
  10183. * <tt>interfaceConfig</tt> Objects with the values from <tt>newConfig</tt>
  10184. * @param config the config object for which we'll be overriding properties
  10185. * @param interfaceConfig the interfaceConfig object for which we'll be
  10186. * overriding properties.
  10187. * @param newConfig object containing configuration properties. Destination
  10188. * object is selected based on root property name:
  10189. * {
  10190. * config: {
  10191. * // config.js properties to be
  10192. * },
  10193. * interfaceConfig: {
  10194. * // interfaceConfig.js properties here
  10195. * }
  10196. * }
  10197. */
  10198. overrideConfigJSON: function (config, interfaceConfig, newConfig) {
  10199. for (var configRoot in newConfig) {
  10200. var confObj = null;
  10201. if (configRoot == "config") {
  10202. confObj = config;
  10203. } else if (configRoot == "interfaceConfig") {
  10204. confObj = interfaceConfig;
  10205. } else {
  10206. continue;
  10207. }
  10208. for (var key in newConfig[configRoot]) {
  10209. var value = newConfig[configRoot][key];
  10210. if (confObj[key] && typeof confObj[key] !== typeof value)
  10211. {
  10212. console.warn(
  10213. "The type of " + key +
  10214. " is wrong. That parameter won't be updated in: ",
  10215. confObj);
  10216. continue;
  10217. }
  10218. console.info("Overriding " + key + " with: " + value);
  10219. confObj[key] = value;
  10220. }
  10221. }
  10222. }
  10223. };
  10224. module.exports = ConfigUtil;
  10225. },{}],47:[function(require,module,exports){
  10226. /* global APP, require */
  10227. var EventEmitter = require("events");
  10228. var eventEmitter = new EventEmitter();
  10229. var CQEvents = require("../../service/connectionquality/CQEvents");
  10230. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10231. /**
  10232. * local stats
  10233. * @type {{}}
  10234. */
  10235. var stats = {};
  10236. /**
  10237. * remote stats
  10238. * @type {{}}
  10239. */
  10240. var remoteStats = {};
  10241. /**
  10242. * Interval for sending statistics to other participants
  10243. * @type {null}
  10244. */
  10245. var sendIntervalId = null;
  10246. /**
  10247. * Start statistics sending.
  10248. */
  10249. function startSendingStats() {
  10250. sendStats();
  10251. sendIntervalId = setInterval(sendStats, 10000);
  10252. }
  10253. /**
  10254. * Sends statistics to other participants
  10255. */
  10256. function sendStats() {
  10257. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  10258. }
  10259. /**
  10260. * Converts statistics to format for sending through XMPP
  10261. * @param stats the statistics
  10262. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  10263. */
  10264. function convertToMUCStats(stats) {
  10265. return {
  10266. "bitrate_download": stats.bitrate.download,
  10267. "bitrate_upload": stats.bitrate.upload,
  10268. "packetLoss_total": stats.packetLoss.total,
  10269. "packetLoss_download": stats.packetLoss.download,
  10270. "packetLoss_upload": stats.packetLoss.upload
  10271. };
  10272. }
  10273. /**
  10274. * Converts statistics to format used by VideoLayout
  10275. * @param stats
  10276. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  10277. */
  10278. function parseMUCStats(stats) {
  10279. return {
  10280. bitrate: {
  10281. download: stats.bitrate_download,
  10282. upload: stats.bitrate_upload
  10283. },
  10284. packetLoss: {
  10285. total: stats.packetLoss_total,
  10286. download: stats.packetLoss_download,
  10287. upload: stats.packetLoss_upload
  10288. }
  10289. };
  10290. }
  10291. var ConnectionQuality = {
  10292. init: function () {
  10293. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  10294. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  10295. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  10296. },
  10297. /**
  10298. * Updates the local statistics
  10299. * @param data new statistics
  10300. */
  10301. updateLocalStats: function (data) {
  10302. stats = data;
  10303. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  10304. if (sendIntervalId == null) {
  10305. startSendingStats();
  10306. }
  10307. },
  10308. /**
  10309. * Updates remote statistics
  10310. * @param jid the jid associated with the statistics
  10311. * @param data the statistics
  10312. */
  10313. updateRemoteStats: function (jid, data) {
  10314. if (data == null || data.packetLoss_total == null) {
  10315. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  10316. return;
  10317. }
  10318. remoteStats[jid] = parseMUCStats(data);
  10319. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  10320. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  10321. },
  10322. /**
  10323. * Stops statistics sending.
  10324. */
  10325. stopSendingStats: function () {
  10326. clearInterval(sendIntervalId);
  10327. sendIntervalId = null;
  10328. //notify UI about stopping statistics gathering
  10329. eventEmitter.emit(CQEvents.STOP);
  10330. },
  10331. /**
  10332. * Returns the local statistics.
  10333. */
  10334. getStats: function () {
  10335. return stats;
  10336. },
  10337. addListener: function (type, listener) {
  10338. eventEmitter.on(type, listener);
  10339. }
  10340. };
  10341. module.exports = ConnectionQuality;
  10342. },{"../../service/connectionquality/CQEvents":170,"../../service/xmpp/XMPPEvents":174,"events":1}],48:[function(require,module,exports){
  10343. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  10344. getUserMediaWithConstraints */
  10345. /**
  10346. * Indicates that desktop stream is currently in use(for toggle purpose).
  10347. * @type {boolean}
  10348. */
  10349. var isUsingScreenStream = false;
  10350. /**
  10351. * Indicates that switch stream operation is in progress and prevent from
  10352. * triggering new events.
  10353. * @type {boolean}
  10354. */
  10355. var switchInProgress = false;
  10356. /**
  10357. * Method used to get screen sharing stream.
  10358. *
  10359. * @type {function (stream_callback, failure_callback}
  10360. */
  10361. var obtainDesktopStream = null;
  10362. /**
  10363. * Indicates whether desktop sharing extension is installed.
  10364. * @type {boolean}
  10365. */
  10366. var extInstalled = false;
  10367. /**
  10368. * Indicates whether update of desktop sharing extension is required.
  10369. * @type {boolean}
  10370. */
  10371. var extUpdateRequired = false;
  10372. var AdapterJS = require("../RTC/adapter.screenshare");
  10373. var EventEmitter = require("events");
  10374. var eventEmitter = new EventEmitter();
  10375. var DesktopSharingEventTypes
  10376. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  10377. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10378. var RTCEvents = require("../../service/RTC/RTCEvents");
  10379. /**
  10380. * Method obtains desktop stream from WebRTC 'screen' source.
  10381. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  10382. */
  10383. function obtainWebRTCScreen(streamCallback, failCallback) {
  10384. APP.RTC.getUserMediaWithConstraints(
  10385. ['screen'],
  10386. streamCallback,
  10387. failCallback
  10388. );
  10389. }
  10390. /**
  10391. * Constructs inline install URL for Chrome desktop streaming extension.
  10392. * The 'chromeExtensionId' must be defined in config.js.
  10393. * @returns {string}
  10394. */
  10395. function getWebStoreInstallUrl()
  10396. {
  10397. return "https://chrome.google.com/webstore/detail/" +
  10398. config.chromeExtensionId;
  10399. }
  10400. /**
  10401. * Checks whether extension update is required.
  10402. * @param minVersion minimal required version
  10403. * @param extVersion current extension version
  10404. * @returns {boolean}
  10405. */
  10406. function isUpdateRequired(minVersion, extVersion)
  10407. {
  10408. try
  10409. {
  10410. var s1 = minVersion.split('.');
  10411. var s2 = extVersion.split('.');
  10412. var len = Math.max(s1.length, s2.length);
  10413. for (var i = 0; i < len; i++)
  10414. {
  10415. var n1 = 0,
  10416. n2 = 0;
  10417. if (i < s1.length)
  10418. n1 = parseInt(s1[i]);
  10419. if (i < s2.length)
  10420. n2 = parseInt(s2[i]);
  10421. if (isNaN(n1) || isNaN(n2))
  10422. {
  10423. return true;
  10424. }
  10425. else if (n1 !== n2)
  10426. {
  10427. return n1 > n2;
  10428. }
  10429. }
  10430. // will happen if boths version has identical numbers in
  10431. // their components (even if one of them is longer, has more components)
  10432. return false;
  10433. }
  10434. catch (e)
  10435. {
  10436. console.error("Failed to parse extension version", e);
  10437. APP.UI.messageHandler.showError("dialog.error",
  10438. "dialog.detectext");
  10439. return true;
  10440. }
  10441. }
  10442. function checkChromeExtInstalled(callback) {
  10443. if (!chrome.runtime) {
  10444. // No API, so no extension for sure
  10445. callback(false, false);
  10446. return;
  10447. }
  10448. chrome.runtime.sendMessage(
  10449. config.chromeExtensionId,
  10450. { getVersion: true },
  10451. function (response) {
  10452. if (!response || !response.version) {
  10453. // Communication failure - assume that no endpoint exists
  10454. console.warn(
  10455. "Extension not installed?: ", chrome.runtime.lastError);
  10456. callback(false, false);
  10457. return;
  10458. }
  10459. // Check installed extension version
  10460. var extVersion = response.version;
  10461. console.log('Extension version is: ' + extVersion);
  10462. var updateRequired
  10463. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  10464. callback(!updateRequired, updateRequired);
  10465. }
  10466. );
  10467. }
  10468. function doGetStreamFromExtension(streamCallback, failCallback) {
  10469. // Sends 'getStream' msg to the extension.
  10470. // Extension id must be defined in the config.
  10471. chrome.runtime.sendMessage(
  10472. config.chromeExtensionId,
  10473. { getStream: true, sources: config.desktopSharingSources },
  10474. function (response) {
  10475. if (!response) {
  10476. failCallback(chrome.runtime.lastError);
  10477. return;
  10478. }
  10479. console.log("Response from extension: " + response);
  10480. if (response.streamId) {
  10481. APP.RTC.getUserMediaWithConstraints(
  10482. ['desktop'],
  10483. function (stream) {
  10484. streamCallback(stream);
  10485. },
  10486. failCallback,
  10487. null, null, null,
  10488. response.streamId);
  10489. } else {
  10490. failCallback("Extension failed to get the stream");
  10491. }
  10492. }
  10493. );
  10494. }
  10495. /**
  10496. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  10497. * stream for returned stream token.
  10498. */
  10499. function obtainScreenFromExtension(streamCallback, failCallback) {
  10500. if (extInstalled) {
  10501. doGetStreamFromExtension(streamCallback, failCallback);
  10502. } else {
  10503. if (extUpdateRequired) {
  10504. alert(
  10505. 'Jitsi Desktop Streamer requires update. ' +
  10506. 'Changes will take effect after next Chrome restart.');
  10507. }
  10508. chrome.webstore.install(
  10509. getWebStoreInstallUrl(),
  10510. function (arg) {
  10511. console.log("Extension installed successfully", arg);
  10512. extInstalled = true;
  10513. // We need to give a moment for the endpoint to become available
  10514. window.setTimeout(function () {
  10515. doGetStreamFromExtension(streamCallback, failCallback);
  10516. }, 500);
  10517. },
  10518. function (arg) {
  10519. console.log("Failed to install the extension", arg);
  10520. failCallback(arg);
  10521. APP.UI.messageHandler.showError("dialog.error",
  10522. "dialog.failtoinstall");
  10523. }
  10524. );
  10525. }
  10526. }
  10527. /**
  10528. * Call this method to toggle desktop sharing feature.
  10529. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  10530. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  10531. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  10532. * enabled), pass any other string or nothing in order to disable this
  10533. * feature completely.
  10534. */
  10535. function setDesktopSharing(method) {
  10536. obtainDesktopStream = null;
  10537. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  10538. // care about 'method' parameter
  10539. if (RTCBrowserType.isTemasysPluginUsed()) {
  10540. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  10541. console.info("Screensharing not supported by this plugin version");
  10542. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  10543. console.info(
  10544. "Screensharing not available with Temasys plugin on this site");
  10545. } else {
  10546. obtainDesktopStream = obtainWebRTCScreen;
  10547. console.info("Using Temasys plugin for desktop sharing");
  10548. }
  10549. } else if (RTCBrowserType.isChrome()) {
  10550. if (method == "ext") {
  10551. if (RTCBrowserType.getChromeVersion() >= 34) {
  10552. obtainDesktopStream = obtainScreenFromExtension;
  10553. console.info("Using Chrome extension for desktop sharing");
  10554. initChromeExtension();
  10555. } else {
  10556. console.info("Chrome extension not supported until ver 34");
  10557. }
  10558. } else if (method == "webrtc") {
  10559. obtainDesktopStream = obtainWebRTCScreen;
  10560. console.info("Using Chrome WebRTC for desktop sharing");
  10561. }
  10562. }
  10563. if (!obtainDesktopStream) {
  10564. console.info("Desktop sharing disabled");
  10565. }
  10566. }
  10567. /**
  10568. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10569. * config.js to support inline installs. Host site must be selected as main
  10570. * website of published extension.
  10571. */
  10572. function initInlineInstalls()
  10573. {
  10574. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10575. }
  10576. function initChromeExtension() {
  10577. // Initialize Chrome extension inline installs
  10578. initInlineInstalls();
  10579. // Check if extension is installed
  10580. checkChromeExtInstalled(function (installed, updateRequired) {
  10581. extInstalled = installed;
  10582. extUpdateRequired = updateRequired;
  10583. console.info(
  10584. "Chrome extension installed: " + extInstalled +
  10585. " updateRequired: " + extUpdateRequired);
  10586. });
  10587. }
  10588. function getVideoStreamFailed(error) {
  10589. console.error("Failed to obtain the stream to switch to", error);
  10590. switchInProgress = false;
  10591. isUsingScreenStream = false;
  10592. newStreamCreated(null);
  10593. }
  10594. function getDesktopStreamFailed(error) {
  10595. console.error("Failed to obtain the stream to switch to", error);
  10596. switchInProgress = false;
  10597. }
  10598. function streamSwitchDone() {
  10599. switchInProgress = false;
  10600. eventEmitter.emit(
  10601. DesktopSharingEventTypes.SWITCHING_DONE,
  10602. isUsingScreenStream);
  10603. }
  10604. function newStreamCreated(stream)
  10605. {
  10606. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10607. stream, isUsingScreenStream, streamSwitchDone);
  10608. }
  10609. function onEndedHandler(stream) {
  10610. if (!switchInProgress && isUsingScreenStream) {
  10611. APP.desktopsharing.toggleScreenSharing();
  10612. }
  10613. //FIXME: to be verified
  10614. if (stream.removeEventListener) {
  10615. stream.removeEventListener('ended', onEndedHandler);
  10616. } else {
  10617. stream.detachEvent('ended', onEndedHandler);
  10618. }
  10619. }
  10620. // Called when RTC finishes initialization
  10621. function onWebRtcReady() {
  10622. setDesktopSharing(config.desktopSharing);
  10623. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10624. }
  10625. module.exports = {
  10626. isUsingScreenStream: function () {
  10627. return isUsingScreenStream;
  10628. },
  10629. /**
  10630. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10631. * and enabled.
  10632. */
  10633. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10634. init: function () {
  10635. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10636. },
  10637. addListener: function (listener, type)
  10638. {
  10639. eventEmitter.on(type, listener);
  10640. },
  10641. removeListener: function (listener, type) {
  10642. eventEmitter.removeListener(type, listener);
  10643. },
  10644. /*
  10645. * Toggles screen sharing.
  10646. */
  10647. toggleScreenSharing: function () {
  10648. if (switchInProgress || !obtainDesktopStream) {
  10649. console.warn("Switch in progress or no method defined");
  10650. return;
  10651. }
  10652. switchInProgress = true;
  10653. if (!isUsingScreenStream)
  10654. {
  10655. // Switch to desktop stream
  10656. obtainDesktopStream(
  10657. function (stream) {
  10658. // We now use screen stream
  10659. isUsingScreenStream = true;
  10660. // Hook 'ended' event to restore camera
  10661. // when screen stream stops
  10662. //FIXME: to be verified
  10663. if (stream.addEventListener) {
  10664. stream.addEventListener('ended', function () {
  10665. onEndedHandler(stream);
  10666. });
  10667. } else {
  10668. stream.attachEvent('ended', function () {
  10669. onEndedHandler(stream);
  10670. });
  10671. }
  10672. newStreamCreated(stream);
  10673. },
  10674. getDesktopStreamFailed);
  10675. } else {
  10676. // Disable screen stream
  10677. APP.RTC.getUserMediaWithConstraints(
  10678. ['video'],
  10679. function (stream) {
  10680. // We are now using camera stream
  10681. isUsingScreenStream = false;
  10682. newStreamCreated(stream);
  10683. },
  10684. getVideoStreamFailed, config.resolution || '360'
  10685. );
  10686. }
  10687. }
  10688. };
  10689. },{"../../service/RTC/RTCEvents":165,"../../service/desktopsharing/DesktopSharingEventTypes":171,"../RTC/RTCBrowserType":10,"../RTC/adapter.screenshare":12,"events":1}],49:[function(require,module,exports){
  10690. /* global APP, $ */
  10691. //maps keycode to character, id of popover for given function and function
  10692. var shortcuts = {};
  10693. function initShortcutHandlers() {
  10694. shortcuts = {
  10695. 67: {
  10696. character: "C",
  10697. id: "toggleChatPopover",
  10698. function: APP.UI.toggleChat
  10699. },
  10700. 70: {
  10701. character: "F",
  10702. id: "filmstripPopover",
  10703. function: APP.UI.toggleFilmStrip
  10704. },
  10705. 77: {
  10706. character: "M",
  10707. id: "mutePopover",
  10708. function: APP.UI.toggleAudio
  10709. },
  10710. 84: {
  10711. character: "T",
  10712. function: function() {
  10713. if(!APP.RTC.localAudio.isMuted()) {
  10714. APP.UI.toggleAudio();
  10715. }
  10716. }
  10717. },
  10718. 86: {
  10719. character: "V",
  10720. id: "toggleVideoPopover",
  10721. function: APP.UI.toggleVideo
  10722. }
  10723. };
  10724. }
  10725. var KeyboardShortcut = {
  10726. init: function () {
  10727. initShortcutHandlers();
  10728. window.onkeyup = function(e) {
  10729. var keycode = e.which;
  10730. if(!($(":focus").is("input[type=text]") ||
  10731. $(":focus").is("input[type=password]") ||
  10732. $(":focus").is("textarea"))) {
  10733. if (typeof shortcuts[keycode] === "object") {
  10734. shortcuts[keycode].function();
  10735. }
  10736. else if (keycode >= "0".charCodeAt(0) &&
  10737. keycode <= "9".charCodeAt(0)) {
  10738. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10739. }
  10740. //esc while the smileys are visible hides them
  10741. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10742. APP.UI.toggleSmileys();
  10743. }
  10744. };
  10745. window.onkeydown = function(e) {
  10746. if(!($(":focus").is("input[type=text]") ||
  10747. $(":focus").is("input[type=password]") ||
  10748. $(":focus").is("textarea"))) {
  10749. if(e.which === "T".charCodeAt(0)) {
  10750. if(APP.RTC.localAudio.isMuted()) {
  10751. APP.UI.toggleAudio();
  10752. }
  10753. }
  10754. }
  10755. };
  10756. var self = this;
  10757. $('body').popover({ selector: '[data-toggle=popover]',
  10758. trigger: 'click hover',
  10759. content: function() {
  10760. return this.getAttribute("content") +
  10761. self.getShortcut(this.getAttribute("shortcut"));
  10762. }
  10763. });
  10764. },
  10765. /**
  10766. *
  10767. * @param id indicates the popover associated with the shortcut
  10768. * @returns {string} the keyboard shortcut used for the id given
  10769. */
  10770. getShortcut: function (id) {
  10771. for (var keycode in shortcuts) {
  10772. if (shortcuts.hasOwnProperty(keycode)) {
  10773. if (shortcuts[keycode].id === id) {
  10774. return " (" + shortcuts[keycode].character + ")";
  10775. }
  10776. }
  10777. }
  10778. return "";
  10779. }
  10780. };
  10781. module.exports = KeyboardShortcut;
  10782. },{}],50:[function(require,module,exports){
  10783. /* global APP, require, $ */
  10784. /**
  10785. * This module is meant to (eventually) contain and manage all information
  10786. * about members/participants of the conference, so that other modules don't
  10787. * have to do it on their own, and so that other modules can access members'
  10788. * information from a single place.
  10789. *
  10790. * Currently this module only manages information about the support of jingle
  10791. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10792. * be added as needed.
  10793. */
  10794. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10795. var Events = require("../../service/members/Events");
  10796. var EventEmitter = require("events");
  10797. var eventEmitter = new EventEmitter();
  10798. /**
  10799. * The actual container.
  10800. */
  10801. var members = {};
  10802. /**
  10803. * There is at least one member that supports DTMF (i.e. is jigasi).
  10804. */
  10805. var atLeastOneDtmf = false;
  10806. function registerListeners() {
  10807. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10808. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10809. }
  10810. /**
  10811. * Handles a new member joining the MUC.
  10812. */
  10813. function onMucMemberJoined(jid, id, displayName) {
  10814. var member = {
  10815. displayName: displayName
  10816. };
  10817. APP.xmpp.getConnection().disco.info(
  10818. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10819. members[jid] = member;
  10820. }
  10821. /**
  10822. * Handles a member leaving the MUC.
  10823. */
  10824. function onMucMemberLeft(jid) {
  10825. delete members[jid];
  10826. updateAtLeastOneDtmf();
  10827. }
  10828. /**
  10829. * Handles the reception of a disco#info packet from a particular JID.
  10830. * @param jid the JID sending the packet.
  10831. * @param iq the packet.
  10832. */
  10833. function onDiscoInfoReceived(jid, iq) {
  10834. if (!members[jid])
  10835. return;
  10836. var supportsDtmf
  10837. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10838. updateDtmf(jid, supportsDtmf);
  10839. }
  10840. /**
  10841. * Updates the 'supportsDtmf' field for a member.
  10842. * @param jid the jid of the member.
  10843. * @param newValue the new value for the 'supportsDtmf' field.
  10844. */
  10845. function updateDtmf(jid, newValue) {
  10846. var oldValue = members[jid].supportsDtmf;
  10847. members[jid].supportsDtmf = newValue;
  10848. if (newValue != oldValue) {
  10849. updateAtLeastOneDtmf();
  10850. }
  10851. }
  10852. /**
  10853. * Checks each member's 'supportsDtmf' field and updates
  10854. * 'atLastOneSupportsDtmf'.
  10855. */
  10856. function updateAtLeastOneDtmf() {
  10857. var newAtLeastOneDtmf = false;
  10858. for (var key in members) {
  10859. if (typeof members[key].supportsDtmf !== 'undefined'
  10860. && members[key].supportsDtmf) {
  10861. newAtLeastOneDtmf= true;
  10862. break;
  10863. }
  10864. }
  10865. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10866. atLeastOneDtmf = newAtLeastOneDtmf;
  10867. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10868. }
  10869. }
  10870. /**
  10871. * Exported interface.
  10872. */
  10873. var Members = {
  10874. start: function() {
  10875. registerListeners();
  10876. },
  10877. addListener: function(type, listener) {
  10878. eventEmitter.on(type, listener);
  10879. },
  10880. removeListener: function (type, listener) {
  10881. eventEmitter.removeListener(type, listener);
  10882. },
  10883. size: function () {
  10884. return Object.keys(members).length;
  10885. },
  10886. getMembers: function () {
  10887. return members;
  10888. }
  10889. };
  10890. module.exports = Members;
  10891. },{"../../service/members/Events":172,"../../service/xmpp/XMPPEvents":174,"events":1}],51:[function(require,module,exports){
  10892. var email = '';
  10893. var displayName = '';
  10894. var userId;
  10895. var language = null;
  10896. function supportsLocalStorage() {
  10897. try {
  10898. return 'localStorage' in window && window.localStorage !== null;
  10899. } catch (e) {
  10900. console.log("localstorage is not supported");
  10901. return false;
  10902. }
  10903. }
  10904. function generateUniqueId() {
  10905. function _p8() {
  10906. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10907. }
  10908. return _p8() + _p8() + _p8() + _p8();
  10909. }
  10910. if (supportsLocalStorage()) {
  10911. if (!window.localStorage.jitsiMeetId) {
  10912. window.localStorage.jitsiMeetId = generateUniqueId();
  10913. console.log("generated id", window.localStorage.jitsiMeetId);
  10914. }
  10915. userId = window.localStorage.jitsiMeetId || '';
  10916. email = window.localStorage.email || '';
  10917. displayName = window.localStorage.displayname || '';
  10918. language = window.localStorage.language;
  10919. } else {
  10920. console.log("local storage is not supported");
  10921. userId = generateUniqueId();
  10922. }
  10923. var Settings = {
  10924. setDisplayName: function (newDisplayName) {
  10925. displayName = newDisplayName;
  10926. window.localStorage.displayname = displayName;
  10927. return displayName;
  10928. },
  10929. setEmail: function (newEmail) {
  10930. email = newEmail;
  10931. window.localStorage.email = newEmail;
  10932. return email;
  10933. },
  10934. getSettings: function () {
  10935. return {
  10936. email: email,
  10937. displayName: displayName,
  10938. uid: userId,
  10939. language: language
  10940. };
  10941. },
  10942. setLanguage: function (lang) {
  10943. language = lang;
  10944. window.localStorage.language = lang;
  10945. }
  10946. };
  10947. module.exports = Settings;
  10948. },{}],52:[function(require,module,exports){
  10949. /* global config, $, APP, Strophe, callstats */
  10950. var jsSHA = require('jssha');
  10951. var io = require('socket.io-client');
  10952. var callStats = null;
  10953. function initCallback (err, msg) {
  10954. console.log("Initializing Status: err="+err+" msg="+msg);
  10955. }
  10956. var CallStats = {
  10957. init: function (jingleSession) {
  10958. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10959. return;
  10960. callStats = new callstats($, io, jsSHA);
  10961. this.session = jingleSession;
  10962. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10963. this.userID = APP.xmpp.myResource();
  10964. var location = window.location;
  10965. this.confID = location.hostname + location.pathname;
  10966. //userID is generated or given by the origin server
  10967. callStats.initialize(config.callStatsID,
  10968. config.callStatsSecret,
  10969. this.userID,
  10970. initCallback);
  10971. var usage = callStats.fabricUsage.multiplex;
  10972. callStats.addNewFabric(this.peerconnection,
  10973. Strophe.getResourceFromJid(jingleSession.peerjid),
  10974. usage,
  10975. this.confID,
  10976. this.pcCallback.bind(this));
  10977. },
  10978. pcCallback: function (err, msg) {
  10979. if (!callStats)
  10980. return;
  10981. console.log("Monitoring status: "+ err + " msg: " + msg);
  10982. callStats.sendFabricEvent(this.peerconnection,
  10983. callStats.fabricEvent.fabricSetup, this.confID);
  10984. },
  10985. sendMuteEvent: function (mute, type) {
  10986. if (!callStats)
  10987. return;
  10988. var event = null;
  10989. if (type === "video") {
  10990. event = (mute? callStats.fabricEvent.videoPause :
  10991. callStats.fabricEvent.videoResume);
  10992. }
  10993. else {
  10994. event = (mute? callStats.fabricEvent.audioMute :
  10995. callStats.fabricEvent.audioUnmute);
  10996. }
  10997. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10998. },
  10999. sendTerminateEvent: function () {
  11000. if(!callStats) {
  11001. return;
  11002. }
  11003. callStats.sendFabricEvent(this.peerconnection,
  11004. callStats.fabricEvent.fabricTerminated, this.confID);
  11005. },
  11006. sendSetupFailedEvent: function () {
  11007. if(!callStats) {
  11008. return;
  11009. }
  11010. callStats.sendFabricEvent(this.peerconnection,
  11011. callStats.fabricEvent.fabricSetupFailed, this.confID);
  11012. }
  11013. };
  11014. module.exports = CallStats;
  11015. },{"jssha":76,"socket.io-client":114}],53:[function(require,module,exports){
  11016. /* global config */
  11017. /**
  11018. * Provides statistics for the local stream.
  11019. */
  11020. var RTCBrowserType = require('../RTC/RTCBrowserType');
  11021. /**
  11022. * Size of the webaudio analyzer buffer.
  11023. * @type {number}
  11024. */
  11025. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  11026. /**
  11027. * Value of the webaudio analyzer smoothing time parameter.
  11028. * @type {number}
  11029. */
  11030. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  11031. /**
  11032. * Converts time domain data array to audio level.
  11033. * @param samples the time domain data array.
  11034. * @returns {number} the audio level
  11035. */
  11036. function timeDomainDataToAudioLevel(samples) {
  11037. var maxVolume = 0;
  11038. var length = samples.length;
  11039. for (var i = 0; i < length; i++) {
  11040. if (maxVolume < samples[i])
  11041. maxVolume = samples[i];
  11042. }
  11043. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  11044. }
  11045. /**
  11046. * Animates audio level change
  11047. * @param newLevel the new audio level
  11048. * @param lastLevel the last audio level
  11049. * @returns {Number} the audio level to be set
  11050. */
  11051. function animateLevel(newLevel, lastLevel) {
  11052. var value = 0;
  11053. var diff = lastLevel - newLevel;
  11054. if(diff > 0.2) {
  11055. value = lastLevel - 0.2;
  11056. }
  11057. else if(diff < -0.4) {
  11058. value = lastLevel + 0.4;
  11059. }
  11060. else {
  11061. value = newLevel;
  11062. }
  11063. return parseFloat(value.toFixed(3));
  11064. }
  11065. /**
  11066. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  11067. *
  11068. * @param stream the local stream
  11069. * @param interval stats refresh interval given in ms.
  11070. * @constructor
  11071. */
  11072. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  11073. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  11074. this.stream = stream;
  11075. this.intervalId = null;
  11076. this.intervalMilis = interval;
  11077. this.eventEmitter = eventEmitter;
  11078. this.audioLevel = 0;
  11079. this.statisticsService = statisticsService;
  11080. }
  11081. /**
  11082. * Starts the collecting the statistics.
  11083. */
  11084. LocalStatsCollector.prototype.start = function () {
  11085. if (config.disableAudioLevels || !window.AudioContext ||
  11086. RTCBrowserType.isTemasysPluginUsed())
  11087. return;
  11088. var context = new AudioContext();
  11089. var analyser = context.createAnalyser();
  11090. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  11091. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  11092. var source = context.createMediaStreamSource(this.stream);
  11093. source.connect(analyser);
  11094. var self = this;
  11095. this.intervalId = setInterval(
  11096. function () {
  11097. var array = new Uint8Array(analyser.frequencyBinCount);
  11098. analyser.getByteTimeDomainData(array);
  11099. var audioLevel = timeDomainDataToAudioLevel(array);
  11100. if (audioLevel != self.audioLevel) {
  11101. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  11102. self.eventEmitter.emit(
  11103. "statistics.audioLevel",
  11104. self.statisticsService.LOCAL_JID,
  11105. self.audioLevel);
  11106. }
  11107. },
  11108. this.intervalMilis
  11109. );
  11110. };
  11111. /**
  11112. * Stops collecting the statistics.
  11113. */
  11114. LocalStatsCollector.prototype.stop = function () {
  11115. if (this.intervalId) {
  11116. clearInterval(this.intervalId);
  11117. this.intervalId = null;
  11118. }
  11119. };
  11120. module.exports = LocalStatsCollector;
  11121. },{"../RTC/RTCBrowserType":10}],54:[function(require,module,exports){
  11122. /* global require, ssrc2jid */
  11123. /* jshint -W117 */
  11124. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11125. /* Whether we support the browser we are running into for logging statistics */
  11126. var browserSupported = RTCBrowserType.isChrome() ||
  11127. RTCBrowserType.isOpera() || RTCBrowserType.isFirefox();
  11128. /**
  11129. * Calculates packet lost percent using the number of lost packets and the
  11130. * number of all packet.
  11131. * @param lostPackets the number of lost packets
  11132. * @param totalPackets the number of all packets.
  11133. * @returns {number} packet loss percent
  11134. */
  11135. function calculatePacketLoss(lostPackets, totalPackets) {
  11136. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  11137. return 0;
  11138. return Math.round((lostPackets/totalPackets)*100);
  11139. }
  11140. function getStatValue(item, name) {
  11141. var browserType = RTCBrowserType.getBrowserType();
  11142. if (!keyMap[browserType][name])
  11143. throw "The property isn't supported!";
  11144. var key = keyMap[browserType][name];
  11145. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  11146. item.stat(key) : item[key];
  11147. }
  11148. /**
  11149. * Peer statistics data holder.
  11150. * @constructor
  11151. */
  11152. function PeerStats()
  11153. {
  11154. this.ssrc2Loss = {};
  11155. this.ssrc2AudioLevel = {};
  11156. this.ssrc2bitrate = {};
  11157. this.ssrc2resolution = {};
  11158. }
  11159. /**
  11160. * The bandwidth
  11161. * @type {{}}
  11162. */
  11163. PeerStats.bandwidth = {};
  11164. /**
  11165. * The bit rate
  11166. * @type {{}}
  11167. */
  11168. PeerStats.bitrate = {};
  11169. /**
  11170. * The packet loss rate
  11171. * @type {{}}
  11172. */
  11173. PeerStats.packetLoss = null;
  11174. /**
  11175. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  11176. * represented by this instance.
  11177. * @param ssrc audio or video RTP stream SSRC.
  11178. * @param lossRate new packet loss rate value to be set.
  11179. */
  11180. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  11181. {
  11182. this.ssrc2Loss[ssrc] = lossRate;
  11183. };
  11184. /**
  11185. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  11186. * represented by this instance.
  11187. * @param ssrc audio or video RTP stream SSRC.
  11188. * @param resolution new resolution value to be set.
  11189. */
  11190. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  11191. {
  11192. if(resolution === null && this.ssrc2resolution[ssrc])
  11193. {
  11194. delete this.ssrc2resolution[ssrc];
  11195. }
  11196. else if(resolution !== null)
  11197. this.ssrc2resolution[ssrc] = resolution;
  11198. };
  11199. /**
  11200. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  11201. * represented by this instance.
  11202. * @param ssrc audio or video RTP stream SSRC.
  11203. * @param bitrate new bitrate value to be set.
  11204. */
  11205. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  11206. {
  11207. if(this.ssrc2bitrate[ssrc])
  11208. {
  11209. this.ssrc2bitrate[ssrc].download += bitrate.download;
  11210. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  11211. }
  11212. else {
  11213. this.ssrc2bitrate[ssrc] = bitrate;
  11214. }
  11215. };
  11216. /**
  11217. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  11218. * the stream which belongs to the peer represented by this instance.
  11219. * @param ssrc RTP stream SSRC for which current audio level value will be
  11220. * updated.
  11221. * @param audioLevel the new audio level value to be set. Value is truncated to
  11222. * fit the range from 0 to 1.
  11223. */
  11224. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  11225. {
  11226. // Range limit 0 - 1
  11227. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  11228. };
  11229. function formatAudioLevel(audioLevel) {
  11230. return Math.min(Math.max(audioLevel, 0), 1);
  11231. }
  11232. /**
  11233. * Array with the transport information.
  11234. * @type {Array}
  11235. */
  11236. PeerStats.transport = [];
  11237. /**
  11238. * <tt>StatsCollector</tt> registers for stats updates of given
  11239. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  11240. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  11241. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  11242. * instance as an event source.
  11243. *
  11244. * @param peerconnection webRTC peer connection object.
  11245. * @param interval stats refresh interval given in ms.
  11246. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  11247. * called on stats update.
  11248. * @constructor
  11249. */
  11250. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  11251. {
  11252. this.peerconnection = peerconnection;
  11253. this.baselineAudioLevelsReport = null;
  11254. this.currentAudioLevelsReport = null;
  11255. this.currentStatsReport = null;
  11256. this.baselineStatsReport = null;
  11257. this.audioLevelsIntervalId = null;
  11258. this.eventEmitter = eventEmitter;
  11259. /**
  11260. * Gather PeerConnection stats once every this many milliseconds.
  11261. */
  11262. this.GATHER_INTERVAL = 15000;
  11263. /**
  11264. * Log stats via the focus once every this many milliseconds.
  11265. */
  11266. this.LOG_INTERVAL = 60000;
  11267. /**
  11268. * Gather stats and store them in this.statsToBeLogged.
  11269. */
  11270. this.gatherStatsIntervalId = null;
  11271. /**
  11272. * Send the stats already saved in this.statsToBeLogged to be logged via
  11273. * the focus.
  11274. */
  11275. this.logStatsIntervalId = null;
  11276. /**
  11277. * Stores the statistics which will be send to the focus to be logged.
  11278. */
  11279. this.statsToBeLogged =
  11280. {
  11281. timestamps: [],
  11282. stats: {}
  11283. };
  11284. // Updates stats interval
  11285. this.audioLevelsIntervalMilis = audioLevelsInterval;
  11286. this.statsIntervalId = null;
  11287. this.statsIntervalMilis = statsInterval;
  11288. // Map of jids to PeerStats
  11289. this.jid2stats = {};
  11290. }
  11291. module.exports = StatsCollector;
  11292. /**
  11293. * Stops stats updates.
  11294. */
  11295. StatsCollector.prototype.stop = function () {
  11296. if (this.audioLevelsIntervalId) {
  11297. clearInterval(this.audioLevelsIntervalId);
  11298. this.audioLevelsIntervalId = null;
  11299. }
  11300. if (this.statsIntervalId)
  11301. {
  11302. clearInterval(this.statsIntervalId);
  11303. this.statsIntervalId = null;
  11304. }
  11305. if(this.logStatsIntervalId)
  11306. {
  11307. clearInterval(this.logStatsIntervalId);
  11308. this.logStatsIntervalId = null;
  11309. }
  11310. if(this.gatherStatsIntervalId)
  11311. {
  11312. clearInterval(this.gatherStatsIntervalId);
  11313. this.gatherStatsIntervalId = null;
  11314. }
  11315. };
  11316. /**
  11317. * Callback passed to <tt>getStats</tt> method.
  11318. * @param error an error that occurred on <tt>getStats</tt> call.
  11319. */
  11320. StatsCollector.prototype.errorCallback = function (error)
  11321. {
  11322. console.error("Get stats error", error);
  11323. this.stop();
  11324. };
  11325. /**
  11326. * Starts stats updates.
  11327. */
  11328. StatsCollector.prototype.start = function ()
  11329. {
  11330. var self = this;
  11331. if (!config.disableAudioLevels) {
  11332. this.audioLevelsIntervalId = setInterval(
  11333. function () {
  11334. // Interval updates
  11335. self.peerconnection.getStats(
  11336. function (report) {
  11337. var results = null;
  11338. if (!report || !report.result ||
  11339. typeof report.result != 'function') {
  11340. results = report;
  11341. }
  11342. else {
  11343. results = report.result();
  11344. }
  11345. //console.error("Got interval report", results);
  11346. self.currentAudioLevelsReport = results;
  11347. self.processAudioLevelReport();
  11348. self.baselineAudioLevelsReport =
  11349. self.currentAudioLevelsReport;
  11350. },
  11351. self.errorCallback
  11352. );
  11353. },
  11354. self.audioLevelsIntervalMilis
  11355. );
  11356. }
  11357. if (!config.disableStats && browserSupported) {
  11358. this.statsIntervalId = setInterval(
  11359. function () {
  11360. // Interval updates
  11361. self.peerconnection.getStats(
  11362. function (report) {
  11363. var results = null;
  11364. if (!report || !report.result ||
  11365. typeof report.result != 'function') {
  11366. //firefox
  11367. results = report;
  11368. }
  11369. else {
  11370. //chrome
  11371. results = report.result();
  11372. }
  11373. //console.error("Got interval report", results);
  11374. self.currentStatsReport = results;
  11375. try {
  11376. self.processStatsReport();
  11377. }
  11378. catch (e) {
  11379. console.error("Unsupported key:" + e, e);
  11380. }
  11381. self.baselineStatsReport = self.currentStatsReport;
  11382. },
  11383. self.errorCallback
  11384. );
  11385. },
  11386. self.statsIntervalMilis
  11387. );
  11388. }
  11389. // Logging statistics does not support firefox
  11390. if (config.logStats && (browserSupported && !RTCBrowserType.isFirefox())) {
  11391. this.gatherStatsIntervalId = setInterval(
  11392. function () {
  11393. self.peerconnection.getStats(
  11394. function (report) {
  11395. self.addStatsToBeLogged(report.result());
  11396. },
  11397. function () {
  11398. }
  11399. );
  11400. },
  11401. this.GATHER_INTERVAL
  11402. );
  11403. this.logStatsIntervalId = setInterval(
  11404. function() { self.logStats(); },
  11405. this.LOG_INTERVAL);
  11406. }
  11407. };
  11408. /**
  11409. * Checks whether a certain record should be included in the logged statistics.
  11410. */
  11411. function acceptStat(reportId, reportType, statName) {
  11412. if (reportType == "googCandidatePair" && statName == "googChannelId")
  11413. return false;
  11414. if (reportType == "ssrc") {
  11415. if (statName == "googTrackId" ||
  11416. statName == "transportId" ||
  11417. statName == "ssrc")
  11418. return false;
  11419. }
  11420. return true;
  11421. }
  11422. /**
  11423. * Checks whether a certain record should be included in the logged statistics.
  11424. */
  11425. function acceptReport(id, type) {
  11426. if (id.substring(0, 15) == "googCertificate" ||
  11427. id.substring(0, 9) == "googTrack" ||
  11428. id.substring(0, 20) == "googLibjingleSession")
  11429. return false;
  11430. if (type == "googComponent")
  11431. return false;
  11432. return true;
  11433. }
  11434. /**
  11435. * Converts the stats to the format used for logging, and saves the data in
  11436. * this.statsToBeLogged.
  11437. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  11438. */
  11439. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  11440. var self = this;
  11441. var num_records = this.statsToBeLogged.timestamps.length;
  11442. this.statsToBeLogged.timestamps.push(new Date().getTime());
  11443. reports.map(function (report) {
  11444. if (!acceptReport(report.id, report.type))
  11445. return;
  11446. var stat = self.statsToBeLogged.stats[report.id];
  11447. if (!stat) {
  11448. stat = self.statsToBeLogged.stats[report.id] = {};
  11449. }
  11450. stat.type = report.type;
  11451. report.names().map(function (name) {
  11452. if (!acceptStat(report.id, report.type, name))
  11453. return;
  11454. var values = stat[name];
  11455. if (!values) {
  11456. values = stat[name] = [];
  11457. }
  11458. while (values.length < num_records) {
  11459. values.push(null);
  11460. }
  11461. values.push(report.stat(name));
  11462. });
  11463. });
  11464. };
  11465. StatsCollector.prototype.logStats = function () {
  11466. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  11467. return;
  11468. // Reset the stats
  11469. this.statsToBeLogged.stats = {};
  11470. this.statsToBeLogged.timestamps = [];
  11471. };
  11472. var keyMap = {};
  11473. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  11474. "ssrc": "ssrc",
  11475. "packetsReceived": "packetsReceived",
  11476. "packetsLost": "packetsLost",
  11477. "packetsSent": "packetsSent",
  11478. "bytesReceived": "bytesReceived",
  11479. "bytesSent": "bytesSent"
  11480. };
  11481. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  11482. "receiveBandwidth": "googAvailableReceiveBandwidth",
  11483. "sendBandwidth": "googAvailableSendBandwidth",
  11484. "remoteAddress": "googRemoteAddress",
  11485. "transportType": "googTransportType",
  11486. "localAddress": "googLocalAddress",
  11487. "activeConnection": "googActiveConnection",
  11488. "ssrc": "ssrc",
  11489. "packetsReceived": "packetsReceived",
  11490. "packetsSent": "packetsSent",
  11491. "packetsLost": "packetsLost",
  11492. "bytesReceived": "bytesReceived",
  11493. "bytesSent": "bytesSent",
  11494. "googFrameHeightReceived": "googFrameHeightReceived",
  11495. "googFrameWidthReceived": "googFrameWidthReceived",
  11496. "googFrameHeightSent": "googFrameHeightSent",
  11497. "googFrameWidthSent": "googFrameWidthSent",
  11498. "audioInputLevel": "audioInputLevel",
  11499. "audioOutputLevel": "audioOutputLevel"
  11500. };
  11501. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  11502. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  11503. /**
  11504. * Stats processing logic.
  11505. */
  11506. StatsCollector.prototype.processStatsReport = function () {
  11507. if (!this.baselineStatsReport) {
  11508. return;
  11509. }
  11510. for (var idx in this.currentStatsReport) {
  11511. var now = this.currentStatsReport[idx];
  11512. try {
  11513. if (getStatValue(now, 'receiveBandwidth') ||
  11514. getStatValue(now, 'sendBandwidth')) {
  11515. PeerStats.bandwidth = {
  11516. "download": Math.round(
  11517. (getStatValue(now, 'receiveBandwidth')) / 1000),
  11518. "upload": Math.round(
  11519. (getStatValue(now, 'sendBandwidth')) / 1000)
  11520. };
  11521. }
  11522. }
  11523. catch(e){/*not supported*/}
  11524. if(now.type == 'googCandidatePair')
  11525. {
  11526. var ip, type, localIP, active;
  11527. try {
  11528. ip = getStatValue(now, 'remoteAddress');
  11529. type = getStatValue(now, "transportType");
  11530. localIP = getStatValue(now, "localAddress");
  11531. active = getStatValue(now, "activeConnection");
  11532. }
  11533. catch(e){/*not supported*/}
  11534. if(!ip || !type || !localIP || active != "true")
  11535. continue;
  11536. var addressSaved = false;
  11537. for(var i = 0; i < PeerStats.transport.length; i++)
  11538. {
  11539. if(PeerStats.transport[i].ip == ip &&
  11540. PeerStats.transport[i].type == type &&
  11541. PeerStats.transport[i].localip == localIP)
  11542. {
  11543. addressSaved = true;
  11544. }
  11545. }
  11546. if(addressSaved)
  11547. continue;
  11548. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  11549. continue;
  11550. }
  11551. if(now.type == "candidatepair")
  11552. {
  11553. if(now.state == "succeeded")
  11554. continue;
  11555. var local = this.currentStatsReport[now.localCandidateId];
  11556. var remote = this.currentStatsReport[now.remoteCandidateId];
  11557. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  11558. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  11559. }
  11560. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11561. now.type != "inboundrtp") {
  11562. continue;
  11563. }
  11564. var before = this.baselineStatsReport[idx];
  11565. if (!before) {
  11566. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11567. continue;
  11568. }
  11569. var ssrc = getStatValue(now, 'ssrc');
  11570. if(!ssrc)
  11571. continue;
  11572. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11573. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11574. console.warn("No jid for ssrc: " + ssrc);
  11575. continue;
  11576. }
  11577. var jidStats = this.jid2stats[jid];
  11578. if (!jidStats) {
  11579. jidStats = new PeerStats();
  11580. this.jid2stats[jid] = jidStats;
  11581. }
  11582. var isDownloadStream = true;
  11583. var key = 'packetsReceived';
  11584. if (!getStatValue(now, key))
  11585. {
  11586. isDownloadStream = false;
  11587. key = 'packetsSent';
  11588. if (!getStatValue(now, key))
  11589. {
  11590. console.warn("No packetsReceived nor packetSent stat found");
  11591. continue;
  11592. }
  11593. }
  11594. var packetsNow = getStatValue(now, key);
  11595. if(!packetsNow || packetsNow < 0)
  11596. packetsNow = 0;
  11597. var packetsBefore = getStatValue(before, key);
  11598. if(!packetsBefore || packetsBefore < 0)
  11599. packetsBefore = 0;
  11600. var packetRate = packetsNow - packetsBefore;
  11601. if(!packetRate || packetRate < 0)
  11602. packetRate = 0;
  11603. var currentLoss = getStatValue(now, 'packetsLost');
  11604. if(!currentLoss || currentLoss < 0)
  11605. currentLoss = 0;
  11606. var previousLoss = getStatValue(before, 'packetsLost');
  11607. if(!previousLoss || previousLoss < 0)
  11608. previousLoss = 0;
  11609. var lossRate = currentLoss - previousLoss;
  11610. if(!lossRate || lossRate < 0)
  11611. lossRate = 0;
  11612. var packetsTotal = (packetRate + lossRate);
  11613. jidStats.setSsrcLoss(ssrc,
  11614. {"packetsTotal": packetsTotal,
  11615. "packetsLost": lossRate,
  11616. "isDownloadStream": isDownloadStream});
  11617. var bytesReceived = 0, bytesSent = 0;
  11618. if(getStatValue(now, "bytesReceived"))
  11619. {
  11620. bytesReceived = getStatValue(now, "bytesReceived") -
  11621. getStatValue(before, "bytesReceived");
  11622. }
  11623. if(getStatValue(now, "bytesSent"))
  11624. {
  11625. bytesSent = getStatValue(now, "bytesSent") -
  11626. getStatValue(before, "bytesSent");
  11627. }
  11628. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11629. if(bytesReceived <= 0 || time <= 0)
  11630. {
  11631. bytesReceived = 0;
  11632. }
  11633. else
  11634. {
  11635. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11636. }
  11637. if(bytesSent <= 0 || time <= 0)
  11638. {
  11639. bytesSent = 0;
  11640. }
  11641. else
  11642. {
  11643. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11644. }
  11645. jidStats.setSsrcBitrate(ssrc, {
  11646. "download": bytesReceived,
  11647. "upload": bytesSent});
  11648. var resolution = {height: null, width: null};
  11649. try {
  11650. if (getStatValue(now, "googFrameHeightReceived") &&
  11651. getStatValue(now, "googFrameWidthReceived")) {
  11652. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11653. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11654. }
  11655. else if (getStatValue(now, "googFrameHeightSent") &&
  11656. getStatValue(now, "googFrameWidthSent")) {
  11657. resolution.height = getStatValue(now, "googFrameHeightSent");
  11658. resolution.width = getStatValue(now, "googFrameWidthSent");
  11659. }
  11660. }
  11661. catch(e){/*not supported*/}
  11662. if(resolution.height && resolution.width)
  11663. {
  11664. jidStats.setSsrcResolution(ssrc, resolution);
  11665. }
  11666. else
  11667. {
  11668. jidStats.setSsrcResolution(ssrc, null);
  11669. }
  11670. }
  11671. var self = this;
  11672. // Jid stats
  11673. var totalPackets = {download: 0, upload: 0};
  11674. var lostPackets = {download: 0, upload: 0};
  11675. var bitrateDownload = 0;
  11676. var bitrateUpload = 0;
  11677. var resolutions = {};
  11678. Object.keys(this.jid2stats).forEach(
  11679. function (jid)
  11680. {
  11681. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11682. function (ssrc)
  11683. {
  11684. var type = "upload";
  11685. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11686. type = "download";
  11687. totalPackets[type] +=
  11688. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11689. lostPackets[type] +=
  11690. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11691. }
  11692. );
  11693. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11694. function (ssrc) {
  11695. bitrateDownload +=
  11696. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11697. bitrateUpload +=
  11698. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11699. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11700. }
  11701. );
  11702. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11703. }
  11704. );
  11705. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11706. PeerStats.packetLoss = {
  11707. total:
  11708. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11709. totalPackets.download + totalPackets.upload),
  11710. download:
  11711. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11712. upload:
  11713. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11714. };
  11715. this.eventEmitter.emit("statistics.connectionstats",
  11716. {
  11717. "bitrate": PeerStats.bitrate,
  11718. "packetLoss": PeerStats.packetLoss,
  11719. "bandwidth": PeerStats.bandwidth,
  11720. "resolution": resolutions,
  11721. "transport": PeerStats.transport
  11722. });
  11723. PeerStats.transport = [];
  11724. };
  11725. /**
  11726. * Stats processing logic.
  11727. */
  11728. StatsCollector.prototype.processAudioLevelReport = function () {
  11729. if (!this.baselineAudioLevelsReport) {
  11730. return;
  11731. }
  11732. for (var idx in this.currentAudioLevelsReport) {
  11733. var now = this.currentAudioLevelsReport[idx];
  11734. if (now.type != 'ssrc') {
  11735. continue;
  11736. }
  11737. var before = this.baselineAudioLevelsReport[idx];
  11738. if (!before) {
  11739. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11740. continue;
  11741. }
  11742. var ssrc = getStatValue(now, 'ssrc');
  11743. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11744. if (!jid) {
  11745. if((Date.now() - now.timestamp) < 3000)
  11746. console.warn("No jid for ssrc: " + ssrc);
  11747. continue;
  11748. }
  11749. var jidStats = this.jid2stats[jid];
  11750. if (!jidStats) {
  11751. jidStats = new PeerStats();
  11752. this.jid2stats[jid] = jidStats;
  11753. }
  11754. // Audio level
  11755. var audioLevel = null;
  11756. try {
  11757. audioLevel = getStatValue(now, 'audioInputLevel');
  11758. if (!audioLevel)
  11759. audioLevel = getStatValue(now, 'audioOutputLevel');
  11760. }
  11761. catch(e) {/*not supported*/
  11762. console.warn("Audio Levels are not available in the statistics.");
  11763. clearInterval(this.audioLevelsIntervalId);
  11764. return;
  11765. }
  11766. if (audioLevel) {
  11767. // TODO: can't find specs about what this value really is,
  11768. // but it seems to vary between 0 and around 32k.
  11769. audioLevel = audioLevel / 32767;
  11770. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11771. if(jid != APP.xmpp.myJid())
  11772. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11773. }
  11774. }
  11775. };
  11776. },{"../RTC/RTCBrowserType":10}],55:[function(require,module,exports){
  11777. /* global require, APP */
  11778. /**
  11779. * Created by hristo on 8/4/14.
  11780. */
  11781. var LocalStats = require("./LocalStatsCollector.js");
  11782. var RTPStats = require("./RTPStatsCollector.js");
  11783. var EventEmitter = require("events");
  11784. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11785. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11786. var CallStats = require("./CallStats");
  11787. var RTCEvents = require("../../service/RTC/RTCEvents");
  11788. var eventEmitter = new EventEmitter();
  11789. var localStats = null;
  11790. var rtpStats = null;
  11791. function stopLocal() {
  11792. if (localStats) {
  11793. localStats.stop();
  11794. localStats = null;
  11795. }
  11796. }
  11797. function stopRemote() {
  11798. if (rtpStats) {
  11799. rtpStats.stop();
  11800. eventEmitter.emit("statistics.stop");
  11801. rtpStats = null;
  11802. }
  11803. }
  11804. function startRemoteStats (peerconnection) {
  11805. if (rtpStats) {
  11806. rtpStats.stop();
  11807. }
  11808. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11809. rtpStats.start();
  11810. }
  11811. function onStreamCreated(stream) {
  11812. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11813. return;
  11814. }
  11815. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11816. eventEmitter);
  11817. localStats.start();
  11818. }
  11819. function onDisposeConference(onUnload) {
  11820. CallStats.sendTerminateEvent();
  11821. stopRemote();
  11822. if(onUnload) {
  11823. stopLocal();
  11824. eventEmitter.removeAllListeners();
  11825. }
  11826. }
  11827. var statistics = {
  11828. /**
  11829. * Indicates that this audio level is for local jid.
  11830. * @type {string}
  11831. */
  11832. LOCAL_JID: 'local',
  11833. addAudioLevelListener: function(listener)
  11834. {
  11835. eventEmitter.on("statistics.audioLevel", listener);
  11836. },
  11837. removeAudioLevelListener: function(listener)
  11838. {
  11839. eventEmitter.removeListener("statistics.audioLevel", listener);
  11840. },
  11841. addConnectionStatsListener: function(listener)
  11842. {
  11843. eventEmitter.on("statistics.connectionstats", listener);
  11844. },
  11845. removeConnectionStatsListener: function(listener)
  11846. {
  11847. eventEmitter.removeListener("statistics.connectionstats", listener);
  11848. },
  11849. addRemoteStatsStopListener: function(listener)
  11850. {
  11851. eventEmitter.on("statistics.stop", listener);
  11852. },
  11853. removeRemoteStatsStopListener: function(listener)
  11854. {
  11855. eventEmitter.removeListener("statistics.stop", listener);
  11856. },
  11857. stop: function () {
  11858. stopLocal();
  11859. stopRemote();
  11860. if(eventEmitter)
  11861. {
  11862. eventEmitter.removeAllListeners();
  11863. }
  11864. },
  11865. stopRemoteStatistics: function()
  11866. {
  11867. stopRemote();
  11868. },
  11869. start: function () {
  11870. APP.RTC.addStreamListener(onStreamCreated,
  11871. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11872. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11873. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11874. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11875. startRemoteStats(event.peerconnection);
  11876. // CallStats.init(event);
  11877. });
  11878. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11879. CallStats.init(session);
  11880. });
  11881. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11882. CallStats.sendMuteEvent(mute, "audio");
  11883. });
  11884. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11885. CallStats.sendSetupFailedEvent();
  11886. });
  11887. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11888. CallStats.sendMuteEvent(mute, "video");
  11889. });
  11890. }
  11891. };
  11892. module.exports = statistics;
  11893. },{"../../service/RTC/RTCEvents":165,"../../service/RTC/StreamEventTypes.js":167,"../../service/xmpp/XMPPEvents":174,"./CallStats":52,"./LocalStatsCollector.js":53,"./RTPStatsCollector.js":54,"events":1}],56:[function(require,module,exports){
  11894. /* global $, require, config, interfaceConfig */
  11895. var i18n = require("i18next-client");
  11896. var languages = require("../../service/translation/languages");
  11897. var Settings = require("../settings/Settings");
  11898. var DEFAULT_LANG = languages.EN;
  11899. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11900. return value.replace("__app__", interfaceConfig.APP_NAME);
  11901. });
  11902. var defaultOptions = {
  11903. detectLngQS: "lang",
  11904. useCookie: false,
  11905. fallbackLng: DEFAULT_LANG,
  11906. load: "unspecific",
  11907. resGetPath: 'lang/__ns__-__lng__.json',
  11908. ns: {
  11909. namespaces: ['main', 'languages'],
  11910. defaultNs: 'main'
  11911. },
  11912. lngWhitelist : languages.getLanguages(),
  11913. fallbackOnNull: true,
  11914. fallbackOnEmpty: true,
  11915. useDataAttrOptions: true,
  11916. app: interfaceConfig.APP_NAME,
  11917. getAsync: false,
  11918. defaultValueFromContent: false,
  11919. customLoad: function(lng, ns, options, done) {
  11920. var resPath = "lang/__ns__-__lng__.json";
  11921. if(lng === languages.EN)
  11922. resPath = "lang/__ns__.json";
  11923. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11924. i18n.functions.ajax({
  11925. url: url,
  11926. success: function(data, status, xhr) {
  11927. i18n.functions.log('loaded: ' + url);
  11928. done(null, data);
  11929. },
  11930. error : function(xhr, status, error) {
  11931. if ((status && status == 200) ||
  11932. (xhr && xhr.status && xhr.status == 200)) {
  11933. // file loaded but invalid json, stop waste time !
  11934. i18n.functions.error('There is a typo in: ' + url);
  11935. } else if ((status && status == 404) ||
  11936. (xhr && xhr.status && xhr.status == 404)) {
  11937. i18n.functions.log('Does not exist: ' + url);
  11938. } else {
  11939. var theStatus = status ? status :
  11940. ((xhr && xhr.status) ? xhr.status : null);
  11941. i18n.functions.log(theStatus + ' when loading ' + url);
  11942. }
  11943. done(error, {});
  11944. },
  11945. dataType: "json",
  11946. async : options.getAsync
  11947. });
  11948. }
  11949. // options for caching
  11950. // useLocalStorage: true,
  11951. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11952. };
  11953. function initCompleted(t) {
  11954. $("[data-i18n]").i18n();
  11955. }
  11956. function checkForParameter() {
  11957. var query = window.location.search.substring(1);
  11958. var vars = query.split("&");
  11959. for (var i=0;i<vars.length;i++) {
  11960. var pair = vars[i].split("=");
  11961. if(pair[0] == "lang")
  11962. {
  11963. return pair[1];
  11964. }
  11965. }
  11966. return null;
  11967. }
  11968. module.exports = {
  11969. init: function (lang) {
  11970. var options = defaultOptions;
  11971. if(!lang)
  11972. {
  11973. lang = checkForParameter();
  11974. if(!lang)
  11975. {
  11976. var settings = Settings.getSettings();
  11977. if(settings)
  11978. lang = settings.language;
  11979. if(!lang && config.defaultLanguage)
  11980. {
  11981. lang = config.defaultLanguage;
  11982. }
  11983. }
  11984. }
  11985. if(lang) {
  11986. options.lng = lang;
  11987. }
  11988. i18n.init(options, initCompleted);
  11989. },
  11990. translateString: function (key, options) {
  11991. return i18n.t(key, options);
  11992. },
  11993. setLanguage: function (lang) {
  11994. if(!lang)
  11995. lang = DEFAULT_LANG;
  11996. i18n.setLng(lang, defaultOptions, initCompleted);
  11997. },
  11998. getCurrentLanguage: function () {
  11999. return i18n.lng();
  12000. },
  12001. translateElement: function (selector) {
  12002. selector.i18n();
  12003. },
  12004. generateTranslationHTML: function (key, options) {
  12005. var str = "<span data-i18n=\"" + key + "\"";
  12006. if(options)
  12007. {
  12008. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  12009. }
  12010. str += ">";
  12011. str += this.translateString(key, options);
  12012. str += "</span>";
  12013. return str;
  12014. }
  12015. };
  12016. },{"../../service/translation/languages":173,"../settings/Settings":51,"i18next-client":75}],57:[function(require,module,exports){
  12017. /*
  12018. * JingleSession provides an API to manage a single Jingle session. We will
  12019. * have different implementations depending on the underlying interface used
  12020. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  12021. */
  12022. function JingleSession(me, sid, connection, service, eventEmitter) {
  12023. /**
  12024. * Our JID.
  12025. */
  12026. this.me = me;
  12027. /**
  12028. * The Jingle session identifier.
  12029. */
  12030. this.sid = sid;
  12031. /**
  12032. * The XMPP connection.
  12033. */
  12034. this.connection = connection;
  12035. /**
  12036. * The XMPP service.
  12037. */
  12038. this.service = service;
  12039. /**
  12040. * The event emitter.
  12041. */
  12042. this.eventEmitter = eventEmitter;
  12043. /**
  12044. * Whether to use dripping or not. Dripping is sending trickle candidates
  12045. * not one-by-one.
  12046. * Note: currently we do not support 'false'.
  12047. */
  12048. this.usedrip = true;
  12049. /**
  12050. * When dripping is used, stores ICE candidates which are to be sent.
  12051. */
  12052. this.drip_container = [];
  12053. // Media constraints. Is this WebRTC only?
  12054. this.media_constraints = null;
  12055. // ICE servers config (RTCConfiguration?).
  12056. this.ice_config = {};
  12057. }
  12058. /**
  12059. * Prepares this object to initiate a session.
  12060. * @param peerjid the JID of the remote peer.
  12061. * @param isInitiator whether we will be the Jingle initiator.
  12062. * @param media_constraints
  12063. * @param ice_config
  12064. */
  12065. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  12066. media_constraints, ice_config) {
  12067. this.media_constraints = media_constraints;
  12068. this.ice_config = ice_config;
  12069. if (this.state !== null) {
  12070. console.error('attempt to initiate on session ' + this.sid +
  12071. 'in state ' + this.state);
  12072. return;
  12073. }
  12074. this.state = 'pending';
  12075. this.initiator = isInitiator ? this.me : peerjid;
  12076. this.responder = !isInitiator ? this.me : peerjid;
  12077. this.peerjid = peerjid;
  12078. this.doInitialize();
  12079. };
  12080. /**
  12081. * Finishes initialization.
  12082. */
  12083. JingleSession.prototype.doInitialize = function() {};
  12084. /**
  12085. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  12086. * Note: currently only used on transport-info
  12087. */
  12088. JingleSession.prototype.addIceCandidates = function(contents) {};
  12089. /**
  12090. * Handles an 'add-source' event.
  12091. *
  12092. * @param contents an array of Jingle 'content' elements.
  12093. */
  12094. JingleSession.prototype.addSources = function(contents) {};
  12095. /**
  12096. * Handles a 'remove-source' event.
  12097. *
  12098. * @param contents an array of Jingle 'content' elements.
  12099. */
  12100. JingleSession.prototype.removeSources = function(contents) {};
  12101. /**
  12102. * Terminates this Jingle session (stops sending media and closes the streams?)
  12103. */
  12104. JingleSession.prototype.terminate = function() {};
  12105. /**
  12106. * Sends a Jingle session-terminate message to the peer and terminates the
  12107. * session.
  12108. * @param reason
  12109. * @param text
  12110. */
  12111. JingleSession.prototype.sendTerminate = function(reason, text) {};
  12112. /**
  12113. * Handles an offer from the remote peer (prepares to accept a session).
  12114. * @param jingle the 'jingle' XML element.
  12115. */
  12116. JingleSession.prototype.setOffer = function(jingle) {};
  12117. /**
  12118. * Handles an answer from the remote peer (prepares to accept a session).
  12119. * @param jingle the 'jingle' XML element.
  12120. */
  12121. JingleSession.prototype.setAnswer = function(jingle) {};
  12122. module.exports = JingleSession;
  12123. },{}],58:[function(require,module,exports){
  12124. /* jshint -W117 */
  12125. var JingleSession = require("./JingleSession");
  12126. var TraceablePeerConnection = require("./TraceablePeerConnection");
  12127. var SDPDiffer = require("./SDPDiffer");
  12128. var SDPUtil = require("./SDPUtil");
  12129. var SDP = require("./SDP");
  12130. var async = require("async");
  12131. var transform = require("sdp-transform");
  12132. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12133. var RTCBrowserType = require("../RTC/RTCBrowserType");
  12134. var SSRCReplacement = require("./LocalSSRCReplacement");
  12135. // Jingle stuff
  12136. function JingleSessionPC(me, sid, connection, service, eventEmitter) {
  12137. JingleSession.call(this, me, sid, connection, service, eventEmitter);
  12138. this.initiator = null;
  12139. this.responder = null;
  12140. this.peerjid = null;
  12141. this.state = null;
  12142. this.localSDP = null;
  12143. this.remoteSDP = null;
  12144. this.relayedStreams = [];
  12145. this.pc_constraints = null;
  12146. this.usetrickle = true;
  12147. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  12148. this.hadstuncandidate = false;
  12149. this.hadturncandidate = false;
  12150. this.lasticecandidate = false;
  12151. this.statsinterval = null;
  12152. this.reason = null;
  12153. this.addssrc = [];
  12154. this.removessrc = [];
  12155. this.pendingop = null;
  12156. this.switchstreams = false;
  12157. this.wait = true;
  12158. this.localStreamsSSRC = null;
  12159. this.ssrcOwners = {};
  12160. this.ssrcVideoTypes = {};
  12161. this.eventEmitter = eventEmitter;
  12162. /**
  12163. * The indicator which determines whether the (local) video has been muted
  12164. * in response to a user command in contrast to an automatic decision made
  12165. * by the application logic.
  12166. */
  12167. this.videoMuteByUser = false;
  12168. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  12169. // We start with the queue paused. We resume it when the signaling state is
  12170. // stable and the ice connection state is connected.
  12171. this.modifySourcesQueue.pause();
  12172. }
  12173. JingleSessionPC.prototype = JingleSession.prototype;
  12174. JingleSessionPC.prototype.constructor = JingleSessionPC;
  12175. JingleSessionPC.prototype.setOffer = function(offer) {
  12176. this.setRemoteDescription(offer, 'offer');
  12177. };
  12178. JingleSessionPC.prototype.setAnswer = function(answer) {
  12179. this.setRemoteDescription(answer, 'answer');
  12180. };
  12181. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  12182. var signalingState = this.peerconnection.signalingState;
  12183. var iceConnectionState = this.peerconnection.iceConnectionState;
  12184. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  12185. this.modifySourcesQueue.resume();
  12186. } else {
  12187. this.modifySourcesQueue.pause();
  12188. }
  12189. };
  12190. JingleSessionPC.prototype.doInitialize = function () {
  12191. var self = this;
  12192. this.hadstuncandidate = false;
  12193. this.hadturncandidate = false;
  12194. this.lasticecandidate = false;
  12195. // True if reconnect is in progress
  12196. this.isreconnect = false;
  12197. // Set to true if the connection was ever stable
  12198. this.wasstable = false;
  12199. this.peerconnection = new TraceablePeerConnection(
  12200. this.connection.jingle.ice_config,
  12201. this.connection.jingle.pc_constraints,
  12202. this);
  12203. this.peerconnection.onicecandidate = function (event) {
  12204. self.sendIceCandidate(event.candidate);
  12205. };
  12206. this.peerconnection.onaddstream = function (event) {
  12207. if (event.stream.id !== 'default') {
  12208. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  12209. self.remoteStreamAdded(event);
  12210. } else {
  12211. // This is a recvonly stream. Clients that implement Unified Plan,
  12212. // such as Firefox use recvonly "streams/channels/tracks" for
  12213. // receiving remote stream/tracks, as opposed to Plan B where there
  12214. // are only 3 channels: audio, video and data.
  12215. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  12216. }
  12217. };
  12218. this.peerconnection.onremovestream = function (event) {
  12219. // Remove the stream from remoteStreams
  12220. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  12221. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  12222. };
  12223. this.peerconnection.onsignalingstatechange = function (event) {
  12224. if (!(self && self.peerconnection)) return;
  12225. console.info("Signaling: " + this.peerconnection.signalingState);
  12226. if (self.peerconnection.signalingState === 'stable') {
  12227. self.wasstable = true;
  12228. }
  12229. self.updateModifySourcesQueue();
  12230. };
  12231. /**
  12232. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  12233. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  12234. * RTCPeerConnection.iceConnectionState changes.
  12235. *
  12236. * @param event the event containing information about the change
  12237. */
  12238. this.peerconnection.oniceconnectionstatechange = function (event) {
  12239. if (!(self && self.peerconnection)) return;
  12240. console.info("Ice: " + self.peerconnection.iceConnectionState);
  12241. self.updateModifySourcesQueue();
  12242. switch (self.peerconnection.iceConnectionState) {
  12243. case 'connected':
  12244. // Informs interested parties that the connection has been restored.
  12245. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  12246. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  12247. self.isreconnect = false;
  12248. break;
  12249. case 'disconnected':
  12250. self.isreconnect = true;
  12251. // Informs interested parties that the connection has been interrupted.
  12252. if (self.wasstable)
  12253. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  12254. break;
  12255. case 'failed':
  12256. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12257. break;
  12258. }
  12259. onIceConnectionStateChange(self.sid, self);
  12260. };
  12261. this.peerconnection.onnegotiationneeded = function (event) {
  12262. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  12263. };
  12264. // add any local and relayed stream
  12265. APP.RTC.localStreams.forEach(function(stream) {
  12266. self.peerconnection.addStream(stream.getOriginalStream());
  12267. });
  12268. this.relayedStreams.forEach(function(stream) {
  12269. self.peerconnection.addStream(stream);
  12270. });
  12271. };
  12272. function onIceConnectionStateChange(sid, session) {
  12273. switch (session.peerconnection.iceConnectionState) {
  12274. case 'checking':
  12275. session.timeChecking = (new Date()).getTime();
  12276. session.firstconnect = true;
  12277. break;
  12278. case 'completed': // on caller side
  12279. case 'connected':
  12280. if (session.firstconnect) {
  12281. session.firstconnect = false;
  12282. var metadata = {};
  12283. metadata.setupTime
  12284. = (new Date()).getTime() - session.timeChecking;
  12285. session.peerconnection.getStats(function (res) {
  12286. if(res && res.result) {
  12287. res.result().forEach(function (report) {
  12288. if (report.type == 'googCandidatePair' &&
  12289. report.stat('googActiveConnection') == 'true') {
  12290. metadata.localCandidateType
  12291. = report.stat('googLocalCandidateType');
  12292. metadata.remoteCandidateType
  12293. = report.stat('googRemoteCandidateType');
  12294. // log pair as well so we can get nice pie
  12295. // charts
  12296. metadata.candidatePair
  12297. = report.stat('googLocalCandidateType') +
  12298. ';' +
  12299. report.stat('googRemoteCandidateType');
  12300. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  12301. {
  12302. metadata.ipv6 = true;
  12303. }
  12304. }
  12305. });
  12306. }
  12307. });
  12308. }
  12309. break;
  12310. }
  12311. }
  12312. JingleSessionPC.prototype.accept = function () {
  12313. this.state = 'active';
  12314. var pranswer = this.peerconnection.localDescription;
  12315. if (!pranswer || pranswer.type != 'pranswer') {
  12316. return;
  12317. }
  12318. console.log('going from pranswer to answer');
  12319. if (this.usetrickle) {
  12320. // remove candidates already sent from session-accept
  12321. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  12322. for (var i = 0; i < lines.length; i++) {
  12323. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  12324. }
  12325. }
  12326. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  12327. // FIXME: change any inactive to sendrecv or whatever they were originally
  12328. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  12329. }
  12330. var prsdp = new SDP(pranswer.sdp);
  12331. var accept = $iq({to: this.peerjid,
  12332. type: 'set'})
  12333. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12334. action: 'session-accept',
  12335. initiator: this.initiator,
  12336. responder: this.responder,
  12337. sid: this.sid });
  12338. // FIXME why do we generate session-accept in 3 different places ?
  12339. prsdp.toJingle(
  12340. accept,
  12341. this.initiator == this.me ? 'initiator' : 'responder',
  12342. this.localStreamsSSRC);
  12343. var sdp = this.peerconnection.localDescription.sdp;
  12344. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  12345. // FIXME: change any inactive to sendrecv or whatever they were originally
  12346. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  12347. }
  12348. var self = this;
  12349. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  12350. function () {
  12351. //console.log('setLocalDescription success');
  12352. self.setLocalDescription();
  12353. SSRCReplacement.processSessionInit(accept);
  12354. self.connection.sendIQ(accept,
  12355. function () {
  12356. var ack = {};
  12357. ack.source = 'answer';
  12358. $(document).trigger('ack.jingle', [self.sid, ack]);
  12359. },
  12360. function (stanza) {
  12361. var error = ($(stanza).find('error').length) ? {
  12362. code: $(stanza).find('error').attr('code'),
  12363. reason: $(stanza).find('error :first')[0].tagName
  12364. }:{};
  12365. error.source = 'answer';
  12366. JingleSessionPC.onJingleError(self.sid, error);
  12367. },
  12368. 10000);
  12369. },
  12370. function (e) {
  12371. console.error('setLocalDescription failed', e);
  12372. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12373. }
  12374. );
  12375. };
  12376. JingleSessionPC.prototype.terminate = function (reason) {
  12377. this.state = 'ended';
  12378. this.reason = reason;
  12379. this.peerconnection.close();
  12380. if (this.statsinterval !== null) {
  12381. window.clearInterval(this.statsinterval);
  12382. this.statsinterval = null;
  12383. }
  12384. };
  12385. JingleSessionPC.prototype.active = function () {
  12386. return this.state == 'active';
  12387. };
  12388. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  12389. var self = this;
  12390. if (candidate && !this.lasticecandidate) {
  12391. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  12392. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  12393. if (!(ice && jcand)) {
  12394. console.error('failed to get ice && jcand');
  12395. return;
  12396. }
  12397. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12398. if (jcand.type === 'srflx') {
  12399. this.hadstuncandidate = true;
  12400. } else if (jcand.type === 'relay') {
  12401. this.hadturncandidate = true;
  12402. }
  12403. if (this.usetrickle) {
  12404. if (this.usedrip) {
  12405. if (this.drip_container.length === 0) {
  12406. // start 20ms callout
  12407. window.setTimeout(function () {
  12408. if (self.drip_container.length === 0) return;
  12409. self.sendIceCandidates(self.drip_container);
  12410. self.drip_container = [];
  12411. }, 20);
  12412. }
  12413. this.drip_container.push(candidate);
  12414. return;
  12415. } else {
  12416. self.sendIceCandidate([candidate]);
  12417. }
  12418. }
  12419. } else {
  12420. //console.log('sendIceCandidate: last candidate.');
  12421. if (!this.usetrickle) {
  12422. //console.log('should send full offer now...');
  12423. //FIXME why do we generate session-accept in 3 different places ?
  12424. var init = $iq({to: this.peerjid,
  12425. type: 'set'})
  12426. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12427. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  12428. initiator: this.initiator,
  12429. sid: this.sid});
  12430. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  12431. var sendJingle = function (ssrc) {
  12432. if(!ssrc)
  12433. ssrc = {};
  12434. self.localSDP.toJingle(
  12435. init,
  12436. self.initiator == self.me ? 'initiator' : 'responder',
  12437. ssrc);
  12438. SSRCReplacement.processSessionInit(init);
  12439. self.connection.sendIQ(init,
  12440. function () {
  12441. //console.log('session initiate ack');
  12442. var ack = {};
  12443. ack.source = 'offer';
  12444. $(document).trigger('ack.jingle', [self.sid, ack]);
  12445. },
  12446. function (stanza) {
  12447. self.state = 'error';
  12448. self.peerconnection.close();
  12449. var error = ($(stanza).find('error').length) ? {
  12450. code: $(stanza).find('error').attr('code'),
  12451. reason: $(stanza).find('error :first')[0].tagName,
  12452. }:{};
  12453. error.source = 'offer';
  12454. JingleSessionPC.onJingleError(self.sid, error);
  12455. },
  12456. 10000);
  12457. };
  12458. sendJingle();
  12459. }
  12460. this.lasticecandidate = true;
  12461. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  12462. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  12463. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  12464. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  12465. }
  12466. }
  12467. };
  12468. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  12469. console.log('sendIceCandidates', candidates);
  12470. var cand = $iq({to: this.peerjid, type: 'set'})
  12471. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12472. action: 'transport-info',
  12473. initiator: this.initiator,
  12474. sid: this.sid});
  12475. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  12476. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  12477. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  12478. if (cands.length > 0) {
  12479. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  12480. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12481. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  12482. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  12483. }).c('transport', ice);
  12484. for (var i = 0; i < cands.length; i++) {
  12485. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  12486. }
  12487. // add fingerprint
  12488. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  12489. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  12490. tmp.required = true;
  12491. cand.c(
  12492. 'fingerprint',
  12493. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  12494. .t(tmp.fingerprint);
  12495. delete tmp.fingerprint;
  12496. cand.attrs(tmp);
  12497. cand.up();
  12498. }
  12499. cand.up(); // transport
  12500. cand.up(); // content
  12501. }
  12502. }
  12503. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  12504. //console.log('was this the last candidate', this.lasticecandidate);
  12505. this.connection.sendIQ(cand,
  12506. function () {
  12507. var ack = {};
  12508. ack.source = 'transportinfo';
  12509. $(document).trigger('ack.jingle', [this.sid, ack]);
  12510. },
  12511. function (stanza) {
  12512. var error = ($(stanza).find('error').length) ? {
  12513. code: $(stanza).find('error').attr('code'),
  12514. reason: $(stanza).find('error :first')[0].tagName,
  12515. }:{};
  12516. error.source = 'transportinfo';
  12517. JingleSessionPC.onJingleError(this.sid, error);
  12518. },
  12519. 10000);
  12520. };
  12521. JingleSessionPC.prototype.sendOffer = function () {
  12522. //console.log('sendOffer...');
  12523. var self = this;
  12524. this.peerconnection.createOffer(function (sdp) {
  12525. self.createdOffer(sdp);
  12526. },
  12527. function (e) {
  12528. console.error('createOffer failed', e);
  12529. },
  12530. this.media_constraints
  12531. );
  12532. };
  12533. // FIXME createdOffer is never used in jitsi-meet
  12534. JingleSessionPC.prototype.createdOffer = function (sdp) {
  12535. //console.log('createdOffer', sdp);
  12536. var self = this;
  12537. this.localSDP = new SDP(sdp.sdp);
  12538. //this.localSDP.mangle();
  12539. var sendJingle = function () {
  12540. var init = $iq({to: this.peerjid,
  12541. type: 'set'})
  12542. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12543. action: 'session-initiate',
  12544. initiator: this.initiator,
  12545. sid: this.sid});
  12546. self.localSDP.toJingle(
  12547. init,
  12548. this.initiator == this.me ? 'initiator' : 'responder',
  12549. this.localStreamsSSRC);
  12550. SSRCReplacement.processSessionInit(init);
  12551. self.connection.sendIQ(init,
  12552. function () {
  12553. var ack = {};
  12554. ack.source = 'offer';
  12555. $(document).trigger('ack.jingle', [self.sid, ack]);
  12556. },
  12557. function (stanza) {
  12558. self.state = 'error';
  12559. self.peerconnection.close();
  12560. var error = ($(stanza).find('error').length) ? {
  12561. code: $(stanza).find('error').attr('code'),
  12562. reason: $(stanza).find('error :first')[0].tagName,
  12563. }:{};
  12564. error.source = 'offer';
  12565. JingleSessionPC.onJingleError(self.sid, error);
  12566. },
  12567. 10000);
  12568. }
  12569. sdp.sdp = this.localSDP.raw;
  12570. this.peerconnection.setLocalDescription(sdp,
  12571. function () {
  12572. if(self.usetrickle)
  12573. {
  12574. sendJingle();
  12575. }
  12576. self.setLocalDescription();
  12577. //console.log('setLocalDescription success');
  12578. },
  12579. function (e) {
  12580. console.error('setLocalDescription failed', e);
  12581. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12582. }
  12583. );
  12584. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12585. for (var i = 0; i < cands.length; i++) {
  12586. var cand = SDPUtil.parse_icecandidate(cands[i]);
  12587. if (cand.type == 'srflx') {
  12588. this.hadstuncandidate = true;
  12589. } else if (cand.type == 'relay') {
  12590. this.hadturncandidate = true;
  12591. }
  12592. }
  12593. };
  12594. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  12595. var self = this;
  12596. $(contents).each(function (idx, content) {
  12597. var name = $(content).attr('name');
  12598. var mediaType = this.getAttribute('name');
  12599. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12600. ssrcs.each(function () {
  12601. var ssrc = this.getAttribute('ssrc');
  12602. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  12603. function () {
  12604. var owner = this.getAttribute('owner');
  12605. self.ssrcOwners[ssrc] = owner;
  12606. }
  12607. );
  12608. });
  12609. });
  12610. };
  12611. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  12612. return this.ssrcOwners[ssrc];
  12613. };
  12614. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  12615. //console.log('setting remote description... ', desctype);
  12616. this.remoteSDP = new SDP('');
  12617. this.remoteSDP.fromJingle(elem);
  12618. this.readSsrcInfo($(elem).find(">content"));
  12619. if (this.peerconnection.remoteDescription !== null) {
  12620. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12621. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12622. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12623. for (var i = 0; i < pranswer.media.length; i++) {
  12624. // make sure we have ice ufrag and pwd
  12625. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12626. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12627. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12628. } else {
  12629. console.warn('no ice ufrag?');
  12630. }
  12631. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12632. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12633. } else {
  12634. console.warn('no ice pwd?');
  12635. }
  12636. }
  12637. // copy over candidates
  12638. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12639. for (var j = 0; j < lines.length; j++) {
  12640. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12641. }
  12642. }
  12643. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12644. }
  12645. }
  12646. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12647. this.peerconnection.setRemoteDescription(remotedesc,
  12648. function () {
  12649. //console.log('setRemoteDescription success');
  12650. },
  12651. function (e) {
  12652. console.error('setRemoteDescription error', e);
  12653. JingleSessionPC.onJingleFatalError(self, e);
  12654. }
  12655. );
  12656. };
  12657. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  12658. var self = this;
  12659. if (this.peerconnection.signalingState == 'closed') {
  12660. return;
  12661. }
  12662. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12663. console.log('trickle ice candidate arriving before session accept...');
  12664. // create a PRANSWER for setRemoteDescription
  12665. if (!this.remoteSDP) {
  12666. var cobbled = 'v=0\r\n' +
  12667. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12668. 's=-\r\n' +
  12669. 't=0 0\r\n';
  12670. // first, take some things from the local description
  12671. for (var i = 0; i < this.localSDP.media.length; i++) {
  12672. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12673. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12674. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12675. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12676. }
  12677. cobbled += 'a=inactive\r\n';
  12678. }
  12679. this.remoteSDP = new SDP(cobbled);
  12680. }
  12681. // then add things like ice and dtls from remote candidate
  12682. elem.each(function () {
  12683. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12684. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12685. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12686. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12687. var tmp = $(this).find('transport');
  12688. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12689. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12690. tmp = $(this).find('transport>fingerprint');
  12691. if (tmp.length) {
  12692. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12693. } else {
  12694. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12695. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12696. }
  12697. break;
  12698. }
  12699. }
  12700. }
  12701. });
  12702. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12703. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12704. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12705. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12706. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12707. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12708. }).length == this.remoteSDP.media.length;
  12709. if (iscomplete) {
  12710. console.log('setting pranswer');
  12711. try {
  12712. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12713. function() {
  12714. },
  12715. function(e) {
  12716. console.log('setRemoteDescription pranswer failed', e.toString());
  12717. });
  12718. } catch (e) {
  12719. console.error('setting pranswer failed', e);
  12720. }
  12721. } else {
  12722. //console.log('not yet setting pranswer');
  12723. }
  12724. }
  12725. // operate on each content element
  12726. elem.each(function () {
  12727. // would love to deactivate this, but firefox still requires it
  12728. var idx = -1;
  12729. var i;
  12730. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12731. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12732. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12733. idx = i;
  12734. break;
  12735. }
  12736. }
  12737. if (idx == -1) { // fall back to localdescription
  12738. for (i = 0; i < self.localSDP.media.length; i++) {
  12739. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12740. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12741. idx = i;
  12742. break;
  12743. }
  12744. }
  12745. }
  12746. var name = $(this).attr('name');
  12747. // TODO: check ice-pwd and ice-ufrag?
  12748. $(this).find('transport>candidate').each(function () {
  12749. var line, candidate;
  12750. line = SDPUtil.candidateFromJingle(this);
  12751. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12752. sdpMid: name,
  12753. candidate: line});
  12754. try {
  12755. self.peerconnection.addIceCandidate(candidate);
  12756. } catch (e) {
  12757. console.error('addIceCandidate failed', e.toString(), line);
  12758. }
  12759. });
  12760. });
  12761. };
  12762. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  12763. //console.log('createAnswer', provisional);
  12764. var self = this;
  12765. this.peerconnection.createAnswer(
  12766. function (sdp) {
  12767. self.createdAnswer(sdp, provisional);
  12768. },
  12769. function (e) {
  12770. console.error('createAnswer failed', e);
  12771. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12772. },
  12773. this.media_constraints
  12774. );
  12775. };
  12776. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  12777. //console.log('createAnswer callback');
  12778. var self = this;
  12779. this.localSDP = new SDP(sdp.sdp);
  12780. //this.localSDP.mangle();
  12781. this.usepranswer = provisional === true;
  12782. if (this.usetrickle) {
  12783. if (this.usepranswer) {
  12784. sdp.type = 'pranswer';
  12785. for (var i = 0; i < this.localSDP.media.length; i++) {
  12786. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12787. }
  12788. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12789. }
  12790. }
  12791. var self = this;
  12792. var sendJingle = function (ssrcs) {
  12793. // FIXME why do we generate session-accept in 3 different places ?
  12794. var accept = $iq({to: self.peerjid,
  12795. type: 'set'})
  12796. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12797. action: 'session-accept',
  12798. initiator: self.initiator,
  12799. responder: self.responder,
  12800. sid: self.sid });
  12801. self.localSDP.toJingle(
  12802. accept,
  12803. self.initiator == self.me ? 'initiator' : 'responder',
  12804. ssrcs);
  12805. SSRCReplacement.processSessionInit(accept);
  12806. self.connection.sendIQ(accept,
  12807. function () {
  12808. var ack = {};
  12809. ack.source = 'answer';
  12810. $(document).trigger('ack.jingle', [self.sid, ack]);
  12811. },
  12812. function (stanza) {
  12813. var error = ($(stanza).find('error').length) ? {
  12814. code: $(stanza).find('error').attr('code'),
  12815. reason: $(stanza).find('error :first')[0].tagName,
  12816. }:{};
  12817. error.source = 'answer';
  12818. JingleSessionPC.onJingleError(self.sid, error);
  12819. },
  12820. 10000);
  12821. }
  12822. sdp.sdp = this.localSDP.raw;
  12823. this.peerconnection.setLocalDescription(sdp,
  12824. function () {
  12825. //console.log('setLocalDescription success');
  12826. if (self.usetrickle && !self.usepranswer) {
  12827. sendJingle();
  12828. }
  12829. self.setLocalDescription();
  12830. },
  12831. function (e) {
  12832. console.error('setLocalDescription failed', e);
  12833. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12834. }
  12835. );
  12836. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12837. for (var j = 0; j < cands.length; j++) {
  12838. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12839. if (cand.type == 'srflx') {
  12840. this.hadstuncandidate = true;
  12841. } else if (cand.type == 'relay') {
  12842. this.hadturncandidate = true;
  12843. }
  12844. }
  12845. };
  12846. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  12847. var self = this,
  12848. term = $iq({to: this.peerjid,
  12849. type: 'set'})
  12850. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12851. action: 'session-terminate',
  12852. initiator: this.initiator,
  12853. sid: this.sid})
  12854. .c('reason')
  12855. .c(reason || 'success');
  12856. if (text) {
  12857. term.up().c('text').t(text);
  12858. }
  12859. this.connection.sendIQ(term,
  12860. function () {
  12861. self.peerconnection.close();
  12862. self.peerconnection = null;
  12863. self.terminate();
  12864. var ack = {};
  12865. ack.source = 'terminate';
  12866. $(document).trigger('ack.jingle', [self.sid, ack]);
  12867. },
  12868. function (stanza) {
  12869. var error = ($(stanza).find('error').length) ? {
  12870. code: $(stanza).find('error').attr('code'),
  12871. reason: $(stanza).find('error :first')[0].tagName,
  12872. }:{};
  12873. $(document).trigger('ack.jingle', [self.sid, error]);
  12874. },
  12875. 10000);
  12876. if (this.statsinterval !== null) {
  12877. window.clearInterval(this.statsinterval);
  12878. this.statsinterval = null;
  12879. }
  12880. };
  12881. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  12882. var self = this;
  12883. // FIXME: dirty waiting
  12884. if (!this.peerconnection.localDescription)
  12885. {
  12886. console.warn("addSource - localDescription not ready yet")
  12887. setTimeout(function()
  12888. {
  12889. self.addSource(elem, fromJid);
  12890. },
  12891. 200
  12892. );
  12893. return;
  12894. }
  12895. console.log('addssrc', new Date().getTime());
  12896. console.log('ice', this.peerconnection.iceConnectionState);
  12897. this.readSsrcInfo(elem);
  12898. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12899. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12900. $(elem).each(function (idx, content) {
  12901. var name = $(content).attr('name');
  12902. var lines = '';
  12903. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12904. var semantics = this.getAttribute('semantics');
  12905. var ssrcs = $(this).find('>source').map(function () {
  12906. return this.getAttribute('ssrc');
  12907. }).get();
  12908. if (ssrcs.length != 0) {
  12909. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12910. }
  12911. });
  12912. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12913. tmp.each(function () {
  12914. var ssrc = $(this).attr('ssrc');
  12915. if(mySdp.containsSSRC(ssrc)){
  12916. /**
  12917. * This happens when multiple participants change their streams at the same time and
  12918. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12919. * addssrc are scheduled for update IQ. See
  12920. */
  12921. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12922. return;
  12923. }
  12924. if (sdp.containsSSRC(ssrc)) {
  12925. console.warn("Source-add request for existing SSRC: " + ssrc);
  12926. return;
  12927. }
  12928. $(this).find('>parameter').each(function () {
  12929. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12930. if ($(this).attr('value') && $(this).attr('value').length)
  12931. lines += ':' + $(this).attr('value');
  12932. lines += '\r\n';
  12933. });
  12934. });
  12935. sdp.media.forEach(function(media, idx) {
  12936. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12937. return;
  12938. sdp.media[idx] += lines;
  12939. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12940. self.addssrc[idx] += lines;
  12941. });
  12942. sdp.raw = sdp.session + sdp.media.join('');
  12943. });
  12944. this.modifySourcesQueue.push(function() {
  12945. // When a source is added and if this is FF, a new channel is allocated
  12946. // for receiving the added source. We need to diffuse the SSRC of this
  12947. // new recvonly channel to the rest of the peers.
  12948. console.log('modify sources done');
  12949. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12950. console.log("SDPs", mySdp, newSdp);
  12951. self.notifyMySSRCUpdate(mySdp, newSdp);
  12952. });
  12953. };
  12954. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  12955. var self = this;
  12956. // FIXME: dirty waiting
  12957. if (!this.peerconnection.localDescription)
  12958. {
  12959. console.warn("removeSource - localDescription not ready yet")
  12960. setTimeout(function()
  12961. {
  12962. self.removeSource(elem, fromJid);
  12963. },
  12964. 200
  12965. );
  12966. return;
  12967. }
  12968. console.log('removessrc', new Date().getTime());
  12969. console.log('ice', this.peerconnection.iceConnectionState);
  12970. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12971. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12972. $(elem).each(function (idx, content) {
  12973. var name = $(content).attr('name');
  12974. var lines = '';
  12975. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12976. var semantics = this.getAttribute('semantics');
  12977. var ssrcs = $(this).find('>source').map(function () {
  12978. return this.getAttribute('ssrc');
  12979. }).get();
  12980. if (ssrcs.length != 0) {
  12981. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12982. }
  12983. });
  12984. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12985. tmp.each(function () {
  12986. var ssrc = $(this).attr('ssrc');
  12987. // This should never happen, but can be useful for bug detection
  12988. if(mySdp.containsSSRC(ssrc)){
  12989. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12990. return;
  12991. }
  12992. $(this).find('>parameter').each(function () {
  12993. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12994. if ($(this).attr('value') && $(this).attr('value').length)
  12995. lines += ':' + $(this).attr('value');
  12996. lines += '\r\n';
  12997. });
  12998. });
  12999. sdp.media.forEach(function(media, idx) {
  13000. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  13001. return;
  13002. sdp.media[idx] += lines;
  13003. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  13004. self.removessrc[idx] += lines;
  13005. });
  13006. sdp.raw = sdp.session + sdp.media.join('');
  13007. });
  13008. this.modifySourcesQueue.push(function() {
  13009. // When a source is removed and if this is FF, the recvonly channel that
  13010. // receives the remote stream is deactivated . We need to diffuse the
  13011. // recvonly SSRC removal to the rest of the peers.
  13012. console.log('modify sources done');
  13013. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  13014. console.log("SDPs", mySdp, newSdp);
  13015. self.notifyMySSRCUpdate(mySdp, newSdp);
  13016. });
  13017. };
  13018. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  13019. var self = this;
  13020. if (this.peerconnection.signalingState == 'closed') return;
  13021. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  13022. // There is nothing to do since scheduled job might have been executed by another succeeding call
  13023. this.setLocalDescription();
  13024. if(successCallback){
  13025. successCallback();
  13026. }
  13027. queueCallback();
  13028. return;
  13029. }
  13030. // Reset switch streams flag
  13031. this.switchstreams = false;
  13032. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  13033. // add sources
  13034. this.addssrc.forEach(function(lines, idx) {
  13035. sdp.media[idx] += lines;
  13036. });
  13037. this.addssrc = [];
  13038. // remove sources
  13039. this.removessrc.forEach(function(lines, idx) {
  13040. lines = lines.split('\r\n');
  13041. lines.pop(); // remove empty last element;
  13042. lines.forEach(function(line) {
  13043. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  13044. });
  13045. });
  13046. this.removessrc = [];
  13047. sdp.raw = sdp.session + sdp.media.join('');
  13048. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  13049. function() {
  13050. if(self.signalingState == 'closed') {
  13051. console.error("createAnswer attempt on closed state");
  13052. queueCallback("createAnswer attempt on closed state");
  13053. return;
  13054. }
  13055. self.peerconnection.createAnswer(
  13056. function(modifiedAnswer) {
  13057. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  13058. if (self.pendingop !== null) {
  13059. var sdp = new SDP(modifiedAnswer.sdp);
  13060. if (sdp.media.length > 1) {
  13061. switch(self.pendingop) {
  13062. case 'mute':
  13063. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  13064. break;
  13065. case 'unmute':
  13066. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  13067. break;
  13068. }
  13069. sdp.raw = sdp.session + sdp.media.join('');
  13070. modifiedAnswer.sdp = sdp.raw;
  13071. }
  13072. self.pendingop = null;
  13073. }
  13074. // FIXME: pushing down an answer while ice connection state
  13075. // is still checking is bad...
  13076. //console.log(self.peerconnection.iceConnectionState);
  13077. // trying to work around another chrome bug
  13078. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  13079. self.peerconnection.setLocalDescription(modifiedAnswer,
  13080. function() {
  13081. //console.log('modified setLocalDescription ok');
  13082. self.setLocalDescription();
  13083. if(successCallback){
  13084. successCallback();
  13085. }
  13086. queueCallback();
  13087. },
  13088. function(error) {
  13089. console.error('modified setLocalDescription failed', error);
  13090. queueCallback(error);
  13091. }
  13092. );
  13093. },
  13094. function(error) {
  13095. console.error('modified answer failed', error);
  13096. queueCallback(error);
  13097. }
  13098. );
  13099. },
  13100. function(error) {
  13101. console.error('modify failed', error);
  13102. queueCallback(error);
  13103. }
  13104. );
  13105. };
  13106. /**
  13107. * Switches video streams.
  13108. * @param new_stream new stream that will be used as video of this session.
  13109. * @param oldStream old video stream of this session.
  13110. * @param success_callback callback executed after successful stream switch.
  13111. */
  13112. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  13113. var self = this;
  13114. // Remember SDP to figure out added/removed SSRCs
  13115. var oldSdp = null;
  13116. if(self.peerconnection) {
  13117. if(self.peerconnection.localDescription) {
  13118. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  13119. }
  13120. self.peerconnection.removeStream(oldStream, true);
  13121. if(new_stream)
  13122. self.peerconnection.addStream(new_stream);
  13123. }
  13124. // Conference is not active
  13125. if(!oldSdp || !self.peerconnection) {
  13126. success_callback();
  13127. return;
  13128. }
  13129. self.switchstreams = true;
  13130. self.modifySourcesQueue.push(function() {
  13131. console.log('modify sources done');
  13132. success_callback();
  13133. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  13134. console.log("SDPs", oldSdp, newSdp);
  13135. self.notifyMySSRCUpdate(oldSdp, newSdp);
  13136. });
  13137. };
  13138. /**
  13139. * Figures out added/removed ssrcs and send update IQs.
  13140. * @param old_sdp SDP object for old description.
  13141. * @param new_sdp SDP object for new description.
  13142. */
  13143. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  13144. if (!(this.peerconnection.signalingState == 'stable' &&
  13145. this.peerconnection.iceConnectionState == 'connected')){
  13146. console.log("Too early to send updates");
  13147. return;
  13148. }
  13149. // send source-remove IQ.
  13150. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  13151. var remove = $iq({to: this.peerjid, type: 'set'})
  13152. .c('jingle', {
  13153. xmlns: 'urn:xmpp:jingle:1',
  13154. action: 'source-remove',
  13155. initiator: this.initiator,
  13156. sid: this.sid
  13157. }
  13158. );
  13159. var removed = sdpDiffer.toJingle(remove);
  13160. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  13161. // it in the current form
  13162. if (removed)
  13163. remove = SSRCReplacement.processSourceRemove(remove);
  13164. if (removed && remove) {
  13165. console.info("Sending source-remove", remove);
  13166. this.connection.sendIQ(remove,
  13167. function (res) {
  13168. console.info('got remove result', res);
  13169. },
  13170. function (err) {
  13171. console.error('got remove error', err);
  13172. }
  13173. );
  13174. } else {
  13175. console.log('removal not necessary');
  13176. }
  13177. // send source-add IQ.
  13178. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  13179. var add = $iq({to: this.peerjid, type: 'set'})
  13180. .c('jingle', {
  13181. xmlns: 'urn:xmpp:jingle:1',
  13182. action: 'source-add',
  13183. initiator: this.initiator,
  13184. sid: this.sid
  13185. }
  13186. );
  13187. var added = sdpDiffer.toJingle(add);
  13188. // Let 'source-add' IQ through the hack and see if we're allowed to send
  13189. // it in the current form
  13190. if (added)
  13191. add = SSRCReplacement.processSourceAdd(add);
  13192. if (added && add) {
  13193. console.info("Sending source-add", add);
  13194. this.connection.sendIQ(add,
  13195. function (res) {
  13196. console.info('got add result', res);
  13197. },
  13198. function (err) {
  13199. console.error('got add error', err);
  13200. }
  13201. );
  13202. } else {
  13203. console.log('addition not necessary');
  13204. }
  13205. };
  13206. /**
  13207. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  13208. *
  13209. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  13210. * tracks; otherwise, <tt>false</tt>
  13211. * @param callback a function to be invoked with <tt>mute</tt> after all video
  13212. * tracks have been enabled/disabled. The function may, optionally, return
  13213. * another function which is to be invoked after the whole mute/unmute operation
  13214. * has completed successfully.
  13215. * @param options an object which specifies optional arguments such as the
  13216. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  13217. * specifies whether the method was initiated in response to a user command (in
  13218. * contrast to an automatic decision made by the application logic)
  13219. */
  13220. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  13221. var byUser;
  13222. if (options) {
  13223. byUser = options.byUser;
  13224. if (typeof byUser === 'undefined') {
  13225. byUser = true;
  13226. }
  13227. } else {
  13228. byUser = true;
  13229. }
  13230. // The user's command to mute the (local) video takes precedence over any
  13231. // automatic decision made by the application logic.
  13232. if (byUser) {
  13233. this.videoMuteByUser = mute;
  13234. } else if (this.videoMuteByUser) {
  13235. return;
  13236. }
  13237. this.hardMuteVideo(mute);
  13238. var self = this;
  13239. var oldSdp = null;
  13240. if(self.peerconnection) {
  13241. if(self.peerconnection.localDescription) {
  13242. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  13243. }
  13244. }
  13245. this.modifySourcesQueue.push(function() {
  13246. console.log('modify sources done');
  13247. callback(mute);
  13248. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  13249. console.log("SDPs", oldSdp, newSdp);
  13250. self.notifyMySSRCUpdate(oldSdp, newSdp);
  13251. });
  13252. };
  13253. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  13254. this.pendingop = muted ? 'mute' : 'unmute';
  13255. };
  13256. JingleSessionPC.prototype.sendMute = function (muted, content) {
  13257. var info = $iq({to: this.peerjid,
  13258. type: 'set'})
  13259. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  13260. action: 'session-info',
  13261. initiator: this.initiator,
  13262. sid: this.sid });
  13263. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  13264. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  13265. if (content) {
  13266. info.attrs({'name': content});
  13267. }
  13268. this.connection.send(info);
  13269. };
  13270. JingleSessionPC.prototype.sendRinging = function () {
  13271. var info = $iq({to: this.peerjid,
  13272. type: 'set'})
  13273. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  13274. action: 'session-info',
  13275. initiator: this.initiator,
  13276. sid: this.sid });
  13277. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  13278. this.connection.send(info);
  13279. };
  13280. JingleSessionPC.prototype.getStats = function (interval) {
  13281. var self = this;
  13282. var recv = {audio: 0, video: 0};
  13283. var lost = {audio: 0, video: 0};
  13284. var lastrecv = {audio: 0, video: 0};
  13285. var lastlost = {audio: 0, video: 0};
  13286. var loss = {audio: 0, video: 0};
  13287. var delta = {audio: 0, video: 0};
  13288. this.statsinterval = window.setInterval(function () {
  13289. if (self && self.peerconnection && self.peerconnection.getStats) {
  13290. self.peerconnection.getStats(function (stats) {
  13291. var results = stats.result();
  13292. // TODO: there are so much statistics you can get from this..
  13293. for (var i = 0; i < results.length; ++i) {
  13294. if (results[i].type == 'ssrc') {
  13295. var packetsrecv = results[i].stat('packetsReceived');
  13296. var packetslost = results[i].stat('packetsLost');
  13297. if (packetsrecv && packetslost) {
  13298. packetsrecv = parseInt(packetsrecv, 10);
  13299. packetslost = parseInt(packetslost, 10);
  13300. if (results[i].stat('googFrameRateReceived')) {
  13301. lastlost.video = lost.video;
  13302. lastrecv.video = recv.video;
  13303. recv.video = packetsrecv;
  13304. lost.video = packetslost;
  13305. } else {
  13306. lastlost.audio = lost.audio;
  13307. lastrecv.audio = recv.audio;
  13308. recv.audio = packetsrecv;
  13309. lost.audio = packetslost;
  13310. }
  13311. }
  13312. }
  13313. }
  13314. delta.audio = recv.audio - lastrecv.audio;
  13315. delta.video = recv.video - lastrecv.video;
  13316. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  13317. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  13318. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  13319. });
  13320. }
  13321. }, interval || 3000);
  13322. return this.statsinterval;
  13323. };
  13324. JingleSessionPC.onJingleError = function (session, error)
  13325. {
  13326. console.error("Jingle error", error);
  13327. }
  13328. JingleSessionPC.onJingleFatalError = function (session, error)
  13329. {
  13330. this.service.sessionTerminated = true;
  13331. this.connection.emuc.doLeave();
  13332. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  13333. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  13334. }
  13335. JingleSessionPC.prototype.setLocalDescription = function () {
  13336. var self = this;
  13337. var newssrcs = [];
  13338. var session = transform.parse(this.peerconnection.localDescription.sdp);
  13339. session.media.forEach(function (media) {
  13340. if (media.ssrcs != null && media.ssrcs.length > 0) {
  13341. // TODO(gp) maybe exclude FID streams?
  13342. media.ssrcs.forEach(function (ssrc) {
  13343. if (ssrc.attribute !== 'cname') {
  13344. return;
  13345. }
  13346. newssrcs.push({
  13347. 'ssrc': ssrc.id,
  13348. 'type': media.type
  13349. });
  13350. });
  13351. }
  13352. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  13353. {
  13354. newssrcs.push({
  13355. 'ssrc': self.localStreamsSSRC[media.type],
  13356. 'type': media.type
  13357. });
  13358. }
  13359. });
  13360. console.log('new ssrcs', newssrcs);
  13361. // Bind us as local SSRCs owner
  13362. if (newssrcs.length > 0) {
  13363. for (var i = 1; i <= newssrcs.length; i ++) {
  13364. var ssrc = newssrcs[i-1].ssrc;
  13365. var myJid = self.connection.emuc.myroomjid;
  13366. self.ssrcOwners[ssrc] = myJid;
  13367. }
  13368. }
  13369. }
  13370. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  13371. // TODO: is this hack (along with the XMPPEvent-s used only for it) still needed
  13372. // now that we announce an SSRC for receive-only streams?
  13373. function sendKeyframe(pc) {
  13374. console.log('sendkeyframe', pc.iceConnectionState);
  13375. if (pc.iceConnectionState !== 'connected') return; // safe...
  13376. pc.setRemoteDescription(
  13377. pc.remoteDescription,
  13378. function () {
  13379. pc.createAnswer(
  13380. function (modifiedAnswer) {
  13381. pc.setLocalDescription(
  13382. modifiedAnswer,
  13383. function () {
  13384. // noop
  13385. },
  13386. function (error) {
  13387. console.log('triggerKeyframe setLocalDescription failed', error);
  13388. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  13389. }
  13390. );
  13391. },
  13392. function (error) {
  13393. console.log('triggerKeyframe createAnswer failed', error);
  13394. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  13395. }
  13396. );
  13397. },
  13398. function (error) {
  13399. console.log('triggerKeyframe setRemoteDescription failed', error);
  13400. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  13401. }
  13402. );
  13403. }
  13404. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  13405. var self = this;
  13406. var thessrc;
  13407. var streamId = APP.RTC.getStreamID(data.stream);
  13408. // look up an associated JID for a stream id
  13409. if (!streamId) {
  13410. console.error("No stream ID for", data.stream);
  13411. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  13412. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  13413. var ssrclines
  13414. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  13415. ssrclines = ssrclines.filter(function (line) {
  13416. // NOTE(gp) previously we filtered on the mslabel, but that property
  13417. // is not always present.
  13418. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  13419. if (RTCBrowserType.isTemasysPluginUsed()) {
  13420. return ((line.indexOf('mslabel:' + streamId) !== -1));
  13421. } else {
  13422. return ((line.indexOf('msid:' + streamId) !== -1));
  13423. }
  13424. });
  13425. if (ssrclines.length) {
  13426. thessrc = ssrclines[0].substring(7).split(' ')[0];
  13427. if (!self.ssrcOwners[thessrc]) {
  13428. console.error("No SSRC owner known for: " + thessrc);
  13429. return;
  13430. }
  13431. data.peerjid = self.ssrcOwners[thessrc];
  13432. console.log('associated jid', self.ssrcOwners[thessrc]);
  13433. } else {
  13434. console.error("No SSRC lines for ", streamId);
  13435. }
  13436. }
  13437. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  13438. var isVideo = data.stream.getVideoTracks().length > 0;
  13439. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  13440. // TODO: is this hack still needed now that we announce an SSRC for
  13441. // receive-only streams?
  13442. if (isVideo &&
  13443. data.peerjid && this.peerjid === data.peerjid &&
  13444. data.stream.getVideoTracks().length === 0 &&
  13445. APP.RTC.localVideo.getTracks().length > 0) {
  13446. window.setTimeout(function () {
  13447. sendKeyframe(self.peerconnection);
  13448. }, 3000);
  13449. }
  13450. }
  13451. module.exports = JingleSessionPC;
  13452. },{"../../service/xmpp/XMPPEvents":174,"../RTC/RTCBrowserType":10,"./JingleSession":57,"./LocalSSRCReplacement":59,"./SDP":60,"./SDPDiffer":61,"./SDPUtil":62,"./TraceablePeerConnection":63,"async":74,"sdp-transform":111}],59:[function(require,module,exports){
  13453. /* global $ */
  13454. /*
  13455. Here we do modifications of local video SSRCs. There are 2 situations we have
  13456. to handle:
  13457. 1. We generate SSRC for local recvonly video stream. This is the case when we
  13458. have no local camera and it is not generated automatically, but SSRC=1 is
  13459. used implicitly. If that happens RTCP packets will be dropped by the JVB
  13460. and we won't be able to request video key frames correctly.
  13461. 2. A hack to re-use SSRC of the first video stream for any new stream created
  13462. in future. It turned out that Chrome may keep on using the SSRC of removed
  13463. video stream in RTCP even though a new one has been created. So we just
  13464. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  13465. notifications are blocked once first video SSRC is advertised to the focus.
  13466. What this hack does:
  13467. 1. Stores the SSRC of the first video stream created by
  13468. a) scanning Jingle session-accept/session-invite for existing video SSRC
  13469. b) watching for 'source-add' for new video stream if it has not been
  13470. created in step a)
  13471. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  13472. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  13473. returned to the other parts of the application.
  13474. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  13475. blocks those notifications. This makes Jicofo and all participants think
  13476. that it exists all the time even if the video stream has been removed or
  13477. replaced locally. Thanks to that there is no additional signaling activity
  13478. on video mute or when switching to the desktop stream.
  13479. */
  13480. var SDP = require('./SDP');
  13481. var RTCBrowserType = require('../RTC/RTCBrowserType');
  13482. /**
  13483. * The hack is enabled on all browsers except FF by default
  13484. * FIXME finish the hack once removeStream method is implemented in FF
  13485. * @type {boolean}
  13486. */
  13487. var isEnabled = !RTCBrowserType.isFirefox();
  13488. /**
  13489. * Stored SSRC of local video stream.
  13490. */
  13491. var localVideoSSRC;
  13492. /**
  13493. * SSRC used for recvonly video stream when we have no local camera.
  13494. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  13495. * instead of 1.
  13496. */
  13497. var localRecvOnlySSRC;
  13498. /**
  13499. * cname for <tt>localRecvOnlySSRC</tt>
  13500. */
  13501. var localRecvOnlyCName;
  13502. /**
  13503. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  13504. * from given Jingle IQ.
  13505. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  13506. * @param actionName display name of the action which will be printed in log
  13507. * messages.
  13508. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  13509. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  13510. * other SSRCs left to be signaled after removing it.
  13511. */
  13512. var filterOutSource = function (modifyIq, actionName) {
  13513. var modifyIqTree = $(modifyIq.tree());
  13514. if (!localVideoSSRC)
  13515. return modifyIqTree[0];
  13516. var videoSSRC = modifyIqTree.find(
  13517. '>jingle>content[name="video"]' +
  13518. '>description>source[ssrc="' + localVideoSSRC + '"]');
  13519. if (!videoSSRC.length) {
  13520. return modifyIqTree[0];
  13521. }
  13522. console.info(
  13523. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  13524. videoSSRC.remove();
  13525. // Check if any sources still left to be added/removed
  13526. if (modifyIqTree.find('>jingle>content>description>source').length) {
  13527. return modifyIqTree[0];
  13528. } else {
  13529. return null;
  13530. }
  13531. };
  13532. /**
  13533. * Scans given Jingle IQ for video SSRC and stores it.
  13534. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  13535. */
  13536. var storeLocalVideoSSRC = function (jingleIq) {
  13537. var videoSSRCs =
  13538. $(jingleIq.tree())
  13539. .find('>jingle>content[name="video"]>description>source');
  13540. videoSSRCs.each(function (idx, ssrcElem) {
  13541. if (localVideoSSRC)
  13542. return;
  13543. // We consider SSRC real only if it has msid attribute
  13544. // recvonly streams in FF do not have it as well as local SSRCs
  13545. // we generate for recvonly streams in Chrome
  13546. var ssrSel = $(ssrcElem);
  13547. var msid = ssrSel.find('>parameter[name="msid"]');
  13548. if (msid.length) {
  13549. var ssrcVal = ssrSel.attr('ssrc');
  13550. if (ssrcVal) {
  13551. localVideoSSRC = ssrcVal;
  13552. console.info('Stored local video SSRC' +
  13553. ' for future re-use: ' + localVideoSSRC);
  13554. }
  13555. }
  13556. });
  13557. };
  13558. /**
  13559. * Generates new SSRC for local video recvonly stream.
  13560. * FIXME what about eventual SSRC collision ?
  13561. */
  13562. function generateRecvonlySSRC() {
  13563. //
  13564. localRecvOnlySSRC =
  13565. Math.random().toString(10).substring(2, 11);
  13566. localRecvOnlyCName =
  13567. Math.random().toString(36).substring(2);
  13568. console.info(
  13569. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  13570. ", cname: " + localRecvOnlyCName);
  13571. }
  13572. var LocalSSRCReplacement = {
  13573. /**
  13574. * Method must be called before 'session-initiate' or 'session-invite' is
  13575. * sent. Scans the IQ for local video SSRC and stores it if detected.
  13576. *
  13577. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  13578. * which will be scanned for local video SSRC.
  13579. */
  13580. processSessionInit: function (sessionInit) {
  13581. if (!isEnabled)
  13582. return;
  13583. if (localVideoSSRC) {
  13584. console.error("Local SSRC stored already: " + localVideoSSRC);
  13585. return;
  13586. }
  13587. storeLocalVideoSSRC(sessionInit);
  13588. },
  13589. /**
  13590. * If we have local video SSRC stored searched given
  13591. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  13592. * with the stored one.
  13593. * @param localDescription local description object that will have local
  13594. * video SSRC replaced with the stored one
  13595. * @returns modified <tt>localDescription</tt> object.
  13596. */
  13597. mungeLocalVideoSSRC: function (localDescription) {
  13598. if (!isEnabled)
  13599. return localDescription;
  13600. if (!localDescription) {
  13601. console.warn("localDescription is null or undefined");
  13602. return localDescription;
  13603. }
  13604. // IF we have local video SSRC stored make sure it is replaced
  13605. // with old SSRC
  13606. if (localVideoSSRC) {
  13607. var newSdp = new SDP(localDescription.sdp);
  13608. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  13609. !newSdp.containsSSRC(localVideoSSRC)) {
  13610. // Get new video SSRC
  13611. var map = newSdp.getMediaSsrcMap();
  13612. var videoPart = map[1];
  13613. var videoSSRCs = videoPart.ssrcs;
  13614. var newSSRC = Object.keys(videoSSRCs)[0];
  13615. console.info(
  13616. "Replacing new video SSRC: " + newSSRC +
  13617. " with " + localVideoSSRC);
  13618. localDescription.sdp =
  13619. newSdp.raw.replace(
  13620. new RegExp('a=ssrc:' + newSSRC, 'g'),
  13621. 'a=ssrc:' + localVideoSSRC);
  13622. }
  13623. } else {
  13624. // Make sure we have any SSRC for recvonly video stream
  13625. var sdp = new SDP(localDescription.sdp);
  13626. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  13627. sdp.media[1].indexOf('a=recvonly') !== -1) {
  13628. if (!localRecvOnlySSRC) {
  13629. generateRecvonlySSRC();
  13630. }
  13631. console.info('No SSRC in video recvonly stream' +
  13632. ' - adding SSRC: ' + localRecvOnlySSRC);
  13633. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  13634. ' cname:' + localRecvOnlyCName + '\r\n';
  13635. localDescription.sdp = sdp.session + sdp.media.join('');
  13636. }
  13637. }
  13638. return localDescription;
  13639. },
  13640. /**
  13641. * Method must be called before 'source-add' notification is sent. In case
  13642. * we have local video SSRC advertised already it will be removed from the
  13643. * notification. If no other SSRCs are described by given IQ null will be
  13644. * returned which means that there is no point in sending the notification.
  13645. * @param sourceAdd 'source-add' Jingle IQ to be processed
  13646. * @returns modified 'source-add' IQ which can be sent to the focus or
  13647. * <tt>null</tt> if no notification shall be sent. It is no longer
  13648. * a Strophe IQ Builder instance, but DOM element tree.
  13649. */
  13650. processSourceAdd: function (sourceAdd) {
  13651. if (!isEnabled)
  13652. return sourceAdd;
  13653. if (!localVideoSSRC) {
  13654. // Store local SSRC if available
  13655. storeLocalVideoSSRC(sourceAdd);
  13656. return sourceAdd;
  13657. } else {
  13658. return filterOutSource(sourceAdd, 'source-add');
  13659. }
  13660. },
  13661. /**
  13662. * Method must be called before 'source-remove' notification is sent.
  13663. * Removes local video SSRC from the notification. If there are no other
  13664. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  13665. * means that there is no point in sending the notification.
  13666. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  13667. * @returns modified 'source-remove' IQ which can be sent to the focus or
  13668. * <tt>null</tt> if no notification shall be sent. It is no longer
  13669. * a Strophe IQ Builder instance, but DOM element tree.
  13670. */
  13671. processSourceRemove: function (sourceRemove) {
  13672. if (!isEnabled)
  13673. return sourceRemove;
  13674. return filterOutSource(sourceRemove, 'source-remove');
  13675. },
  13676. /**
  13677. * Turns the hack on or off
  13678. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  13679. * to disable it
  13680. */
  13681. setEnabled: function (enabled) {
  13682. isEnabled = enabled;
  13683. }
  13684. };
  13685. module.exports = LocalSSRCReplacement;
  13686. },{"../RTC/RTCBrowserType":10,"./SDP":60}],60:[function(require,module,exports){
  13687. /* jshint -W117 */
  13688. var SDPUtil = require("./SDPUtil");
  13689. // SDP STUFF
  13690. function SDP(sdp) {
  13691. this.media = sdp.split('\r\nm=');
  13692. for (var i = 1; i < this.media.length; i++) {
  13693. this.media[i] = 'm=' + this.media[i];
  13694. if (i != this.media.length - 1) {
  13695. this.media[i] += '\r\n';
  13696. }
  13697. }
  13698. this.session = this.media.shift() + '\r\n';
  13699. this.raw = this.session + this.media.join('');
  13700. }
  13701. /**
  13702. * Returns map of MediaChannel mapped per channel idx.
  13703. */
  13704. SDP.prototype.getMediaSsrcMap = function() {
  13705. var self = this;
  13706. var media_ssrcs = {};
  13707. var tmp;
  13708. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  13709. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  13710. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  13711. var media = {
  13712. mediaindex: mediaindex,
  13713. mid: mid,
  13714. ssrcs: {},
  13715. ssrcGroups: []
  13716. };
  13717. media_ssrcs[mediaindex] = media;
  13718. tmp.forEach(function (line) {
  13719. var linessrc = line.substring(7).split(' ')[0];
  13720. // allocate new ChannelSsrc
  13721. if(!media.ssrcs[linessrc]) {
  13722. media.ssrcs[linessrc] = {
  13723. ssrc: linessrc,
  13724. lines: []
  13725. };
  13726. }
  13727. media.ssrcs[linessrc].lines.push(line);
  13728. });
  13729. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  13730. tmp.forEach(function(line){
  13731. var semantics = line.substr(0, idx).substr(13);
  13732. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13733. if (ssrcs.length != 0) {
  13734. media.ssrcGroups.push({
  13735. semantics: semantics,
  13736. ssrcs: ssrcs
  13737. });
  13738. }
  13739. });
  13740. }
  13741. return media_ssrcs;
  13742. };
  13743. /**
  13744. * Returns <tt>true</tt> if this SDP contains given SSRC.
  13745. * @param ssrc the ssrc to check.
  13746. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  13747. */
  13748. SDP.prototype.containsSSRC = function(ssrc) {
  13749. var medias = this.getMediaSsrcMap();
  13750. var contains = false;
  13751. Object.keys(medias).forEach(function(mediaindex){
  13752. var media = medias[mediaindex];
  13753. //console.log("Check", channel, ssrc);
  13754. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  13755. contains = true;
  13756. }
  13757. });
  13758. return contains;
  13759. };
  13760. // remove iSAC and CN from SDP
  13761. SDP.prototype.mangle = function () {
  13762. var i, j, mline, lines, rtpmap, newdesc;
  13763. for (i = 0; i < this.media.length; i++) {
  13764. lines = this.media[i].split('\r\n');
  13765. lines.pop(); // remove empty last element
  13766. mline = SDPUtil.parse_mline(lines.shift());
  13767. if (mline.media != 'audio')
  13768. continue;
  13769. newdesc = '';
  13770. mline.fmt.length = 0;
  13771. for (j = 0; j < lines.length; j++) {
  13772. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  13773. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  13774. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  13775. continue;
  13776. mline.fmt.push(rtpmap.id);
  13777. newdesc += lines[j] + '\r\n';
  13778. } else {
  13779. newdesc += lines[j] + '\r\n';
  13780. }
  13781. }
  13782. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  13783. this.media[i] += newdesc;
  13784. }
  13785. this.raw = this.session + this.media.join('');
  13786. };
  13787. // remove lines matching prefix from session section
  13788. SDP.prototype.removeSessionLines = function(prefix) {
  13789. var self = this;
  13790. var lines = SDPUtil.find_lines(this.session, prefix);
  13791. lines.forEach(function(line) {
  13792. self.session = self.session.replace(line + '\r\n', '');
  13793. });
  13794. this.raw = this.session + this.media.join('');
  13795. return lines;
  13796. }
  13797. // remove lines matching prefix from a media section specified by mediaindex
  13798. // TODO: non-numeric mediaindex could match mid
  13799. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  13800. var self = this;
  13801. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  13802. lines.forEach(function(line) {
  13803. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  13804. });
  13805. this.raw = this.session + this.media.join('');
  13806. return lines;
  13807. }
  13808. // add content's to a jingle element
  13809. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  13810. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  13811. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  13812. var self = this;
  13813. // new bundle plan
  13814. if (SDPUtil.find_line(this.session, 'a=group:')) {
  13815. lines = SDPUtil.find_lines(this.session, 'a=group:');
  13816. for (i = 0; i < lines.length; i++) {
  13817. tmp = lines[i].split(' ');
  13818. var semantics = tmp.shift().substr(8);
  13819. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  13820. for (j = 0; j < tmp.length; j++) {
  13821. elem.c('content', {name: tmp[j]}).up();
  13822. }
  13823. elem.up();
  13824. }
  13825. }
  13826. for (i = 0; i < this.media.length; i++) {
  13827. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  13828. if (!(mline.media === 'audio' ||
  13829. mline.media === 'video' ||
  13830. mline.media === 'application'))
  13831. {
  13832. continue;
  13833. }
  13834. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  13835. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13836. } else {
  13837. if(ssrcs && ssrcs[mline.media])
  13838. {
  13839. ssrc = ssrcs[mline.media];
  13840. }
  13841. else
  13842. ssrc = false;
  13843. }
  13844. elem.c('content', {creator: thecreator, name: mline.media});
  13845. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13846. // prefer identifier from a=mid if present
  13847. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13848. elem.attrs({ name: mid });
  13849. }
  13850. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13851. {
  13852. elem.c('description',
  13853. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13854. media: mline.media });
  13855. if (ssrc) {
  13856. elem.attrs({ssrc: ssrc});
  13857. }
  13858. for (j = 0; j < mline.fmt.length; j++) {
  13859. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13860. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13861. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13862. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13863. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13864. for (k = 0; k < tmp.length; k++) {
  13865. elem.c('parameter', tmp[k]).up();
  13866. }
  13867. }
  13868. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13869. elem.up();
  13870. }
  13871. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13872. elem.c('encryption', {required: 1});
  13873. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13874. crypto.forEach(function(line) {
  13875. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13876. });
  13877. elem.up(); // end of encryption
  13878. }
  13879. if (ssrc) {
  13880. // new style mapping
  13881. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13882. // FIXME: group by ssrc and support multiple different ssrcs
  13883. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13884. if(ssrclines.length > 0) {
  13885. ssrclines.forEach(function (line) {
  13886. idx = line.indexOf(' ');
  13887. var linessrc = line.substr(0, idx).substr(7);
  13888. if (linessrc != ssrc) {
  13889. elem.up();
  13890. ssrc = linessrc;
  13891. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13892. }
  13893. var kv = line.substr(idx + 1);
  13894. elem.c('parameter');
  13895. if (kv.indexOf(':') == -1) {
  13896. elem.attrs({ name: kv });
  13897. } else {
  13898. var k = kv.split(':', 2)[0];
  13899. elem.attrs({ name: k });
  13900. var v = kv.split(':', 2)[1];
  13901. v = SDPUtil.filter_special_chars(v);
  13902. elem.attrs({ value: v });
  13903. }
  13904. elem.up();
  13905. });
  13906. }
  13907. else
  13908. {
  13909. elem.up();
  13910. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13911. elem.c('parameter');
  13912. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13913. elem.up();
  13914. var msid = null;
  13915. if(mline.media == "audio")
  13916. {
  13917. msid = APP.RTC.localAudio.getId();
  13918. }
  13919. else
  13920. {
  13921. msid = APP.RTC.localVideo.getId();
  13922. }
  13923. if(msid != null)
  13924. {
  13925. msid = SDPUtil.filter_special_chars(msid);
  13926. elem.c('parameter');
  13927. elem.attrs({name: "msid", value:msid});
  13928. elem.up();
  13929. elem.c('parameter');
  13930. elem.attrs({name: "mslabel", value:msid});
  13931. elem.up();
  13932. elem.c('parameter');
  13933. elem.attrs({name: "label", value:msid});
  13934. elem.up();
  13935. }
  13936. }
  13937. elem.up();
  13938. // XEP-0339 handle ssrc-group attributes
  13939. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13940. ssrc_group_lines.forEach(function(line) {
  13941. idx = line.indexOf(' ');
  13942. var semantics = line.substr(0, idx).substr(13);
  13943. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13944. if (ssrcs.length != 0) {
  13945. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13946. ssrcs.forEach(function(ssrc) {
  13947. elem.c('source', { ssrc: ssrc })
  13948. .up();
  13949. });
  13950. elem.up();
  13951. }
  13952. });
  13953. }
  13954. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13955. elem.c('rtcp-mux').up();
  13956. }
  13957. // XEP-0293 -- map a=rtcp-fb:*
  13958. this.RtcpFbToJingle(i, elem, '*');
  13959. // XEP-0294
  13960. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13961. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13962. for (j = 0; j < lines.length; j++) {
  13963. tmp = SDPUtil.parse_extmap(lines[j]);
  13964. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13965. uri: tmp.uri,
  13966. id: tmp.value });
  13967. if (tmp.hasOwnProperty('direction')) {
  13968. switch (tmp.direction) {
  13969. case 'sendonly':
  13970. elem.attrs({senders: 'responder'});
  13971. break;
  13972. case 'recvonly':
  13973. elem.attrs({senders: 'initiator'});
  13974. break;
  13975. case 'sendrecv':
  13976. elem.attrs({senders: 'both'});
  13977. break;
  13978. case 'inactive':
  13979. elem.attrs({senders: 'none'});
  13980. break;
  13981. }
  13982. }
  13983. // TODO: handle params
  13984. elem.up();
  13985. }
  13986. }
  13987. elem.up(); // end of description
  13988. }
  13989. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13990. this.TransportToJingle(i, elem);
  13991. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13992. elem.attrs({senders: 'both'});
  13993. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13994. elem.attrs({senders: 'initiator'});
  13995. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13996. elem.attrs({senders: 'responder'});
  13997. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13998. elem.attrs({senders: 'none'});
  13999. }
  14000. if (mline.port == '0') {
  14001. // estos hack to reject an m-line
  14002. elem.attrs({senders: 'rejected'});
  14003. }
  14004. elem.up(); // end of content
  14005. }
  14006. elem.up();
  14007. return elem;
  14008. };
  14009. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  14010. var i = mediaindex;
  14011. var tmp;
  14012. var self = this;
  14013. elem.c('transport');
  14014. // XEP-0343 DTLS/SCTP
  14015. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  14016. {
  14017. var sctpmap = SDPUtil.find_line(
  14018. this.media[i], 'a=sctpmap:', self.session);
  14019. if (sctpmap)
  14020. {
  14021. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  14022. elem.c('sctpmap',
  14023. {
  14024. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  14025. number: sctpAttrs[0], /* SCTP port */
  14026. protocol: sctpAttrs[1], /* protocol */
  14027. });
  14028. // Optional stream count attribute
  14029. if (sctpAttrs.length > 2)
  14030. elem.attrs({ streams: sctpAttrs[2]});
  14031. elem.up();
  14032. }
  14033. }
  14034. // XEP-0320
  14035. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  14036. fingerprints.forEach(function(line) {
  14037. tmp = SDPUtil.parse_fingerprint(line);
  14038. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  14039. elem.c('fingerprint').t(tmp.fingerprint);
  14040. delete tmp.fingerprint;
  14041. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  14042. if (line) {
  14043. tmp.setup = line.substr(8);
  14044. }
  14045. elem.attrs(tmp);
  14046. elem.up(); // end of fingerprint
  14047. });
  14048. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  14049. if (tmp) {
  14050. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  14051. elem.attrs(tmp);
  14052. // XEP-0176
  14053. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  14054. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  14055. lines.forEach(function (line) {
  14056. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  14057. });
  14058. }
  14059. }
  14060. elem.up(); // end of transport
  14061. }
  14062. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  14063. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  14064. lines.forEach(function (line) {
  14065. var tmp = SDPUtil.parse_rtcpfb(line);
  14066. if (tmp.type == 'trr-int') {
  14067. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  14068. elem.up();
  14069. } else {
  14070. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  14071. if (tmp.params.length > 0) {
  14072. elem.attrs({'subtype': tmp.params[0]});
  14073. }
  14074. elem.up();
  14075. }
  14076. });
  14077. };
  14078. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  14079. var media = '';
  14080. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  14081. if (tmp.length) {
  14082. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  14083. if (tmp.attr('value')) {
  14084. media += tmp.attr('value');
  14085. } else {
  14086. media += '0';
  14087. }
  14088. media += '\r\n';
  14089. }
  14090. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  14091. tmp.each(function () {
  14092. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  14093. if ($(this).attr('subtype')) {
  14094. media += ' ' + $(this).attr('subtype');
  14095. }
  14096. media += '\r\n';
  14097. });
  14098. return media;
  14099. };
  14100. // construct an SDP from a jingle stanza
  14101. SDP.prototype.fromJingle = function (jingle) {
  14102. var self = this;
  14103. this.raw = 'v=0\r\n' +
  14104. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  14105. 's=-\r\n' +
  14106. 't=0 0\r\n';
  14107. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  14108. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  14109. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  14110. var contents = $(group).find('>content').map(function (idx, content) {
  14111. return content.getAttribute('name');
  14112. }).get();
  14113. if (contents.length > 0) {
  14114. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  14115. }
  14116. });
  14117. }
  14118. this.session = this.raw;
  14119. jingle.find('>content').each(function () {
  14120. var m = self.jingle2media($(this));
  14121. self.media.push(m);
  14122. });
  14123. // reconstruct msid-semantic -- apparently not necessary
  14124. /*
  14125. var msid = SDPUtil.parse_ssrc(this.raw);
  14126. if (msid.hasOwnProperty('mslabel')) {
  14127. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  14128. }
  14129. */
  14130. this.raw = this.session + this.media.join('');
  14131. };
  14132. // translate a jingle content element into an an SDP media part
  14133. SDP.prototype.jingle2media = function (content) {
  14134. var media = '',
  14135. desc = content.find('description'),
  14136. ssrc = desc.attr('ssrc'),
  14137. self = this,
  14138. tmp;
  14139. var sctp = content.find(
  14140. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  14141. tmp = { media: desc.attr('media') };
  14142. tmp.port = '1';
  14143. if (content.attr('senders') == 'rejected') {
  14144. // estos hack to reject an m-line.
  14145. tmp.port = '0';
  14146. }
  14147. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  14148. if (sctp.length)
  14149. tmp.proto = 'DTLS/SCTP';
  14150. else
  14151. tmp.proto = 'RTP/SAVPF';
  14152. } else {
  14153. tmp.proto = 'RTP/AVPF';
  14154. }
  14155. if (!sctp.length)
  14156. {
  14157. tmp.fmt = desc.find('payload-type').map(
  14158. function () { return this.getAttribute('id'); }).get();
  14159. media += SDPUtil.build_mline(tmp) + '\r\n';
  14160. }
  14161. else
  14162. {
  14163. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  14164. media += 'a=sctpmap:' + sctp.attr('number') +
  14165. ' ' + sctp.attr('protocol');
  14166. var streamCount = sctp.attr('streams');
  14167. if (streamCount)
  14168. media += ' ' + streamCount + '\r\n';
  14169. else
  14170. media += '\r\n';
  14171. }
  14172. media += 'c=IN IP4 0.0.0.0\r\n';
  14173. if (!sctp.length)
  14174. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  14175. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  14176. if (tmp.length) {
  14177. if (tmp.attr('ufrag')) {
  14178. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  14179. }
  14180. if (tmp.attr('pwd')) {
  14181. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  14182. }
  14183. tmp.find('>fingerprint').each(function () {
  14184. // FIXME: check namespace at some point
  14185. media += 'a=fingerprint:' + this.getAttribute('hash');
  14186. media += ' ' + $(this).text();
  14187. media += '\r\n';
  14188. if (this.getAttribute('setup')) {
  14189. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  14190. }
  14191. });
  14192. }
  14193. switch (content.attr('senders')) {
  14194. case 'initiator':
  14195. media += 'a=sendonly\r\n';
  14196. break;
  14197. case 'responder':
  14198. media += 'a=recvonly\r\n';
  14199. break;
  14200. case 'none':
  14201. media += 'a=inactive\r\n';
  14202. break;
  14203. case 'both':
  14204. media += 'a=sendrecv\r\n';
  14205. break;
  14206. }
  14207. media += 'a=mid:' + content.attr('name') + '\r\n';
  14208. // <description><rtcp-mux/></description>
  14209. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  14210. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  14211. if (desc.find('rtcp-mux').length) {
  14212. media += 'a=rtcp-mux\r\n';
  14213. }
  14214. if (desc.find('encryption').length) {
  14215. desc.find('encryption>crypto').each(function () {
  14216. media += 'a=crypto:' + this.getAttribute('tag');
  14217. media += ' ' + this.getAttribute('crypto-suite');
  14218. media += ' ' + this.getAttribute('key-params');
  14219. if (this.getAttribute('session-params')) {
  14220. media += ' ' + this.getAttribute('session-params');
  14221. }
  14222. media += '\r\n';
  14223. });
  14224. }
  14225. desc.find('payload-type').each(function () {
  14226. media += SDPUtil.build_rtpmap(this) + '\r\n';
  14227. if ($(this).find('>parameter').length) {
  14228. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  14229. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  14230. media += '\r\n';
  14231. }
  14232. // xep-0293
  14233. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  14234. });
  14235. // xep-0293
  14236. media += self.RtcpFbFromJingle(desc, '*');
  14237. // xep-0294
  14238. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  14239. tmp.each(function () {
  14240. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  14241. });
  14242. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  14243. media += SDPUtil.candidateFromJingle(this);
  14244. });
  14245. // XEP-0339 handle ssrc-group attributes
  14246. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  14247. var semantics = this.getAttribute('semantics');
  14248. var ssrcs = $(this).find('>source').map(function() {
  14249. return this.getAttribute('ssrc');
  14250. }).get();
  14251. if (ssrcs.length != 0) {
  14252. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  14253. }
  14254. });
  14255. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  14256. tmp.each(function () {
  14257. var ssrc = this.getAttribute('ssrc');
  14258. $(this).find('>parameter').each(function () {
  14259. var name = this.getAttribute('name');
  14260. var value = this.getAttribute('value');
  14261. value = SDPUtil.filter_special_chars(value);
  14262. media += 'a=ssrc:' + ssrc + ' ' + name;
  14263. if (value && value.length)
  14264. media += ':' + value;
  14265. media += '\r\n';
  14266. });
  14267. });
  14268. return media;
  14269. };
  14270. module.exports = SDP;
  14271. },{"./SDPUtil":62}],61:[function(require,module,exports){
  14272. var SDPUtil = require("./SDPUtil");
  14273. function SDPDiffer(mySDP, otherSDP) {
  14274. this.mySDP = mySDP;
  14275. this.otherSDP = otherSDP;
  14276. }
  14277. /**
  14278. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  14279. * @param otherSdp the other SDP to check ssrc with.
  14280. */
  14281. SDPDiffer.prototype.getNewMedia = function() {
  14282. // this could be useful in Array.prototype.
  14283. function arrayEquals(array) {
  14284. // if the other array is a falsy value, return
  14285. if (!array)
  14286. return false;
  14287. // compare lengths - can save a lot of time
  14288. if (this.length != array.length)
  14289. return false;
  14290. for (var i = 0, l=this.length; i < l; i++) {
  14291. // Check if we have nested arrays
  14292. if (this[i] instanceof Array && array[i] instanceof Array) {
  14293. // recurse into the nested arrays
  14294. if (!this[i].equals(array[i]))
  14295. return false;
  14296. }
  14297. else if (this[i] != array[i]) {
  14298. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  14299. return false;
  14300. }
  14301. }
  14302. return true;
  14303. }
  14304. var myMedias = this.mySDP.getMediaSsrcMap();
  14305. var othersMedias = this.otherSDP.getMediaSsrcMap();
  14306. var newMedia = {};
  14307. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  14308. var myMedia = myMedias[othersMediaIdx];
  14309. var othersMedia = othersMedias[othersMediaIdx];
  14310. if(!myMedia && othersMedia) {
  14311. // Add whole channel
  14312. newMedia[othersMediaIdx] = othersMedia;
  14313. return;
  14314. }
  14315. // Look for new ssrcs accross the channel
  14316. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  14317. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  14318. // Allocate channel if we've found ssrc that doesn't exist in our channel
  14319. if(!newMedia[othersMediaIdx]){
  14320. newMedia[othersMediaIdx] = {
  14321. mediaindex: othersMedia.mediaindex,
  14322. mid: othersMedia.mid,
  14323. ssrcs: {},
  14324. ssrcGroups: []
  14325. };
  14326. }
  14327. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  14328. }
  14329. });
  14330. // Look for new ssrc groups across the channels
  14331. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  14332. // try to match the other ssrc-group with an ssrc-group of ours
  14333. var matched = false;
  14334. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  14335. var mySsrcGroup = myMedia.ssrcGroups[i];
  14336. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  14337. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  14338. matched = true;
  14339. break;
  14340. }
  14341. }
  14342. if (!matched) {
  14343. // Allocate channel if we've found an ssrc-group that doesn't
  14344. // exist in our channel
  14345. if(!newMedia[othersMediaIdx]){
  14346. newMedia[othersMediaIdx] = {
  14347. mediaindex: othersMedia.mediaindex,
  14348. mid: othersMedia.mid,
  14349. ssrcs: {},
  14350. ssrcGroups: []
  14351. };
  14352. }
  14353. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  14354. }
  14355. });
  14356. });
  14357. return newMedia;
  14358. };
  14359. /**
  14360. * Sends SSRC update IQ.
  14361. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  14362. * @param sid session identifier that will be put into the IQ.
  14363. * @param initiator initiator identifier.
  14364. * @param toJid destination Jid
  14365. * @param isAdd indicates if this is remove or add operation.
  14366. */
  14367. SDPDiffer.prototype.toJingle = function(modify) {
  14368. var sdpMediaSsrcs = this.getNewMedia();
  14369. var self = this;
  14370. // FIXME: only announce video ssrcs since we mix audio and dont need
  14371. // the audio ssrcs therefore
  14372. var modified = false;
  14373. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  14374. modified = true;
  14375. var media = sdpMediaSsrcs[mediaindex];
  14376. modify.c('content', {name: media.mid});
  14377. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  14378. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  14379. // generate sources from lines
  14380. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  14381. var mediaSsrc = media.ssrcs[ssrcNum];
  14382. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  14383. modify.attrs({ssrc: mediaSsrc.ssrc});
  14384. // iterate over ssrc lines
  14385. mediaSsrc.lines.forEach(function (line) {
  14386. var idx = line.indexOf(' ');
  14387. var kv = line.substr(idx + 1);
  14388. modify.c('parameter');
  14389. if (kv.indexOf(':') == -1) {
  14390. modify.attrs({ name: kv });
  14391. } else {
  14392. var nv = kv.split(':', 2);
  14393. var name = nv[0];
  14394. var value = SDPUtil.filter_special_chars(nv[1]);
  14395. modify.attrs({ name: name });
  14396. modify.attrs({ value: value });
  14397. }
  14398. modify.up(); // end of parameter
  14399. });
  14400. modify.up(); // end of source
  14401. });
  14402. // generate source groups from lines
  14403. media.ssrcGroups.forEach(function(ssrcGroup) {
  14404. if (ssrcGroup.ssrcs.length != 0) {
  14405. modify.c('ssrc-group', {
  14406. semantics: ssrcGroup.semantics,
  14407. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  14408. });
  14409. ssrcGroup.ssrcs.forEach(function (ssrc) {
  14410. modify.c('source', { ssrc: ssrc })
  14411. .up(); // end of source
  14412. });
  14413. modify.up(); // end of ssrc-group
  14414. }
  14415. });
  14416. modify.up(); // end of description
  14417. modify.up(); // end of content
  14418. });
  14419. return modified;
  14420. };
  14421. module.exports = SDPDiffer;
  14422. },{"./SDPUtil":62}],62:[function(require,module,exports){
  14423. SDPUtil = {
  14424. filter_special_chars: function (text) {
  14425. return text.replace(/[\\\/\{,\}\+]/g, "");
  14426. },
  14427. iceparams: function (mediadesc, sessiondesc) {
  14428. var data = null;
  14429. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  14430. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  14431. data = {
  14432. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  14433. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  14434. };
  14435. }
  14436. return data;
  14437. },
  14438. parse_iceufrag: function (line) {
  14439. return line.substring(12);
  14440. },
  14441. build_iceufrag: function (frag) {
  14442. return 'a=ice-ufrag:' + frag;
  14443. },
  14444. parse_icepwd: function (line) {
  14445. return line.substring(10);
  14446. },
  14447. build_icepwd: function (pwd) {
  14448. return 'a=ice-pwd:' + pwd;
  14449. },
  14450. parse_mid: function (line) {
  14451. return line.substring(6);
  14452. },
  14453. parse_mline: function (line) {
  14454. var parts = line.substring(2).split(' '),
  14455. data = {};
  14456. data.media = parts.shift();
  14457. data.port = parts.shift();
  14458. data.proto = parts.shift();
  14459. if (parts[parts.length - 1] === '') { // trailing whitespace
  14460. parts.pop();
  14461. }
  14462. data.fmt = parts;
  14463. return data;
  14464. },
  14465. build_mline: function (mline) {
  14466. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  14467. },
  14468. parse_rtpmap: function (line) {
  14469. var parts = line.substring(9).split(' '),
  14470. data = {};
  14471. data.id = parts.shift();
  14472. parts = parts[0].split('/');
  14473. data.name = parts.shift();
  14474. data.clockrate = parts.shift();
  14475. data.channels = parts.length ? parts.shift() : '1';
  14476. return data;
  14477. },
  14478. /**
  14479. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  14480. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  14481. * @returns [SCTP port number, protocol, streams]
  14482. */
  14483. parse_sctpmap: function (line)
  14484. {
  14485. var parts = line.substring(10).split(' ');
  14486. var sctpPort = parts[0];
  14487. var protocol = parts[1];
  14488. // Stream count is optional
  14489. var streamCount = parts.length > 2 ? parts[2] : null;
  14490. return [sctpPort, protocol, streamCount];// SCTP port
  14491. },
  14492. build_rtpmap: function (el) {
  14493. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  14494. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  14495. line += '/' + el.getAttribute('channels');
  14496. }
  14497. return line;
  14498. },
  14499. parse_crypto: function (line) {
  14500. var parts = line.substring(9).split(' '),
  14501. data = {};
  14502. data.tag = parts.shift();
  14503. data['crypto-suite'] = parts.shift();
  14504. data['key-params'] = parts.shift();
  14505. if (parts.length) {
  14506. data['session-params'] = parts.join(' ');
  14507. }
  14508. return data;
  14509. },
  14510. parse_fingerprint: function (line) { // RFC 4572
  14511. var parts = line.substring(14).split(' '),
  14512. data = {};
  14513. data.hash = parts.shift();
  14514. data.fingerprint = parts.shift();
  14515. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  14516. return data;
  14517. },
  14518. parse_fmtp: function (line) {
  14519. var parts = line.split(' '),
  14520. i, key, value,
  14521. data = [];
  14522. parts.shift();
  14523. parts = parts.join(' ').split(';');
  14524. for (i = 0; i < parts.length; i++) {
  14525. key = parts[i].split('=')[0];
  14526. while (key.length && key[0] == ' ') {
  14527. key = key.substring(1);
  14528. }
  14529. value = parts[i].split('=')[1];
  14530. if (key && value) {
  14531. data.push({name: key, value: value});
  14532. } else if (key) {
  14533. // rfc 4733 (DTMF) style stuff
  14534. data.push({name: '', value: key});
  14535. }
  14536. }
  14537. return data;
  14538. },
  14539. parse_icecandidate: function (line) {
  14540. var candidate = {},
  14541. elems = line.split(' ');
  14542. candidate.foundation = elems[0].substring(12);
  14543. candidate.component = elems[1];
  14544. candidate.protocol = elems[2].toLowerCase();
  14545. candidate.priority = elems[3];
  14546. candidate.ip = elems[4];
  14547. candidate.port = elems[5];
  14548. // elems[6] => "typ"
  14549. candidate.type = elems[7];
  14550. candidate.generation = 0; // default value, may be overwritten below
  14551. for (var i = 8; i < elems.length; i += 2) {
  14552. switch (elems[i]) {
  14553. case 'raddr':
  14554. candidate['rel-addr'] = elems[i + 1];
  14555. break;
  14556. case 'rport':
  14557. candidate['rel-port'] = elems[i + 1];
  14558. break;
  14559. case 'generation':
  14560. candidate.generation = elems[i + 1];
  14561. break;
  14562. case 'tcptype':
  14563. candidate.tcptype = elems[i + 1];
  14564. break;
  14565. default: // TODO
  14566. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14567. }
  14568. }
  14569. candidate.network = '1';
  14570. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14571. return candidate;
  14572. },
  14573. build_icecandidate: function (cand) {
  14574. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  14575. line += ' ';
  14576. switch (cand.type) {
  14577. case 'srflx':
  14578. case 'prflx':
  14579. case 'relay':
  14580. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  14581. line += 'raddr';
  14582. line += ' ';
  14583. line += cand['rel-addr'];
  14584. line += ' ';
  14585. line += 'rport';
  14586. line += ' ';
  14587. line += cand['rel-port'];
  14588. line += ' ';
  14589. }
  14590. break;
  14591. }
  14592. if (cand.hasOwnAttribute('tcptype')) {
  14593. line += 'tcptype';
  14594. line += ' ';
  14595. line += cand.tcptype;
  14596. line += ' ';
  14597. }
  14598. line += 'generation';
  14599. line += ' ';
  14600. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  14601. return line;
  14602. },
  14603. parse_ssrc: function (desc) {
  14604. // proprietary mapping of a=ssrc lines
  14605. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  14606. // and parse according to that
  14607. var lines = desc.split('\r\n'),
  14608. data = {};
  14609. for (var i = 0; i < lines.length; i++) {
  14610. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  14611. var idx = lines[i].indexOf(' ');
  14612. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  14613. }
  14614. }
  14615. return data;
  14616. },
  14617. parse_rtcpfb: function (line) {
  14618. var parts = line.substr(10).split(' ');
  14619. var data = {};
  14620. data.pt = parts.shift();
  14621. data.type = parts.shift();
  14622. data.params = parts;
  14623. return data;
  14624. },
  14625. parse_extmap: function (line) {
  14626. var parts = line.substr(9).split(' ');
  14627. var data = {};
  14628. data.value = parts.shift();
  14629. if (data.value.indexOf('/') != -1) {
  14630. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  14631. data.value = data.value.substr(0, data.value.indexOf('/'));
  14632. } else {
  14633. data.direction = 'both';
  14634. }
  14635. data.uri = parts.shift();
  14636. data.params = parts;
  14637. return data;
  14638. },
  14639. find_line: function (haystack, needle, sessionpart) {
  14640. var lines = haystack.split('\r\n');
  14641. for (var i = 0; i < lines.length; i++) {
  14642. if (lines[i].substring(0, needle.length) == needle) {
  14643. return lines[i];
  14644. }
  14645. }
  14646. if (!sessionpart) {
  14647. return false;
  14648. }
  14649. // search session part
  14650. lines = sessionpart.split('\r\n');
  14651. for (var j = 0; j < lines.length; j++) {
  14652. if (lines[j].substring(0, needle.length) == needle) {
  14653. return lines[j];
  14654. }
  14655. }
  14656. return false;
  14657. },
  14658. find_lines: function (haystack, needle, sessionpart) {
  14659. var lines = haystack.split('\r\n'),
  14660. needles = [];
  14661. for (var i = 0; i < lines.length; i++) {
  14662. if (lines[i].substring(0, needle.length) == needle)
  14663. needles.push(lines[i]);
  14664. }
  14665. if (needles.length || !sessionpart) {
  14666. return needles;
  14667. }
  14668. // search session part
  14669. lines = sessionpart.split('\r\n');
  14670. for (var j = 0; j < lines.length; j++) {
  14671. if (lines[j].substring(0, needle.length) == needle) {
  14672. needles.push(lines[j]);
  14673. }
  14674. }
  14675. return needles;
  14676. },
  14677. candidateToJingle: function (line) {
  14678. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  14679. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  14680. if (line.indexOf('candidate:') === 0) {
  14681. line = 'a=' + line;
  14682. } else if (line.substring(0, 12) != 'a=candidate:') {
  14683. console.log('parseCandidate called with a line that is not a candidate line');
  14684. console.log(line);
  14685. return null;
  14686. }
  14687. if (line.substring(line.length - 2) == '\r\n') // chomp it
  14688. line = line.substring(0, line.length - 2);
  14689. var candidate = {},
  14690. elems = line.split(' '),
  14691. i;
  14692. if (elems[6] != 'typ') {
  14693. console.log('did not find typ in the right place');
  14694. console.log(line);
  14695. return null;
  14696. }
  14697. candidate.foundation = elems[0].substring(12);
  14698. candidate.component = elems[1];
  14699. candidate.protocol = elems[2].toLowerCase();
  14700. candidate.priority = elems[3];
  14701. candidate.ip = elems[4];
  14702. candidate.port = elems[5];
  14703. // elems[6] => "typ"
  14704. candidate.type = elems[7];
  14705. candidate.generation = '0'; // default, may be overwritten below
  14706. for (i = 8; i < elems.length; i += 2) {
  14707. switch (elems[i]) {
  14708. case 'raddr':
  14709. candidate['rel-addr'] = elems[i + 1];
  14710. break;
  14711. case 'rport':
  14712. candidate['rel-port'] = elems[i + 1];
  14713. break;
  14714. case 'generation':
  14715. candidate.generation = elems[i + 1];
  14716. break;
  14717. case 'tcptype':
  14718. candidate.tcptype = elems[i + 1];
  14719. break;
  14720. default: // TODO
  14721. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14722. }
  14723. }
  14724. candidate.network = '1';
  14725. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14726. return candidate;
  14727. },
  14728. candidateFromJingle: function (cand) {
  14729. var line = 'a=candidate:';
  14730. line += cand.getAttribute('foundation');
  14731. line += ' ';
  14732. line += cand.getAttribute('component');
  14733. line += ' ';
  14734. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  14735. line += ' ';
  14736. line += cand.getAttribute('priority');
  14737. line += ' ';
  14738. line += cand.getAttribute('ip');
  14739. line += ' ';
  14740. line += cand.getAttribute('port');
  14741. line += ' ';
  14742. line += 'typ';
  14743. line += ' ' + cand.getAttribute('type');
  14744. line += ' ';
  14745. switch (cand.getAttribute('type')) {
  14746. case 'srflx':
  14747. case 'prflx':
  14748. case 'relay':
  14749. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  14750. line += 'raddr';
  14751. line += ' ';
  14752. line += cand.getAttribute('rel-addr');
  14753. line += ' ';
  14754. line += 'rport';
  14755. line += ' ';
  14756. line += cand.getAttribute('rel-port');
  14757. line += ' ';
  14758. }
  14759. break;
  14760. }
  14761. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  14762. line += 'tcptype';
  14763. line += ' ';
  14764. line += cand.getAttribute('tcptype');
  14765. line += ' ';
  14766. }
  14767. line += 'generation';
  14768. line += ' ';
  14769. line += cand.getAttribute('generation') || '0';
  14770. return line + '\r\n';
  14771. }
  14772. };
  14773. module.exports = SDPUtil;
  14774. },{}],63:[function(require,module,exports){
  14775. var RTC = require('../RTC/RTC');
  14776. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  14777. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14778. var SSRCReplacement = require("./LocalSSRCReplacement");
  14779. function TraceablePeerConnection(ice_config, constraints, session) {
  14780. var self = this;
  14781. var RTCPeerConnectionType = null;
  14782. if (RTCBrowserType.isFirefox()) {
  14783. RTCPeerConnectionType = mozRTCPeerConnection;
  14784. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  14785. RTCPeerConnectionType = RTCPeerConnection;
  14786. } else {
  14787. RTCPeerConnectionType = webkitRTCPeerConnection;
  14788. }
  14789. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  14790. this.updateLog = [];
  14791. this.stats = {};
  14792. this.statsinterval = null;
  14793. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  14794. var Interop = require('sdp-interop').Interop;
  14795. this.interop = new Interop();
  14796. var Simulcast = require('sdp-simulcast');
  14797. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  14798. // override as desired
  14799. this.trace = function (what, info) {
  14800. /*console.warn('WTRACE', what, info);
  14801. if (info && RTCBrowserType.isIExplorer()) {
  14802. if (info.length > 1024) {
  14803. console.warn('WTRACE', what, info.substr(1024));
  14804. }
  14805. if (info.length > 2048) {
  14806. console.warn('WTRACE', what, info.substr(2048));
  14807. }
  14808. }*/
  14809. self.updateLog.push({
  14810. time: new Date(),
  14811. type: what,
  14812. value: info || ""
  14813. });
  14814. };
  14815. this.onicecandidate = null;
  14816. this.peerconnection.onicecandidate = function (event) {
  14817. // FIXME: this causes stack overflow with Temasys Plugin
  14818. if (!RTCBrowserType.isTemasysPluginUsed())
  14819. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  14820. if (self.onicecandidate !== null) {
  14821. self.onicecandidate(event);
  14822. }
  14823. };
  14824. this.onaddstream = null;
  14825. this.peerconnection.onaddstream = function (event) {
  14826. self.trace('onaddstream', event.stream.id);
  14827. if (self.onaddstream !== null) {
  14828. self.onaddstream(event);
  14829. }
  14830. };
  14831. this.onremovestream = null;
  14832. this.peerconnection.onremovestream = function (event) {
  14833. self.trace('onremovestream', event.stream.id);
  14834. if (self.onremovestream !== null) {
  14835. self.onremovestream(event);
  14836. }
  14837. };
  14838. this.onsignalingstatechange = null;
  14839. this.peerconnection.onsignalingstatechange = function (event) {
  14840. self.trace('onsignalingstatechange', self.signalingState);
  14841. if (self.onsignalingstatechange !== null) {
  14842. self.onsignalingstatechange(event);
  14843. }
  14844. };
  14845. this.oniceconnectionstatechange = null;
  14846. this.peerconnection.oniceconnectionstatechange = function (event) {
  14847. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14848. if (self.oniceconnectionstatechange !== null) {
  14849. self.oniceconnectionstatechange(event);
  14850. }
  14851. };
  14852. this.onnegotiationneeded = null;
  14853. this.peerconnection.onnegotiationneeded = function (event) {
  14854. self.trace('onnegotiationneeded');
  14855. if (self.onnegotiationneeded !== null) {
  14856. self.onnegotiationneeded(event);
  14857. }
  14858. };
  14859. self.ondatachannel = null;
  14860. this.peerconnection.ondatachannel = function (event) {
  14861. self.trace('ondatachannel', event);
  14862. if (self.ondatachannel !== null) {
  14863. self.ondatachannel(event);
  14864. }
  14865. };
  14866. // XXX: do all non-firefox browsers which we support also support this?
  14867. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  14868. this.statsinterval = window.setInterval(function() {
  14869. self.peerconnection.getStats(function(stats) {
  14870. var results = stats.result();
  14871. var now = new Date();
  14872. for (var i = 0; i < results.length; ++i) {
  14873. results[i].names().forEach(function (name) {
  14874. var id = results[i].id + '-' + name;
  14875. if (!self.stats[id]) {
  14876. self.stats[id] = {
  14877. startTime: now,
  14878. endTime: now,
  14879. values: [],
  14880. times: []
  14881. };
  14882. }
  14883. self.stats[id].values.push(results[i].stat(name));
  14884. self.stats[id].times.push(now.getTime());
  14885. if (self.stats[id].values.length > self.maxstats) {
  14886. self.stats[id].values.shift();
  14887. self.stats[id].times.shift();
  14888. }
  14889. self.stats[id].endTime = now;
  14890. });
  14891. }
  14892. });
  14893. }, 1000);
  14894. }
  14895. }
  14896. /**
  14897. * Returns a string representation of a SessionDescription object.
  14898. */
  14899. var dumpSDP = function(description) {
  14900. if (typeof description === 'undefined' || description == null) {
  14901. return '';
  14902. }
  14903. return 'type: ' + description.type + '\r\n' + description.sdp;
  14904. };
  14905. /**
  14906. * Takes a SessionDescription object and returns a "normalized" version.
  14907. * Currently it only takes care of ordering the a=ssrc lines.
  14908. */
  14909. var normalizePlanB = function(desc) {
  14910. if (typeof desc !== 'object' || desc === null ||
  14911. typeof desc.sdp !== 'string') {
  14912. console.warn('An empty description was passed as an argument.');
  14913. return desc;
  14914. }
  14915. var transform = require('sdp-transform');
  14916. var session = transform.parse(desc.sdp);
  14917. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  14918. Array.isArray(session.media)) {
  14919. session.media.forEach(function (mLine) {
  14920. // Chrome appears to be picky about the order in which a=ssrc lines
  14921. // are listed in an m-line when rtx is enabled (and thus there are
  14922. // a=ssrc-group lines with FID semantics). Specifically if we have
  14923. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  14924. // the "a=ssrc:S1" lines, SRD fails.
  14925. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  14926. // first.
  14927. var firstSsrcs = [];
  14928. var newSsrcLines = [];
  14929. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  14930. mLine.ssrcGroups.forEach(function (group) {
  14931. if (typeof group.semantics !== 'undefined' &&
  14932. group.semantics === 'FID') {
  14933. if (typeof group.ssrcs !== 'undefined') {
  14934. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14935. }
  14936. }
  14937. });
  14938. }
  14939. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14940. for (var i = 0; i<mLine.ssrcs.length; i++){
  14941. if (typeof mLine.ssrcs[i] === 'object'
  14942. && typeof mLine.ssrcs[i].id !== 'undefined'
  14943. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14944. newSsrcLines.push(mLine.ssrcs[i]);
  14945. delete mLine.ssrcs[i];
  14946. }
  14947. }
  14948. for (var i = 0; i<mLine.ssrcs.length; i++){
  14949. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14950. newSsrcLines.push(mLine.ssrcs[i]);
  14951. }
  14952. }
  14953. mLine.ssrcs = newSsrcLines;
  14954. }
  14955. });
  14956. }
  14957. var resStr = transform.write(session);
  14958. return new RTCSessionDescription({
  14959. type: desc.type,
  14960. sdp: resStr
  14961. });
  14962. };
  14963. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14964. TraceablePeerConnection.prototype.__defineGetter__(
  14965. 'signalingState',
  14966. function() { return this.peerconnection.signalingState; });
  14967. TraceablePeerConnection.prototype.__defineGetter__(
  14968. 'iceConnectionState',
  14969. function() { return this.peerconnection.iceConnectionState; });
  14970. TraceablePeerConnection.prototype.__defineGetter__(
  14971. 'localDescription',
  14972. function() {
  14973. var desc = this.peerconnection.localDescription;
  14974. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  14975. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14976. // if we're running on FF, transform to Plan B first.
  14977. if (RTCBrowserType.usesUnifiedPlan()) {
  14978. desc = this.interop.toPlanB(desc);
  14979. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14980. }
  14981. return desc;
  14982. });
  14983. TraceablePeerConnection.prototype.__defineGetter__(
  14984. 'remoteDescription',
  14985. function() {
  14986. var desc = this.peerconnection.remoteDescription;
  14987. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14988. // if we're running on FF, transform to Plan B first.
  14989. if (RTCBrowserType.usesUnifiedPlan()) {
  14990. desc = this.interop.toPlanB(desc);
  14991. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14992. }
  14993. return desc;
  14994. });
  14995. }
  14996. TraceablePeerConnection.prototype.addStream = function (stream) {
  14997. this.trace('addStream', stream.id);
  14998. try
  14999. {
  15000. this.peerconnection.addStream(stream);
  15001. }
  15002. catch (e)
  15003. {
  15004. console.error(e);
  15005. }
  15006. };
  15007. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  15008. this.trace('removeStream', stream.id);
  15009. if(stopStreams) {
  15010. stream.getAudioTracks().forEach(function (track) {
  15011. // stop() not supported with IE
  15012. if (track.stop) {
  15013. track.stop();
  15014. }
  15015. });
  15016. stream.getVideoTracks().forEach(function (track) {
  15017. // stop() not supported with IE
  15018. if (track.stop) {
  15019. track.stop();
  15020. }
  15021. });
  15022. if (stream.stop) {
  15023. stream.stop();
  15024. }
  15025. }
  15026. try {
  15027. // FF doesn't support this yet.
  15028. if (this.peerconnection.removeStream)
  15029. this.peerconnection.removeStream(stream);
  15030. } catch (e) {
  15031. console.error(e);
  15032. }
  15033. };
  15034. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  15035. this.trace('createDataChannel', label, opts);
  15036. return this.peerconnection.createDataChannel(label, opts);
  15037. };
  15038. TraceablePeerConnection.prototype.setLocalDescription
  15039. = function (description, successCallback, failureCallback) {
  15040. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  15041. // if we're running on FF, transform to Plan A first.
  15042. if (RTCBrowserType.usesUnifiedPlan()) {
  15043. description = this.interop.toUnifiedPlan(description);
  15044. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  15045. }
  15046. var self = this;
  15047. this.peerconnection.setLocalDescription(description,
  15048. function () {
  15049. self.trace('setLocalDescriptionOnSuccess');
  15050. successCallback();
  15051. },
  15052. function (err) {
  15053. self.trace('setLocalDescriptionOnFailure', err);
  15054. failureCallback(err);
  15055. }
  15056. );
  15057. /*
  15058. if (this.statsinterval === null && this.maxstats > 0) {
  15059. // start gathering stats
  15060. }
  15061. */
  15062. };
  15063. TraceablePeerConnection.prototype.setRemoteDescription
  15064. = function (description, successCallback, failureCallback) {
  15065. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  15066. // TODO the focus should squeze or explode the remote simulcast
  15067. description = this.simulcast.mungeRemoteDescription(description);
  15068. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  15069. // if we're running on FF, transform to Plan A first.
  15070. if (RTCBrowserType.usesUnifiedPlan()) {
  15071. description = this.interop.toUnifiedPlan(description);
  15072. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  15073. }
  15074. if (RTCBrowserType.usesPlanB()) {
  15075. description = normalizePlanB(description);
  15076. }
  15077. var self = this;
  15078. this.peerconnection.setRemoteDescription(description,
  15079. function () {
  15080. self.trace('setRemoteDescriptionOnSuccess');
  15081. successCallback();
  15082. },
  15083. function (err) {
  15084. self.trace('setRemoteDescriptionOnFailure', err);
  15085. failureCallback(err);
  15086. }
  15087. );
  15088. /*
  15089. if (this.statsinterval === null && this.maxstats > 0) {
  15090. // start gathering stats
  15091. }
  15092. */
  15093. };
  15094. TraceablePeerConnection.prototype.close = function () {
  15095. this.trace('stop');
  15096. if (this.statsinterval !== null) {
  15097. window.clearInterval(this.statsinterval);
  15098. this.statsinterval = null;
  15099. }
  15100. this.peerconnection.close();
  15101. };
  15102. TraceablePeerConnection.prototype.createOffer
  15103. = function (successCallback, failureCallback, constraints) {
  15104. var self = this;
  15105. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  15106. this.peerconnection.createOffer(
  15107. function (offer) {
  15108. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  15109. // NOTE this is not tested because in meet the focus generates the
  15110. // offer.
  15111. // if we're running on FF, transform to Plan B first.
  15112. if (RTCBrowserType.usesUnifiedPlan()) {
  15113. offer = self.interop.toPlanB(offer);
  15114. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  15115. }
  15116. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  15117. if (config.enableSimulcast && self.simulcast.isSupported()) {
  15118. offer = self.simulcast.mungeLocalDescription(offer);
  15119. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  15120. }
  15121. successCallback(offer);
  15122. },
  15123. function(err) {
  15124. self.trace('createOfferOnFailure', err);
  15125. failureCallback(err);
  15126. },
  15127. constraints
  15128. );
  15129. };
  15130. TraceablePeerConnection.prototype.createAnswer
  15131. = function (successCallback, failureCallback, constraints) {
  15132. var self = this;
  15133. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  15134. this.peerconnection.createAnswer(
  15135. function (answer) {
  15136. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  15137. // if we're running on FF, transform to Plan A first.
  15138. if (RTCBrowserType.usesUnifiedPlan()) {
  15139. answer = self.interop.toPlanB(answer);
  15140. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  15141. }
  15142. // munge local video SSRC
  15143. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  15144. if (config.enableSimulcast && self.simulcast.isSupported()) {
  15145. answer = self.simulcast.mungeLocalDescription(answer);
  15146. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  15147. }
  15148. successCallback(answer);
  15149. },
  15150. function(err) {
  15151. self.trace('createAnswerOnFailure', err);
  15152. failureCallback(err);
  15153. },
  15154. constraints
  15155. );
  15156. };
  15157. TraceablePeerConnection.prototype.addIceCandidate
  15158. = function (candidate, successCallback, failureCallback) {
  15159. //var self = this;
  15160. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  15161. this.peerconnection.addIceCandidate(candidate);
  15162. /* maybe later
  15163. this.peerconnection.addIceCandidate(candidate,
  15164. function () {
  15165. self.trace('addIceCandidateOnSuccess');
  15166. successCallback();
  15167. },
  15168. function (err) {
  15169. self.trace('addIceCandidateOnFailure', err);
  15170. failureCallback(err);
  15171. }
  15172. );
  15173. */
  15174. };
  15175. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  15176. // TODO: Is this the correct way to handle Opera, Temasys?
  15177. if (RTCBrowserType.isFirefox()) {
  15178. // ignore for now...
  15179. if(!errback)
  15180. errback = function () {};
  15181. this.peerconnection.getStats(null, callback, errback);
  15182. } else {
  15183. this.peerconnection.getStats(callback);
  15184. }
  15185. };
  15186. module.exports = TraceablePeerConnection;
  15187. },{"../../service/xmpp/XMPPEvents":174,"../RTC/RTC":9,"../RTC/RTCBrowserType.js":10,"./LocalSSRCReplacement":59,"sdp-interop":97,"sdp-simulcast":104,"sdp-transform":111}],64:[function(require,module,exports){
  15188. /* global $, $iq, APP, config, messageHandler,
  15189. roomName, sessionTerminated, Strophe, Util */
  15190. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15191. var Settings = require("../settings/Settings");
  15192. var AuthenticationEvents
  15193. = require("../../service/authentication/AuthenticationEvents");
  15194. /**
  15195. * Contains logic responsible for enabling/disabling functionality available
  15196. * only to moderator users.
  15197. */
  15198. var connection = null;
  15199. var focusUserJid;
  15200. function createExpBackoffTimer(step) {
  15201. var count = 1;
  15202. return function (reset) {
  15203. // Reset call
  15204. if (reset) {
  15205. count = 1;
  15206. return;
  15207. }
  15208. // Calculate next timeout
  15209. var timeout = Math.pow(2, count - 1);
  15210. count += 1;
  15211. return timeout * step;
  15212. };
  15213. }
  15214. var getNextTimeout = createExpBackoffTimer(1000);
  15215. var getNextErrorTimeout = createExpBackoffTimer(1000);
  15216. // External authentication stuff
  15217. var externalAuthEnabled = false;
  15218. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  15219. // it will be enabled automatically if focus detects the component through
  15220. // service discovery.
  15221. var sipGatewayEnabled;
  15222. var eventEmitter = null;
  15223. var Moderator = {
  15224. isModerator: function () {
  15225. return connection && connection.emuc.isModerator();
  15226. },
  15227. isPeerModerator: function (peerJid) {
  15228. return connection &&
  15229. connection.emuc.getMemberRole(peerJid) === 'moderator';
  15230. },
  15231. isExternalAuthEnabled: function () {
  15232. return externalAuthEnabled;
  15233. },
  15234. isSipGatewayEnabled: function () {
  15235. return sipGatewayEnabled;
  15236. },
  15237. setConnection: function (con) {
  15238. connection = con;
  15239. },
  15240. init: function (xmpp, emitter) {
  15241. this.xmppService = xmpp;
  15242. eventEmitter = emitter;
  15243. sipGatewayEnabled =
  15244. config.hosts && config.hosts.call_control !== undefined;
  15245. // Message listener that talks to POPUP window
  15246. function listener(event) {
  15247. if (event.data && event.data.sessionId) {
  15248. if (event.origin !== window.location.origin) {
  15249. console.warn("Ignoring sessionId from different origin: " +
  15250. event.origin);
  15251. return;
  15252. }
  15253. localStorage.setItem('sessionId', event.data.sessionId);
  15254. // After popup is closed we will authenticate
  15255. }
  15256. }
  15257. // Register
  15258. if (window.addEventListener) {
  15259. window.addEventListener("message", listener, false);
  15260. } else {
  15261. window.attachEvent("onmessage", listener);
  15262. }
  15263. },
  15264. onMucMemberLeft: function (jid) {
  15265. console.info("Someone left is it focus ? " + jid);
  15266. var resource = Strophe.getResourceFromJid(jid);
  15267. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  15268. console.info(
  15269. "Focus has left the room - leaving conference");
  15270. //hangUp();
  15271. // We'd rather reload to have everything re-initialized
  15272. // FIXME: show some message before reload
  15273. location.reload();
  15274. }
  15275. },
  15276. setFocusUserJid: function (focusJid) {
  15277. if (!focusUserJid) {
  15278. focusUserJid = focusJid;
  15279. console.info("Focus jid set to: " + focusUserJid);
  15280. }
  15281. },
  15282. getFocusUserJid: function () {
  15283. return focusUserJid;
  15284. },
  15285. getFocusComponent: function () {
  15286. // Get focus component address
  15287. var focusComponent = config.hosts.focus;
  15288. // If not specified use default: 'focus.domain'
  15289. if (!focusComponent) {
  15290. focusComponent = 'focus.' + config.hosts.domain;
  15291. }
  15292. return focusComponent;
  15293. },
  15294. createConferenceIq: function (roomName) {
  15295. // Generate create conference IQ
  15296. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  15297. // Session Id used for authentication
  15298. var sessionId = localStorage.getItem('sessionId');
  15299. var machineUID = Settings.getSettings().uid;
  15300. console.info(
  15301. "Session ID: " + sessionId + " machine UID: " + machineUID);
  15302. elem.c('conference', {
  15303. xmlns: 'http://jitsi.org/protocol/focus',
  15304. room: roomName,
  15305. 'machine-uid': machineUID
  15306. });
  15307. if (sessionId) {
  15308. elem.attrs({ 'session-id': sessionId});
  15309. }
  15310. if (config.hosts.bridge !== undefined) {
  15311. elem.c(
  15312. 'property',
  15313. { name: 'bridge', value: config.hosts.bridge})
  15314. .up();
  15315. }
  15316. // Tell the focus we have Jigasi configured
  15317. if (config.hosts.call_control !== undefined) {
  15318. elem.c(
  15319. 'property',
  15320. { name: 'call_control', value: config.hosts.call_control})
  15321. .up();
  15322. }
  15323. if (config.channelLastN !== undefined) {
  15324. elem.c(
  15325. 'property',
  15326. { name: 'channelLastN', value: config.channelLastN})
  15327. .up();
  15328. }
  15329. if (config.adaptiveLastN !== undefined) {
  15330. elem.c(
  15331. 'property',
  15332. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  15333. .up();
  15334. }
  15335. if (config.adaptiveSimulcast !== undefined) {
  15336. elem.c(
  15337. 'property',
  15338. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  15339. .up();
  15340. }
  15341. if (config.openSctp !== undefined) {
  15342. elem.c(
  15343. 'property',
  15344. { name: 'openSctp', value: config.openSctp})
  15345. .up();
  15346. }
  15347. if(config.startAudioMuted !== undefined)
  15348. {
  15349. elem.c(
  15350. 'property',
  15351. { name: 'startAudioMuted', value: config.startAudioMuted})
  15352. .up();
  15353. }
  15354. if(config.startVideoMuted !== undefined)
  15355. {
  15356. elem.c(
  15357. 'property',
  15358. { name: 'startVideoMuted', value: config.startVideoMuted})
  15359. .up();
  15360. }
  15361. elem.c(
  15362. 'property',
  15363. { name: 'simulcastMode', value: 'rewriting'})
  15364. .up();
  15365. elem.up();
  15366. return elem;
  15367. },
  15368. parseSessionId: function (resultIq) {
  15369. var sessionId = $(resultIq).find('conference').attr('session-id');
  15370. if (sessionId) {
  15371. console.info('Received sessionId: ' + sessionId);
  15372. localStorage.setItem('sessionId', sessionId);
  15373. }
  15374. },
  15375. parseConfigOptions: function (resultIq) {
  15376. Moderator.setFocusUserJid(
  15377. $(resultIq).find('conference').attr('focusjid'));
  15378. var authenticationEnabled
  15379. = $(resultIq).find(
  15380. '>conference>property' +
  15381. '[name=\'authentication\'][value=\'true\']').length > 0;
  15382. console.info("Authentication enabled: " + authenticationEnabled);
  15383. externalAuthEnabled = $(resultIq).find(
  15384. '>conference>property' +
  15385. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  15386. console.info('External authentication enabled: ' + externalAuthEnabled);
  15387. if (!externalAuthEnabled) {
  15388. // We expect to receive sessionId in 'internal' authentication mode
  15389. Moderator.parseSessionId(resultIq);
  15390. }
  15391. var authIdentity = $(resultIq).find('>conference').attr('identity');
  15392. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  15393. authenticationEnabled, authIdentity);
  15394. // Check if focus has auto-detected Jigasi component(this will be also
  15395. // included if we have passed our host from the config)
  15396. if ($(resultIq).find(
  15397. '>conference>property' +
  15398. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  15399. sipGatewayEnabled = true;
  15400. }
  15401. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  15402. },
  15403. // FIXME: we need to show the fact that we're waiting for the focus
  15404. // to the user(or that focus is not available)
  15405. allocateConferenceFocus: function (roomName, callback) {
  15406. // Try to use focus user JID from the config
  15407. Moderator.setFocusUserJid(config.focusUserJid);
  15408. // Send create conference IQ
  15409. var iq = Moderator.createConferenceIq(roomName);
  15410. var self = this;
  15411. connection.sendIQ(
  15412. iq,
  15413. function (result) {
  15414. // Setup config options
  15415. Moderator.parseConfigOptions(result);
  15416. if ('true' === $(result).find('conference').attr('ready')) {
  15417. // Reset both timers
  15418. getNextTimeout(true);
  15419. getNextErrorTimeout(true);
  15420. // Exec callback
  15421. callback();
  15422. } else {
  15423. var waitMs = getNextTimeout();
  15424. console.info("Waiting for the focus... " + waitMs);
  15425. // Reset error timeout
  15426. getNextErrorTimeout(true);
  15427. window.setTimeout(
  15428. function () {
  15429. Moderator.allocateConferenceFocus(
  15430. roomName, callback);
  15431. }, waitMs);
  15432. }
  15433. },
  15434. function (error) {
  15435. // Invalid session ? remove and try again
  15436. // without session ID to get a new one
  15437. var invalidSession
  15438. = $(error).find('>error>session-invalid').length;
  15439. if (invalidSession) {
  15440. console.info("Session expired! - removing");
  15441. localStorage.removeItem("sessionId");
  15442. }
  15443. if ($(error).find('>error>graceful-shutdown').length) {
  15444. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  15445. return;
  15446. }
  15447. // Check for error returned by the reservation system
  15448. var reservationErr = $(error).find('>error>reservation-error');
  15449. if (reservationErr.length) {
  15450. // Trigger error event
  15451. var errorCode = reservationErr.attr('error-code');
  15452. var errorMsg;
  15453. if ($(error).find('>error>text')) {
  15454. errorMsg = $(error).find('>error>text').text();
  15455. }
  15456. eventEmitter.emit(
  15457. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  15458. return;
  15459. }
  15460. // Not authorized to create new room
  15461. if ($(error).find('>error>not-authorized').length) {
  15462. console.warn("Unauthorized to start the conference", error);
  15463. var toDomain
  15464. = Strophe.getDomainFromJid(error.getAttribute('to'));
  15465. if (toDomain !== config.hosts.anonymousdomain) {
  15466. // FIXME: "is external" should come either from
  15467. // the focus or config.js
  15468. externalAuthEnabled = true;
  15469. }
  15470. eventEmitter.emit(
  15471. XMPPEvents.AUTHENTICATION_REQUIRED,
  15472. function () {
  15473. Moderator.allocateConferenceFocus(
  15474. roomName, callback);
  15475. });
  15476. return;
  15477. }
  15478. var waitMs = getNextErrorTimeout();
  15479. console.error("Focus error, retry after " + waitMs, error);
  15480. // Show message
  15481. var focusComponent = Moderator.getFocusComponent();
  15482. var retrySec = waitMs / 1000;
  15483. // FIXME: message is duplicated ?
  15484. // Do not show in case of session invalid
  15485. // which means just a retry
  15486. if (!invalidSession) {
  15487. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  15488. focusComponent, retrySec);
  15489. }
  15490. // Reset response timeout
  15491. getNextTimeout(true);
  15492. window.setTimeout(
  15493. function () {
  15494. Moderator.allocateConferenceFocus(roomName, callback);
  15495. }, waitMs);
  15496. }
  15497. );
  15498. },
  15499. getLoginUrl: function (roomName, urlCallback) {
  15500. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15501. iq.c('login-url', {
  15502. xmlns: 'http://jitsi.org/protocol/focus',
  15503. room: roomName,
  15504. 'machine-uid': Settings.getSettings().uid
  15505. });
  15506. connection.sendIQ(
  15507. iq,
  15508. function (result) {
  15509. var url = $(result).find('login-url').attr('url');
  15510. url = url = decodeURIComponent(url);
  15511. if (url) {
  15512. console.info("Got auth url: " + url);
  15513. urlCallback(url);
  15514. } else {
  15515. console.error(
  15516. "Failed to get auth url from the focus", result);
  15517. }
  15518. },
  15519. function (error) {
  15520. console.error("Get auth url error", error);
  15521. }
  15522. );
  15523. },
  15524. getPopupLoginUrl: function (roomName, urlCallback) {
  15525. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15526. iq.c('login-url', {
  15527. xmlns: 'http://jitsi.org/protocol/focus',
  15528. room: roomName,
  15529. 'machine-uid': Settings.getSettings().uid,
  15530. popup: true
  15531. });
  15532. connection.sendIQ(
  15533. iq,
  15534. function (result) {
  15535. var url = $(result).find('login-url').attr('url');
  15536. url = url = decodeURIComponent(url);
  15537. if (url) {
  15538. console.info("Got POPUP auth url: " + url);
  15539. urlCallback(url);
  15540. } else {
  15541. console.error(
  15542. "Failed to get POPUP auth url from the focus", result);
  15543. }
  15544. },
  15545. function (error) {
  15546. console.error('Get POPUP auth url error', error);
  15547. }
  15548. );
  15549. },
  15550. logout: function (callback) {
  15551. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  15552. var sessionId = localStorage.getItem('sessionId');
  15553. if (!sessionId) {
  15554. callback();
  15555. return;
  15556. }
  15557. iq.c('logout', {
  15558. xmlns: 'http://jitsi.org/protocol/focus',
  15559. 'session-id': sessionId
  15560. });
  15561. connection.sendIQ(
  15562. iq,
  15563. function (result) {
  15564. var logoutUrl = $(result).find('logout').attr('logout-url');
  15565. if (logoutUrl) {
  15566. logoutUrl = decodeURIComponent(logoutUrl);
  15567. }
  15568. console.info("Log out OK, url: " + logoutUrl, result);
  15569. localStorage.removeItem('sessionId');
  15570. callback(logoutUrl);
  15571. },
  15572. function (error) {
  15573. console.error("Logout error", error);
  15574. }
  15575. );
  15576. }
  15577. };
  15578. module.exports = Moderator;
  15579. },{"../../service/authentication/AuthenticationEvents":169,"../../service/xmpp/XMPPEvents":174,"../settings/Settings":51}],65:[function(require,module,exports){
  15580. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  15581. Toolbar, Util */
  15582. var Moderator = require("./moderator");
  15583. var recordingToken = null;
  15584. var recordingEnabled;
  15585. /**
  15586. * Whether to use a jirecon component for recording, or use the videobridge
  15587. * through COLIBRI.
  15588. */
  15589. var useJirecon;
  15590. /**
  15591. * The ID of the jirecon recording session. Jirecon generates it when we
  15592. * initially start recording, and it needs to be used in subsequent requests
  15593. * to jirecon.
  15594. */
  15595. var jireconRid = null;
  15596. /**
  15597. * The callback to update the recording button. Currently used from colibri
  15598. * after receiving a pending status.
  15599. */
  15600. var recordingStateChangeCallback = null;
  15601. function setRecordingToken(token) {
  15602. recordingToken = token;
  15603. }
  15604. function setRecordingJirecon(state, token, callback, connection) {
  15605. if (state == recordingEnabled){
  15606. return;
  15607. }
  15608. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  15609. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  15610. action: (state === 'on') ? 'start' : 'stop',
  15611. mucjid: connection.emuc.roomjid});
  15612. if (state === 'off'){
  15613. iq.attrs({rid: jireconRid});
  15614. }
  15615. console.log('Start recording');
  15616. connection.sendIQ(
  15617. iq,
  15618. function (result) {
  15619. // TODO wait for an IQ with the real status, since this is
  15620. // provisional?
  15621. jireconRid = $(result).find('recording').attr('rid');
  15622. console.log('Recording ' + ((state === 'on') ? 'started' : 'stopped') +
  15623. '(jirecon)' + result);
  15624. recordingEnabled = state;
  15625. if (state === 'off'){
  15626. jireconRid = null;
  15627. }
  15628. callback(state);
  15629. },
  15630. function (error) {
  15631. console.log('Failed to start recording, error: ', error);
  15632. callback(recordingEnabled);
  15633. });
  15634. }
  15635. // Sends a COLIBRI message which enables or disables (according to 'state')
  15636. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  15637. // with the new recording state, according to the IQ.
  15638. function setRecordingColibri(state, token, callback, connection) {
  15639. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  15640. elem.c('conference', {
  15641. xmlns: 'http://jitsi.org/protocol/colibri'
  15642. });
  15643. elem.c('recording', {state: state, token: token});
  15644. connection.sendIQ(elem,
  15645. function (result) {
  15646. console.log('Set recording "', state, '". Result:', result);
  15647. var recordingElem = $(result).find('>conference>recording');
  15648. var newState = recordingElem.attr('state');
  15649. recordingEnabled = newState;
  15650. callback(newState);
  15651. if (newState === 'pending' && recordingStateChangeCallback == null) {
  15652. recordingStateChangeCallback = callback;
  15653. connection.addHandler(function(iq){
  15654. var state = $(iq).find('recording').attr('state');
  15655. if (state)
  15656. recordingStateChangeCallback(state);
  15657. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  15658. }
  15659. },
  15660. function (error) {
  15661. console.warn(error);
  15662. callback(recordingEnabled);
  15663. }
  15664. );
  15665. }
  15666. function setRecording(state, token, callback, connection) {
  15667. if (useJirecon){
  15668. setRecordingJirecon(state, token, callback, connection);
  15669. } else {
  15670. setRecordingColibri(state, token, callback, connection);
  15671. }
  15672. }
  15673. var Recording = {
  15674. init: function () {
  15675. useJirecon = config.hosts &&
  15676. (typeof config.hosts.jirecon != "undefined");
  15677. },
  15678. toggleRecording: function (tokenEmptyCallback, recordingStateChangeCallback, connection) {
  15679. if (!Moderator.isModerator()) {
  15680. console.log(
  15681. 'non-focus, or conference not yet organized:' +
  15682. ' not enabling recording');
  15683. return;
  15684. }
  15685. var self = this;
  15686. // Jirecon does not (currently) support a token.
  15687. if (!recordingToken && !useJirecon) {
  15688. tokenEmptyCallback(function (value) {
  15689. setRecordingToken(value);
  15690. self.toggleRecording(tokenEmptyCallback, recordingStateChangeCallback, connection);
  15691. });
  15692. return;
  15693. }
  15694. var oldState = recordingEnabled;
  15695. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  15696. setRecording(newState,
  15697. recordingToken,
  15698. function (state) {
  15699. console.log("New recording state: ", state);
  15700. if (state === oldState) {
  15701. // FIXME: new focus:
  15702. // this will not work when moderator changes
  15703. // during active session. Then it will assume that
  15704. // recording status has changed to true, but it might have
  15705. // been already true(and we only received actual status from
  15706. // the focus).
  15707. //
  15708. // SO we start with status null, so that it is initialized
  15709. // here and will fail only after second click, so if invalid
  15710. // token was used we have to press the button twice before
  15711. // current status will be fetched and token will be reset.
  15712. //
  15713. // Reliable way would be to return authentication error.
  15714. // Or status update when moderator connects.
  15715. // Or we have to stop recording session when current
  15716. // moderator leaves the room.
  15717. // Failed to change, reset the token because it might
  15718. // have been wrong
  15719. setRecordingToken(null);
  15720. }
  15721. recordingStateChangeCallback(state);
  15722. },
  15723. connection
  15724. );
  15725. }
  15726. };
  15727. module.exports = Recording;
  15728. },{"./moderator":64}],66:[function(require,module,exports){
  15729. /* jshint -W117 */
  15730. /* a simple MUC connection plugin
  15731. * can only handle a single MUC room
  15732. */
  15733. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15734. var Moderator = require("./moderator");
  15735. module.exports = function(XMPP, eventEmitter) {
  15736. Strophe.addConnectionPlugin('emuc', {
  15737. connection: null,
  15738. roomjid: null,
  15739. myroomjid: null,
  15740. members: {},
  15741. list_members: [], // so we can elect a new focus
  15742. presMap: {},
  15743. preziMap: {},
  15744. joined: false,
  15745. isOwner: false,
  15746. role: null,
  15747. focusMucJid: null,
  15748. bridgeIsDown: false,
  15749. init: function (conn) {
  15750. this.connection = conn;
  15751. },
  15752. initPresenceMap: function (myroomjid) {
  15753. this.presMap['to'] = myroomjid;
  15754. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  15755. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  15756. this.addAudioInfoToPresence(true);
  15757. }
  15758. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  15759. this.addVideoInfoToPresence(true);
  15760. }
  15761. },
  15762. doJoin: function (jid, password) {
  15763. this.myroomjid = jid;
  15764. console.info("Joined MUC as " + this.myroomjid);
  15765. this.initPresenceMap(this.myroomjid);
  15766. if (!this.roomjid) {
  15767. this.roomjid = Strophe.getBareJidFromJid(jid);
  15768. // add handlers (just once)
  15769. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  15770. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  15771. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  15772. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  15773. }
  15774. if (password !== undefined) {
  15775. this.presMap['password'] = password;
  15776. }
  15777. this.sendPresence();
  15778. },
  15779. doLeave: function () {
  15780. console.log("do leave", this.myroomjid);
  15781. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  15782. this.presMap.length = 0;
  15783. this.connection.send(pres);
  15784. },
  15785. createNonAnonymousRoom: function () {
  15786. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15787. var getForm = $iq({type: 'get', to: this.roomjid})
  15788. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15789. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15790. var self = this;
  15791. this.connection.sendIQ(getForm, function (form) {
  15792. if (!$(form).find(
  15793. '>query>x[xmlns="jabber:x:data"]' +
  15794. '>field[var="muc#roomconfig_whois"]').length) {
  15795. console.error('non-anonymous rooms not supported');
  15796. return;
  15797. }
  15798. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15799. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15800. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15801. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15802. .c('value')
  15803. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15804. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15805. .c('value').t('anyone').up().up();
  15806. self.connection.sendIQ(formSubmit);
  15807. }, function (error) {
  15808. console.error("Error getting room configuration form");
  15809. });
  15810. },
  15811. onPresence: function (pres) {
  15812. var from = pres.getAttribute('from');
  15813. // What is this for? A workaround for something?
  15814. if (pres.getAttribute('type')) {
  15815. return true;
  15816. }
  15817. // Parse etherpad tag.
  15818. var etherpad = $(pres).find('>etherpad');
  15819. if (etherpad.length) {
  15820. if (config.etherpad_base) {
  15821. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15822. }
  15823. }
  15824. var url;
  15825. // Parse prezi tag.
  15826. var presentation = $(pres).find('>prezi');
  15827. if (presentation.length) {
  15828. url = presentation.attr('url');
  15829. var current = presentation.find('>current').text();
  15830. console.log('presentation info received from', from, url);
  15831. if (this.preziMap[from] == null) {
  15832. this.preziMap[from] = url;
  15833. $(document).trigger('presentationadded.muc', [from, url, current]);
  15834. }
  15835. else {
  15836. $(document).trigger('gotoslide.muc', [from, url, current]);
  15837. }
  15838. }
  15839. else if (this.preziMap[from] != null) {
  15840. url = this.preziMap[from];
  15841. delete this.preziMap[from];
  15842. $(document).trigger('presentationremoved.muc', [from, url]);
  15843. }
  15844. // Parse audio info tag.
  15845. var audioMuted = $(pres).find('>audiomuted');
  15846. if (audioMuted.length) {
  15847. eventEmitter.emit(XMPPEvents.PARTICIPANT_AUDIO_MUTED,
  15848. from, (audioMuted.text() === "true"));
  15849. }
  15850. // Parse video info tag.
  15851. var videoMuted = $(pres).find('>videomuted');
  15852. if (videoMuted.length) {
  15853. eventEmitter.emit(XMPPEvents.PARTICIPANT_VIDEO_MUTED,
  15854. from, (videoMuted.text() === "true"));
  15855. }
  15856. var startMuted = $(pres).find('>startmuted');
  15857. if (startMuted.length && Moderator.isPeerModerator(from)) {
  15858. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15859. startMuted.attr("audio") === "true",
  15860. startMuted.attr("video") === "true");
  15861. }
  15862. var devices = $(pres).find('>devices');
  15863. if(devices.length)
  15864. {
  15865. var audio = devices.find('>audio');
  15866. var video = devices.find('>video');
  15867. var devicesValues = {audio: false, video: false};
  15868. if(audio.length && audio.text() === "true")
  15869. {
  15870. devicesValues.audio = true;
  15871. }
  15872. if(video.length && video.text() === "true")
  15873. {
  15874. devicesValues.video = true;
  15875. }
  15876. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15877. Strophe.getResourceFromJid(from), devicesValues);
  15878. }
  15879. var videoType = $(pres).find('>videoType');
  15880. if (videoType.length)
  15881. {
  15882. if (videoType.text().length)
  15883. {
  15884. eventEmitter.emit(XMPPEvents.PARTICIPANT_VIDEO_TYPE_CHANGED,
  15885. Strophe.getResourceFromJid(from), videoType.text());
  15886. }
  15887. }
  15888. var stats = $(pres).find('>stats');
  15889. if (stats.length) {
  15890. var statsObj = {};
  15891. Strophe.forEachChild(stats[0], "stat", function (el) {
  15892. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15893. });
  15894. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15895. }
  15896. // Parse status.
  15897. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15898. this.isOwner = true;
  15899. this.createNonAnonymousRoom();
  15900. }
  15901. // Parse roles.
  15902. var member = {};
  15903. member.show = $(pres).find('>show').text();
  15904. member.status = $(pres).find('>status').text();
  15905. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15906. member.affiliation = tmp.attr('affiliation');
  15907. member.role = tmp.attr('role');
  15908. // Focus recognition
  15909. member.jid = tmp.attr('jid');
  15910. member.isFocus = false;
  15911. if (member.jid
  15912. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15913. member.isFocus = true;
  15914. }
  15915. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15916. member.displayName = (nicktag.length > 0 ? nicktag.text() : null);
  15917. if (from == this.myroomjid) {
  15918. if (member.affiliation == 'owner') this.isOwner = true;
  15919. if (this.role !== member.role) {
  15920. this.role = member.role;
  15921. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15922. from, member, pres, Moderator.isModerator());
  15923. }
  15924. if (!this.joined) {
  15925. this.joined = true;
  15926. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15927. this.list_members.push(from);
  15928. }
  15929. } else if (this.members[from] === undefined) {
  15930. // new participant
  15931. this.members[from] = member;
  15932. this.list_members.push(from);
  15933. console.log('entered', from, member);
  15934. if (member.isFocus) {
  15935. this.focusMucJid = from;
  15936. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15937. }
  15938. else {
  15939. var id = $(pres).find('>userId').text();
  15940. var email = $(pres).find('>email');
  15941. if (email.length > 0) {
  15942. id = email.text();
  15943. }
  15944. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15945. }
  15946. } else {
  15947. // Presence update for existing participant
  15948. // Watch role change:
  15949. if (this.members[from].role != member.role) {
  15950. this.members[from].role = member.role;
  15951. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15952. member.role, member.displayName);
  15953. }
  15954. }
  15955. // Always trigger presence to update bindings
  15956. this.parsePresence(from, member, pres);
  15957. // Trigger status message update
  15958. if (member.status) {
  15959. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15960. }
  15961. return true;
  15962. },
  15963. onPresenceUnavailable: function (pres) {
  15964. var from = pres.getAttribute('from');
  15965. // room destroyed ?
  15966. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15967. '>destroy').length) {
  15968. var reason;
  15969. var reasonSelect = $(pres).find(
  15970. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15971. '>destroy>reason');
  15972. if (reasonSelect.length) {
  15973. reason = reasonSelect.text();
  15974. }
  15975. XMPP.disposeConference(false);
  15976. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15977. return true;
  15978. }
  15979. // Status code 110 indicates that this notification is "self-presence".
  15980. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15981. delete this.members[from];
  15982. this.list_members.splice(this.list_members.indexOf(from), 1);
  15983. this.onParticipantLeft(from);
  15984. }
  15985. // If the status code is 110 this means we're leaving and we would like
  15986. // to remove everyone else from our view, so we trigger the event.
  15987. else if (this.list_members.length > 1) {
  15988. for (var i = 0; i < this.list_members.length; i++) {
  15989. var member = this.list_members[i];
  15990. delete this.members[i];
  15991. this.list_members.splice(i, 1);
  15992. this.onParticipantLeft(member);
  15993. }
  15994. }
  15995. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15996. $(document).trigger('kicked.muc', [from]);
  15997. if (this.myroomjid === from) {
  15998. XMPP.disposeConference(false);
  15999. eventEmitter.emit(XMPPEvents.KICKED);
  16000. }
  16001. }
  16002. return true;
  16003. },
  16004. onPresenceError: function (pres) {
  16005. var from = pres.getAttribute('from');
  16006. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  16007. console.log('on password required', from);
  16008. var self = this;
  16009. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  16010. self.doJoin(from, value);
  16011. });
  16012. } else if ($(pres).find(
  16013. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  16014. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  16015. if (toDomain === config.hosts.anonymousdomain) {
  16016. // enter the room by replying with 'not-authorized'. This would
  16017. // result in reconnection from authorized domain.
  16018. // We're either missing Jicofo/Prosody config for anonymous
  16019. // domains or something is wrong.
  16020. // XMPP.promptLogin();
  16021. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  16022. } else {
  16023. console.warn('onPresError ', pres);
  16024. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  16025. }
  16026. } else {
  16027. console.warn('onPresError ', pres);
  16028. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  16029. }
  16030. return true;
  16031. },
  16032. sendMessage: function (body, nickname) {
  16033. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  16034. msg.c('body', body).up();
  16035. if (nickname) {
  16036. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  16037. }
  16038. this.connection.send(msg);
  16039. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  16040. },
  16041. setSubject: function (subject) {
  16042. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  16043. msg.c('subject', subject);
  16044. this.connection.send(msg);
  16045. console.log("topic changed to " + subject);
  16046. },
  16047. onMessage: function (msg) {
  16048. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  16049. var from = msg.getAttribute('from');
  16050. var nick =
  16051. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  16052. .text() ||
  16053. Strophe.getResourceFromJid(from);
  16054. var txt = $(msg).find('>body').text();
  16055. var type = msg.getAttribute("type");
  16056. if (type == "error") {
  16057. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  16058. $(msg).find('>text').text(), txt);
  16059. return true;
  16060. }
  16061. var subject = $(msg).find('>subject');
  16062. if (subject.length) {
  16063. var subjectText = subject.text();
  16064. if (subjectText || subjectText == "") {
  16065. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  16066. console.log("Subject is changed to " + subjectText);
  16067. }
  16068. }
  16069. // xep-0203 delay
  16070. var stamp = $(msg).find('>delay').attr('stamp');
  16071. if (!stamp) {
  16072. // or xep-0091 delay, UTC timestamp
  16073. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  16074. if (stamp) {
  16075. // the format is CCYYMMDDThh:mm:ss
  16076. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  16077. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  16078. }
  16079. }
  16080. if (txt) {
  16081. console.log('chat', nick, txt);
  16082. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  16083. from, nick, txt, this.myroomjid, stamp);
  16084. }
  16085. return true;
  16086. },
  16087. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16088. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  16089. var ob = this;
  16090. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  16091. function (res) {
  16092. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  16093. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  16094. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  16095. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  16096. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  16097. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  16098. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  16099. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  16100. ob.connection.sendIQ(formsubmit,
  16101. onSuccess,
  16102. onError);
  16103. } else {
  16104. onNotSupported();
  16105. }
  16106. }, onError);
  16107. },
  16108. kick: function (jid) {
  16109. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  16110. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  16111. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  16112. .c('reason').t('You have been kicked.').up().up().up();
  16113. this.connection.sendIQ(
  16114. kickIQ,
  16115. function (result) {
  16116. console.log('Kick participant with jid: ', jid, result);
  16117. },
  16118. function (error) {
  16119. console.log('Kick participant error: ', error);
  16120. });
  16121. },
  16122. sendPresence: function () {
  16123. if (!this.presMap['to']) {
  16124. // Too early to send presence - not initialized
  16125. return;
  16126. }
  16127. var pres = $pres({to: this.presMap['to'] });
  16128. pres.c('x', {xmlns: this.presMap['xns']});
  16129. if (this.presMap['password']) {
  16130. pres.c('password').t(this.presMap['password']).up();
  16131. }
  16132. pres.up();
  16133. // Send XEP-0115 'c' stanza that contains our capabilities info
  16134. if (this.connection.caps) {
  16135. this.connection.caps.node = config.clientNode;
  16136. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  16137. }
  16138. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  16139. .t(navigator.userAgent).up();
  16140. if (this.presMap['bridgeIsDown']) {
  16141. pres.c('bridgeIsDown').up();
  16142. }
  16143. if (this.presMap['email']) {
  16144. pres.c('email').t(this.presMap['email']).up();
  16145. }
  16146. if (this.presMap['userId']) {
  16147. pres.c('userId').t(this.presMap['userId']).up();
  16148. }
  16149. if (this.presMap['displayName']) {
  16150. // XEP-0172
  16151. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  16152. .t(this.presMap['displayName']).up();
  16153. }
  16154. if(this.presMap["devices"])
  16155. {
  16156. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  16157. .c('video').t(this.presMap['devices'].video).up().up();
  16158. }
  16159. if (this.presMap['audions']) {
  16160. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  16161. .t(this.presMap['audiomuted']).up();
  16162. }
  16163. if (this.presMap['videons']) {
  16164. pres.c('videomuted', {xmlns: this.presMap['videons']})
  16165. .t(this.presMap['videomuted']).up();
  16166. }
  16167. if (this.presMap['videoTypeNs']) {
  16168. pres.c('videoType', { xmlns: this.presMap['videoTypeNs'] })
  16169. .t(this.presMap['videoType']).up();
  16170. }
  16171. if (this.presMap['statsns']) {
  16172. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  16173. for (var stat in this.presMap["stats"])
  16174. if (this.presMap["stats"][stat] != null)
  16175. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  16176. pres.up();
  16177. }
  16178. if (this.presMap['prezins']) {
  16179. pres.c('prezi',
  16180. {xmlns: this.presMap['prezins'],
  16181. 'url': this.presMap['preziurl']})
  16182. .c('current').t(this.presMap['prezicurrent']).up().up();
  16183. }
  16184. if(this.presMap["startMuted"] !== undefined)
  16185. {
  16186. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  16187. video: this.presMap["startMuted"].video,
  16188. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  16189. delete this.presMap["startMuted"];
  16190. }
  16191. pres.up();
  16192. this.connection.send(pres);
  16193. },
  16194. addDisplayNameToPresence: function (displayName) {
  16195. this.presMap['displayName'] = displayName;
  16196. },
  16197. addDevicesToPresence: function (devices) {
  16198. this.presMap['devices'] = devices;
  16199. },
  16200. /**
  16201. * Adds the info about the type of our video stream.
  16202. * @param videoType 'camera' or 'screen'
  16203. */
  16204. addVideoTypeToPresence: function (videoType) {
  16205. this.presMap['videoTypeNs'] = 'http://jitsi.org/jitmeet/video';
  16206. this.presMap['videoType'] = videoType;
  16207. },
  16208. addPreziToPresence: function (url, currentSlide) {
  16209. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  16210. this.presMap['preziurl'] = url;
  16211. this.presMap['prezicurrent'] = currentSlide;
  16212. },
  16213. removePreziFromPresence: function () {
  16214. delete this.presMap['prezins'];
  16215. delete this.presMap['preziurl'];
  16216. delete this.presMap['prezicurrent'];
  16217. },
  16218. addCurrentSlideToPresence: function (currentSlide) {
  16219. this.presMap['prezicurrent'] = currentSlide;
  16220. },
  16221. getPrezi: function (roomjid) {
  16222. return this.preziMap[roomjid];
  16223. },
  16224. addAudioInfoToPresence: function (isMuted) {
  16225. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  16226. this.presMap['audiomuted'] = isMuted.toString();
  16227. },
  16228. addVideoInfoToPresence: function (isMuted) {
  16229. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  16230. this.presMap['videomuted'] = isMuted.toString();
  16231. },
  16232. addConnectionInfoToPresence: function (stats) {
  16233. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  16234. this.presMap['stats'] = stats;
  16235. },
  16236. findJidFromResource: function (resourceJid) {
  16237. if (resourceJid &&
  16238. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  16239. return this.myroomjid;
  16240. }
  16241. var peerJid = null;
  16242. Object.keys(this.members).some(function (jid) {
  16243. peerJid = jid;
  16244. return Strophe.getResourceFromJid(jid) === resourceJid;
  16245. });
  16246. return peerJid;
  16247. },
  16248. addBridgeIsDownToPresence: function () {
  16249. this.presMap['bridgeIsDown'] = true;
  16250. },
  16251. addEmailToPresence: function (email) {
  16252. this.presMap['email'] = email;
  16253. },
  16254. addUserIdToPresence: function (userId) {
  16255. this.presMap['userId'] = userId;
  16256. },
  16257. addStartMutedToPresence: function (audio, video) {
  16258. this.presMap["startMuted"] = {audio: audio, video: video};
  16259. },
  16260. isModerator: function () {
  16261. return this.role === 'moderator';
  16262. },
  16263. getMemberRole: function (peerJid) {
  16264. if (this.members[peerJid]) {
  16265. return this.members[peerJid].role;
  16266. }
  16267. return null;
  16268. },
  16269. onParticipantLeft: function (jid) {
  16270. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  16271. this.connection.jingle.terminateByJid(jid);
  16272. if (this.getPrezi(jid)) {
  16273. $(document).trigger('presentationremoved.muc',
  16274. [jid, this.getPrezi(jid)]);
  16275. }
  16276. Moderator.onMucMemberLeft(jid);
  16277. },
  16278. parsePresence: function (from, member, pres) {
  16279. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  16280. this.bridgeIsDown = true;
  16281. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  16282. }
  16283. if(member.isFocus)
  16284. return;
  16285. var displayName = !config.displayJids
  16286. ? member.displayName : Strophe.getResourceFromJid(from);
  16287. if (displayName && displayName.length > 0) {
  16288. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  16289. }
  16290. var id = $(pres).find('>userID').text();
  16291. var email = $(pres).find('>email');
  16292. if (email.length > 0) {
  16293. id = email.text();
  16294. }
  16295. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  16296. }
  16297. });
  16298. };
  16299. },{"../../service/xmpp/XMPPEvents":174,"./moderator":64}],67:[function(require,module,exports){
  16300. /* jshint -W117 */
  16301. var JingleSession = require("./JingleSessionPC");
  16302. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16303. var RTCBrowserType = require("../RTC/RTCBrowserType");
  16304. module.exports = function(XMPP, eventEmitter) {
  16305. Strophe.addConnectionPlugin('jingle', {
  16306. connection: null,
  16307. sessions: {},
  16308. jid2session: {},
  16309. ice_config: {iceServers: []},
  16310. pc_constraints: {},
  16311. activecall: null,
  16312. media_constraints: {
  16313. mandatory: {
  16314. 'OfferToReceiveAudio': true,
  16315. 'OfferToReceiveVideo': true
  16316. }
  16317. // MozDontOfferDataChannel: true when this is firefox
  16318. },
  16319. init: function (conn) {
  16320. this.connection = conn;
  16321. if (this.connection.disco) {
  16322. // http://xmpp.org/extensions/xep-0167.html#support
  16323. // http://xmpp.org/extensions/xep-0176.html#support
  16324. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  16325. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  16326. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  16327. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  16328. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  16329. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  16330. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  16331. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  16332. || RTCBrowserType.isTemasysPluginUsed()) {
  16333. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  16334. }
  16335. // this is dealt with by SDP O/A so we don't need to announce this
  16336. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  16337. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  16338. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  16339. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  16340. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  16341. }
  16342. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  16343. },
  16344. onJingle: function (iq) {
  16345. var sid = $(iq).find('jingle').attr('sid');
  16346. var action = $(iq).find('jingle').attr('action');
  16347. var fromJid = iq.getAttribute('from');
  16348. // send ack first
  16349. var ack = $iq({type: 'result',
  16350. to: fromJid,
  16351. id: iq.getAttribute('id')
  16352. });
  16353. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  16354. var sess = this.sessions[sid];
  16355. if ('session-initiate' != action) {
  16356. if (sess === null) {
  16357. ack.type = 'error';
  16358. ack.c('error', {type: 'cancel'})
  16359. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  16360. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  16361. this.connection.send(ack);
  16362. return true;
  16363. }
  16364. // local jid is not checked
  16365. if (fromJid != sess.peerjid) {
  16366. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  16367. ack.type = 'error';
  16368. ack.c('error', {type: 'cancel'})
  16369. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  16370. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  16371. this.connection.send(ack);
  16372. return true;
  16373. }
  16374. } else if (sess !== undefined) {
  16375. // existing session with same session id
  16376. // this might be out-of-order if the sess.peerjid is the same as from
  16377. ack.type = 'error';
  16378. ack.c('error', {type: 'cancel'})
  16379. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  16380. console.warn('duplicate session id', sid);
  16381. this.connection.send(ack);
  16382. return true;
  16383. }
  16384. // FIXME: check for a defined action
  16385. this.connection.send(ack);
  16386. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  16387. switch (action) {
  16388. case 'session-initiate':
  16389. var startMuted = $(iq).find('jingle>startmuted');
  16390. if (startMuted && startMuted.length > 0) {
  16391. var audioMuted = startMuted.attr("audio");
  16392. var videoMuted = startMuted.attr("video");
  16393. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  16394. audioMuted === "true", videoMuted === "true");
  16395. }
  16396. sess = new JingleSession(
  16397. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  16398. this.connection, XMPP, eventEmitter);
  16399. // configure session
  16400. sess.media_constraints = this.media_constraints;
  16401. sess.pc_constraints = this.pc_constraints;
  16402. sess.ice_config = this.ice_config;
  16403. sess.initialize(fromJid, false);
  16404. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  16405. sess.setOffer($(iq).find('>jingle'));
  16406. this.sessions[sess.sid] = sess;
  16407. this.jid2session[sess.peerjid] = sess;
  16408. // the callback should either
  16409. // .sendAnswer and .accept
  16410. // or .sendTerminate -- not necessarily synchronous
  16411. // TODO: do we check activecall == null?
  16412. this.connection.jingle.activecall = sess;
  16413. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  16414. // TODO: check affiliation and/or role
  16415. console.log('emuc data for', sess.peerjid,
  16416. this.connection.emuc.members[sess.peerjid]);
  16417. sess.sendAnswer();
  16418. sess.accept();
  16419. break;
  16420. case 'session-accept':
  16421. sess.setAnswer($(iq).find('>jingle'));
  16422. sess.accept();
  16423. $(document).trigger('callaccepted.jingle', [sess.sid]);
  16424. break;
  16425. case 'session-terminate':
  16426. // If this is not the focus sending the terminate, we have
  16427. // nothing more to do here.
  16428. if (Object.keys(this.sessions).length < 1
  16429. || !(this.sessions[Object.keys(this.sessions)[0]]
  16430. instanceof JingleSession))
  16431. {
  16432. break;
  16433. }
  16434. console.log('terminating...', sess.sid);
  16435. sess.terminate();
  16436. this.terminate(sess.sid);
  16437. if ($(iq).find('>jingle>reason').length) {
  16438. $(document).trigger('callterminated.jingle', [
  16439. sess.sid,
  16440. sess.peerjid,
  16441. $(iq).find('>jingle>reason>:first')[0].tagName,
  16442. $(iq).find('>jingle>reason>text').text()
  16443. ]);
  16444. } else {
  16445. $(document).trigger('callterminated.jingle',
  16446. [sess.sid, sess.peerjid]);
  16447. }
  16448. break;
  16449. case 'transport-info':
  16450. sess.addIceCandidate($(iq).find('>jingle>content'));
  16451. break;
  16452. case 'session-info':
  16453. var affected;
  16454. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16455. $(document).trigger('ringing.jingle', [sess.sid]);
  16456. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16457. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16458. $(document).trigger('mute.jingle', [sess.sid, affected]);
  16459. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16460. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16461. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  16462. }
  16463. break;
  16464. case 'addsource': // FIXME: proprietary, un-jingleish
  16465. case 'source-add': // FIXME: proprietary
  16466. sess.addSource($(iq).find('>jingle>content'), fromJid);
  16467. break;
  16468. case 'removesource': // FIXME: proprietary, un-jingleish
  16469. case 'source-remove': // FIXME: proprietary
  16470. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  16471. break;
  16472. default:
  16473. console.warn('jingle action not implemented', action);
  16474. break;
  16475. }
  16476. return true;
  16477. },
  16478. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  16479. var sess = new JingleSession(myjid || this.connection.jid,
  16480. Math.random().toString(36).substr(2, 12), // random string
  16481. this.connection, XMPP, eventEmitter);
  16482. // configure session
  16483. sess.media_constraints = this.media_constraints;
  16484. sess.pc_constraints = this.pc_constraints;
  16485. sess.ice_config = this.ice_config;
  16486. sess.initialize(peerjid, true);
  16487. this.sessions[sess.sid] = sess;
  16488. this.jid2session[sess.peerjid] = sess;
  16489. sess.sendOffer();
  16490. return sess;
  16491. },
  16492. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  16493. if (sid === null || sid === undefined) {
  16494. for (sid in this.sessions) {
  16495. if (this.sessions[sid].state != 'ended') {
  16496. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16497. this.sessions[sid].terminate();
  16498. }
  16499. delete this.jid2session[this.sessions[sid].peerjid];
  16500. delete this.sessions[sid];
  16501. }
  16502. } else if (this.sessions.hasOwnProperty(sid)) {
  16503. if (this.sessions[sid].state != 'ended') {
  16504. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16505. this.sessions[sid].terminate();
  16506. }
  16507. delete this.jid2session[this.sessions[sid].peerjid];
  16508. delete this.sessions[sid];
  16509. }
  16510. },
  16511. // Used to terminate a session when an unavailable presence is received.
  16512. terminateByJid: function (jid) {
  16513. if (this.jid2session.hasOwnProperty(jid)) {
  16514. var sess = this.jid2session[jid];
  16515. if (sess) {
  16516. sess.terminate();
  16517. console.log('peer went away silently', jid);
  16518. delete this.sessions[sess.sid];
  16519. delete this.jid2session[jid];
  16520. $(document).trigger('callterminated.jingle',
  16521. [sess.sid, jid], 'gone');
  16522. }
  16523. }
  16524. },
  16525. terminateRemoteByJid: function (jid, reason) {
  16526. if (this.jid2session.hasOwnProperty(jid)) {
  16527. var sess = this.jid2session[jid];
  16528. if (sess) {
  16529. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  16530. sess.terminate();
  16531. console.log('terminate peer with jid', sess.sid, jid);
  16532. delete this.sessions[sess.sid];
  16533. delete this.jid2session[jid];
  16534. $(document).trigger('callterminated.jingle',
  16535. [sess.sid, jid, 'kicked']);
  16536. }
  16537. }
  16538. },
  16539. getStunAndTurnCredentials: function () {
  16540. // get stun and turn configuration from server via xep-0215
  16541. // uses time-limited credentials as described in
  16542. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  16543. //
  16544. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  16545. // for a prosody module which implements this
  16546. //
  16547. // currently, this doesn't work with updateIce and therefore credentials with a long
  16548. // validity have to be fetched before creating the peerconnection
  16549. // TODO: implement refresh via updateIce as described in
  16550. // https://code.google.com/p/webrtc/issues/detail?id=1650
  16551. var self = this;
  16552. this.connection.sendIQ(
  16553. $iq({type: 'get', to: this.connection.domain})
  16554. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  16555. function (res) {
  16556. var iceservers = [];
  16557. $(res).find('>services>service').each(function (idx, el) {
  16558. el = $(el);
  16559. var dict = {};
  16560. var type = el.attr('type');
  16561. switch (type) {
  16562. case 'stun':
  16563. dict.url = 'stun:' + el.attr('host');
  16564. if (el.attr('port')) {
  16565. dict.url += ':' + el.attr('port');
  16566. }
  16567. iceservers.push(dict);
  16568. break;
  16569. case 'turn':
  16570. case 'turns':
  16571. dict.url = type + ':';
  16572. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  16573. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  16574. dict.url += el.attr('username') + '@';
  16575. } else {
  16576. dict.username = el.attr('username'); // only works in M28
  16577. }
  16578. }
  16579. dict.url += el.attr('host');
  16580. if (el.attr('port') && el.attr('port') != '3478') {
  16581. dict.url += ':' + el.attr('port');
  16582. }
  16583. if (el.attr('transport') && el.attr('transport') != 'udp') {
  16584. dict.url += '?transport=' + el.attr('transport');
  16585. }
  16586. if (el.attr('password')) {
  16587. dict.credential = el.attr('password');
  16588. }
  16589. iceservers.push(dict);
  16590. break;
  16591. }
  16592. });
  16593. self.ice_config.iceServers = iceservers;
  16594. },
  16595. function (err) {
  16596. console.warn('getting turn credentials failed', err);
  16597. console.warn('is mod_turncredentials or similar installed?');
  16598. }
  16599. );
  16600. // implement push?
  16601. },
  16602. /**
  16603. * Returns the data saved in 'updateLog' in a format to be logged.
  16604. */
  16605. getLog: function () {
  16606. var data = {};
  16607. var self = this;
  16608. Object.keys(this.sessions).forEach(function (sid) {
  16609. var session = self.sessions[sid];
  16610. if (session.peerconnection && session.peerconnection.updateLog) {
  16611. // FIXME: should probably be a .dump call
  16612. data["jingle_" + session.sid] = {
  16613. updateLog: session.peerconnection.updateLog,
  16614. stats: session.peerconnection.stats,
  16615. url: window.location.href
  16616. };
  16617. }
  16618. });
  16619. return data;
  16620. }
  16621. });
  16622. };
  16623. },{"../../service/xmpp/XMPPEvents":174,"../RTC/RTCBrowserType":10,"./JingleSessionPC":58}],68:[function(require,module,exports){
  16624. /* global Strophe */
  16625. module.exports = function () {
  16626. Strophe.addConnectionPlugin('logger', {
  16627. // logs raw stanzas and makes them available for download as JSON
  16628. connection: null,
  16629. log: [],
  16630. init: function (conn) {
  16631. this.connection = conn;
  16632. this.connection.rawInput = this.log_incoming.bind(this);
  16633. this.connection.rawOutput = this.log_outgoing.bind(this);
  16634. },
  16635. log_incoming: function (stanza) {
  16636. this.log.push([new Date().getTime(), 'incoming', stanza]);
  16637. },
  16638. log_outgoing: function (stanza) {
  16639. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  16640. }
  16641. });
  16642. };
  16643. },{}],69:[function(require,module,exports){
  16644. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  16645. setAudioMuted, Strophe */
  16646. /**
  16647. * Moderate connection plugin.
  16648. */
  16649. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16650. module.exports = function (XMPP, eventEmitter) {
  16651. Strophe.addConnectionPlugin('moderate', {
  16652. connection: null,
  16653. init: function (conn) {
  16654. this.connection = conn;
  16655. this.connection.addHandler(this.onMute.bind(this),
  16656. 'http://jitsi.org/jitmeet/audio',
  16657. 'iq',
  16658. 'set',
  16659. null,
  16660. null);
  16661. },
  16662. setMute: function (jid, mute) {
  16663. console.info("set mute", mute);
  16664. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  16665. .c('mute', {
  16666. xmlns: 'http://jitsi.org/jitmeet/audio',
  16667. jid: jid
  16668. })
  16669. .t(mute.toString())
  16670. .up();
  16671. this.connection.sendIQ(
  16672. iqToFocus,
  16673. function (result) {
  16674. console.log('set mute', result);
  16675. },
  16676. function (error) {
  16677. console.log('set mute error', error);
  16678. });
  16679. },
  16680. onMute: function (iq) {
  16681. var from = iq.getAttribute('from');
  16682. if (from !== this.connection.emuc.focusMucJid) {
  16683. console.warn("Ignored mute from non focus peer");
  16684. return false;
  16685. }
  16686. var mute = $(iq).find('mute');
  16687. if (mute.length) {
  16688. var doMuteAudio = mute.text() === "true";
  16689. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  16690. XMPP.forceMuted = doMuteAudio;
  16691. }
  16692. return true;
  16693. },
  16694. eject: function (jid) {
  16695. // We're not the focus, so can't terminate
  16696. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  16697. this.connection.emuc.kick(jid);
  16698. }
  16699. });
  16700. }
  16701. },{"../../service/xmpp/XMPPEvents":174}],70:[function(require,module,exports){
  16702. /* global $, $iq, Strophe */
  16703. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16704. /**
  16705. * Ping every 20 sec
  16706. */
  16707. var PING_INTERVAL = 20000;
  16708. /**
  16709. * Ping timeout error after 15 sec of waiting.
  16710. */
  16711. var PING_TIMEOUT = 15000;
  16712. /**
  16713. * Will close the connection after 3 consecutive ping errors.
  16714. */
  16715. var PING_THRESHOLD = 3;
  16716. /**
  16717. * XEP-0199 ping plugin.
  16718. *
  16719. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  16720. */
  16721. module.exports = function (XMPP, eventEmitter) {
  16722. Strophe.addConnectionPlugin('ping', {
  16723. connection: null,
  16724. failedPings: 0,
  16725. /**
  16726. * Initializes the plugin. Method called by Strophe.
  16727. * @param connection Strophe connection instance.
  16728. */
  16729. init: function (connection) {
  16730. this.connection = connection;
  16731. Strophe.addNamespace('PING', "urn:xmpp:ping");
  16732. },
  16733. /**
  16734. * Sends "ping" to given <tt>jid</tt>
  16735. * @param jid the JID to which ping request will be sent.
  16736. * @param success callback called on success.
  16737. * @param error callback called on error.
  16738. * @param timeout ms how long are we going to wait for the response. On
  16739. * timeout <tt>error<//t> callback is called with undefined error
  16740. * argument.
  16741. */
  16742. ping: function (jid, success, error, timeout) {
  16743. var iq = $iq({type: 'get', to: jid});
  16744. iq.c('ping', {xmlns: Strophe.NS.PING});
  16745. this.connection.sendIQ(iq, success, error, timeout);
  16746. },
  16747. /**
  16748. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  16749. * @param jid the JID to be checked for ping support.
  16750. * @param callback function with boolean argument which will be
  16751. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  16752. */
  16753. hasPingSupport: function (jid, callback) {
  16754. this.connection.disco.info(
  16755. jid, null,
  16756. function (result) {
  16757. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  16758. callback(ping.length > 0);
  16759. },
  16760. function (error) {
  16761. console.error("Ping feature discovery error", error);
  16762. callback(false);
  16763. }
  16764. );
  16765. },
  16766. /**
  16767. * Starts to send ping in given interval to specified remote JID.
  16768. * This plugin supports only one such task and <tt>stopInterval</tt>
  16769. * must be called before starting a new one.
  16770. * @param remoteJid remote JID to which ping requests will be sent to.
  16771. * @param interval task interval in ms.
  16772. */
  16773. startInterval: function (remoteJid, interval) {
  16774. if (this.intervalId) {
  16775. console.error("Ping task scheduled already");
  16776. return;
  16777. }
  16778. if (!interval)
  16779. interval = PING_INTERVAL;
  16780. var self = this;
  16781. this.intervalId = window.setInterval(function () {
  16782. self.ping(remoteJid,
  16783. function (result) {
  16784. // Ping OK
  16785. self.failedPings = 0;
  16786. },
  16787. function (error) {
  16788. self.failedPings += 1;
  16789. console.error(
  16790. "Ping " + (error ? "error" : "timeout"), error);
  16791. if (self.failedPings >= PING_THRESHOLD) {
  16792. self.connection.disconnect();
  16793. }
  16794. }, PING_TIMEOUT);
  16795. }, interval);
  16796. console.info("XMPP pings will be sent every " + interval + " ms");
  16797. },
  16798. /**
  16799. * Stops current "ping" interval task.
  16800. */
  16801. stopInterval: function () {
  16802. if (this.intervalId) {
  16803. window.clearInterval(this.intervalId);
  16804. this.intervalId = null;
  16805. this.failedPings = 0;
  16806. console.info("Ping interval cleared");
  16807. }
  16808. }
  16809. });
  16810. };
  16811. },{"../../service/xmpp/XMPPEvents":174}],71:[function(require,module,exports){
  16812. /* jshint -W117 */
  16813. module.exports = function() {
  16814. Strophe.addConnectionPlugin('rayo',
  16815. {
  16816. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  16817. connection: null,
  16818. init: function (conn) {
  16819. this.connection = conn;
  16820. if (this.connection.disco) {
  16821. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  16822. }
  16823. this.connection.addHandler(
  16824. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  16825. },
  16826. onRayo: function (iq) {
  16827. console.info("Rayo IQ", iq);
  16828. },
  16829. dial: function (to, from, roomName, roomPass) {
  16830. var self = this;
  16831. var req = $iq(
  16832. {
  16833. type: 'set',
  16834. to: this.connection.emuc.focusMucJid
  16835. }
  16836. );
  16837. req.c('dial',
  16838. {
  16839. xmlns: this.RAYO_XMLNS,
  16840. to: to,
  16841. from: from
  16842. });
  16843. req.c('header',
  16844. {
  16845. name: 'JvbRoomName',
  16846. value: roomName
  16847. }).up();
  16848. if (roomPass !== null && roomPass.length) {
  16849. req.c('header',
  16850. {
  16851. name: 'JvbRoomPassword',
  16852. value: roomPass
  16853. }).up();
  16854. }
  16855. this.connection.sendIQ(
  16856. req,
  16857. function (result) {
  16858. console.info('Dial result ', result);
  16859. var resource = $(result).find('ref').attr('uri');
  16860. this.call_resource = resource.substr('xmpp:'.length);
  16861. console.info(
  16862. "Received call resource: " + this.call_resource);
  16863. },
  16864. function (error) {
  16865. console.info('Dial error ', error);
  16866. }
  16867. );
  16868. },
  16869. hang_up: function () {
  16870. if (!this.call_resource) {
  16871. console.warn("No call in progress");
  16872. return;
  16873. }
  16874. var self = this;
  16875. var req = $iq(
  16876. {
  16877. type: 'set',
  16878. to: this.call_resource
  16879. }
  16880. );
  16881. req.c('hangup',
  16882. {
  16883. xmlns: this.RAYO_XMLNS
  16884. });
  16885. this.connection.sendIQ(
  16886. req,
  16887. function (result) {
  16888. console.info('Hangup result ', result);
  16889. self.call_resource = null;
  16890. },
  16891. function (error) {
  16892. console.info('Hangup error ', error);
  16893. self.call_resource = null;
  16894. }
  16895. );
  16896. }
  16897. }
  16898. );
  16899. };
  16900. },{}],72:[function(require,module,exports){
  16901. /**
  16902. * Strophe logger implementation. Logs from level WARN and above.
  16903. */
  16904. module.exports = function () {
  16905. Strophe.log = function (level, msg) {
  16906. switch (level) {
  16907. case Strophe.LogLevel.WARN:
  16908. console.warn("Strophe: " + msg);
  16909. break;
  16910. case Strophe.LogLevel.ERROR:
  16911. case Strophe.LogLevel.FATAL:
  16912. console.error("Strophe: " + msg);
  16913. break;
  16914. }
  16915. };
  16916. Strophe.getStatusString = function (status) {
  16917. switch (status) {
  16918. case Strophe.Status.ERROR:
  16919. return "ERROR";
  16920. case Strophe.Status.CONNECTING:
  16921. return "CONNECTING";
  16922. case Strophe.Status.CONNFAIL:
  16923. return "CONNFAIL";
  16924. case Strophe.Status.AUTHENTICATING:
  16925. return "AUTHENTICATING";
  16926. case Strophe.Status.AUTHFAIL:
  16927. return "AUTHFAIL";
  16928. case Strophe.Status.CONNECTED:
  16929. return "CONNECTED";
  16930. case Strophe.Status.DISCONNECTED:
  16931. return "DISCONNECTED";
  16932. case Strophe.Status.DISCONNECTING:
  16933. return "DISCONNECTING";
  16934. case Strophe.Status.ATTACHED:
  16935. return "ATTACHED";
  16936. default:
  16937. return "unknown";
  16938. }
  16939. };
  16940. };
  16941. },{}],73:[function(require,module,exports){
  16942. /* global $, APP, config, Strophe*/
  16943. var Moderator = require("./moderator");
  16944. var EventEmitter = require("events");
  16945. var Recording = require("./recording");
  16946. var SDP = require("./SDP");
  16947. var Settings = require("../settings/Settings");
  16948. var Pako = require("pako");
  16949. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16950. var RTCEvents = require("../../service/RTC/RTCEvents");
  16951. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16952. var retry = require('retry');
  16953. var eventEmitter = new EventEmitter();
  16954. var connection = null;
  16955. var authenticatedUser = false;
  16956. function connect(jid, password) {
  16957. var faultTolerantConnect = retry.operation({
  16958. retries: 3
  16959. });
  16960. // fault tolerant connect
  16961. faultTolerantConnect.attempt(function () {
  16962. connection = XMPP.createConnection();
  16963. Moderator.setConnection(connection);
  16964. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16965. if (config.useIPv6) {
  16966. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16967. if (!connection.jingle.pc_constraints.optional)
  16968. connection.jingle.pc_constraints.optional = [];
  16969. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16970. }
  16971. // Include user info in MUC presence
  16972. var settings = Settings.getSettings();
  16973. if (settings.email) {
  16974. connection.emuc.addEmailToPresence(settings.email);
  16975. }
  16976. if (settings.uid) {
  16977. connection.emuc.addUserIdToPresence(settings.uid);
  16978. }
  16979. if (settings.displayName) {
  16980. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16981. }
  16982. // connection.connect() starts the connection process.
  16983. //
  16984. // As the connection process proceeds, the user supplied callback will
  16985. // be triggered multiple times with status updates. The callback should
  16986. // take two arguments - the status code and the error condition.
  16987. //
  16988. // The status code will be one of the values in the Strophe.Status
  16989. // constants. The error condition will be one of the conditions defined
  16990. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16991. //
  16992. // The Parameters wait, hold and route are optional and only relevant
  16993. // for BOSH connections. Please see XEP 124 for a more detailed
  16994. // explanation of the optional parameters.
  16995. //
  16996. // Connection status constants for use by the connection handler
  16997. // callback.
  16998. //
  16999. // Status.ERROR - An error has occurred (websockets specific)
  17000. // Status.CONNECTING - The connection is currently being made
  17001. // Status.CONNFAIL - The connection attempt failed
  17002. // Status.AUTHENTICATING - The connection is authenticating
  17003. // Status.AUTHFAIL - The authentication attempt failed
  17004. // Status.CONNECTED - The connection has succeeded
  17005. // Status.DISCONNECTED - The connection has been terminated
  17006. // Status.DISCONNECTING - The connection is currently being terminated
  17007. // Status.ATTACHED - The connection has been attached
  17008. var anonymousConnectionFailed = false;
  17009. var connectionFailed = false;
  17010. var lastErrorMsg;
  17011. connection.connect(jid, password, function (status, msg) {
  17012. console.log('Strophe status changed to',
  17013. Strophe.getStatusString(status), msg);
  17014. if (status === Strophe.Status.CONNECTED) {
  17015. if (config.useStunTurn) {
  17016. connection.jingle.getStunAndTurnCredentials();
  17017. }
  17018. console.info("My Jabber ID: " + connection.jid);
  17019. // Schedule ping ?
  17020. var pingJid = connection.domain;
  17021. connection.ping.hasPingSupport(
  17022. pingJid,
  17023. function (hasPing) {
  17024. if (hasPing)
  17025. connection.ping.startInterval(pingJid);
  17026. else
  17027. console.warn("Ping NOT supported by " + pingJid);
  17028. }
  17029. );
  17030. if (password)
  17031. authenticatedUser = true;
  17032. maybeDoJoin();
  17033. } else if (status === Strophe.Status.CONNFAIL) {
  17034. if (msg === 'x-strophe-bad-non-anon-jid') {
  17035. anonymousConnectionFailed = true;
  17036. } else {
  17037. connectionFailed = true;
  17038. }
  17039. lastErrorMsg = msg;
  17040. } else if (status === Strophe.Status.DISCONNECTED) {
  17041. // Stop ping interval
  17042. connection.ping.stopInterval();
  17043. if (anonymousConnectionFailed) {
  17044. // prompt user for username and password
  17045. XMPP.promptLogin();
  17046. } else {
  17047. // Strophe already has built-in HTTP/BOSH error handling and
  17048. // request retry logic. Requests are resent automatically
  17049. // until their error count reaches 5. Strophe.js disconnects
  17050. // if the error count is > 5. We are not replicating this
  17051. // here.
  17052. //
  17053. // The "problem" is that failed HTTP/BOSH requests don't
  17054. // trigger a callback with a status update, so when a
  17055. // callback with status Strophe.Status.DISCONNECTED arrives,
  17056. // we can't be sure if it's a graceful disconnect or if it's
  17057. // triggered by some HTTP/BOSH error.
  17058. //
  17059. // But that's a minor issue in Jitsi Meet as we never
  17060. // disconnect anyway, not even when the user closes the
  17061. // browser window (which is kind of wrong, but the point is
  17062. // that we should never ever get disconnected).
  17063. //
  17064. // On the other hand, failed connections due to XMPP layer
  17065. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  17066. //
  17067. // Here we implement retry logic for failed connections due
  17068. // to XMPP layer errors and we display an error to the user
  17069. // if we get disconnected from the XMPP server permanently.
  17070. // If the connection failed, retry.
  17071. if (connectionFailed &&
  17072. faultTolerantConnect.retry("connection-failed")) {
  17073. return;
  17074. }
  17075. // If we failed to connect to the XMPP server, fire an event
  17076. // to let all the interested module now about it.
  17077. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  17078. msg ? msg : lastErrorMsg);
  17079. }
  17080. } else if (status === Strophe.Status.AUTHFAIL) {
  17081. // wrong password or username, prompt user
  17082. XMPP.promptLogin();
  17083. }
  17084. });
  17085. });
  17086. }
  17087. function maybeDoJoin() {
  17088. if (connection && connection.connected &&
  17089. Strophe.getResourceFromJid(connection.jid) &&
  17090. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  17091. // .connected is true while connecting?
  17092. doJoin();
  17093. }
  17094. }
  17095. function doJoin() {
  17096. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  17097. }
  17098. function initStrophePlugins()
  17099. {
  17100. require("./strophe.emuc")(XMPP, eventEmitter);
  17101. require("./strophe.jingle")(XMPP, eventEmitter);
  17102. require("./strophe.moderate")(XMPP, eventEmitter);
  17103. require("./strophe.util")();
  17104. require("./strophe.ping")(XMPP, eventEmitter);
  17105. require("./strophe.rayo")();
  17106. require("./strophe.logger")();
  17107. }
  17108. /**
  17109. * If given <tt>localStream</tt> is video one this method will advertise it's
  17110. * video type in MUC presence.
  17111. * @param localStream new or modified <tt>LocalStream</tt>.
  17112. */
  17113. function broadcastLocalVideoType(localStream) {
  17114. if (localStream.videoType)
  17115. XMPP.addToPresence('videoType', localStream.videoType);
  17116. }
  17117. function registerListeners() {
  17118. APP.RTC.addStreamListener(
  17119. function (localStream) {
  17120. maybeDoJoin();
  17121. broadcastLocalVideoType(localStream);
  17122. },
  17123. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  17124. );
  17125. APP.RTC.addStreamListener(
  17126. broadcastLocalVideoType,
  17127. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  17128. );
  17129. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  17130. XMPP.addToPresence("devices", devices);
  17131. });
  17132. }
  17133. var unload = (function () {
  17134. var unloaded = false;
  17135. return function () {
  17136. if (unloaded) { return; }
  17137. unloaded = true;
  17138. if (connection && connection.connected) {
  17139. // ensure signout
  17140. $.ajax({
  17141. type: 'POST',
  17142. url: config.bosh,
  17143. async: false,
  17144. cache: false,
  17145. contentType: 'application/xml',
  17146. data: "<body rid='" +
  17147. (connection.rid || connection._proto.rid) +
  17148. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  17149. (connection.sid || connection._proto.sid) +
  17150. "' type='terminate'>" +
  17151. "<presence xmlns='jabber:client' type='unavailable'/>" +
  17152. "</body>",
  17153. success: function (data) {
  17154. console.log('signed out');
  17155. console.log(data);
  17156. },
  17157. error: function (XMLHttpRequest, textStatus, errorThrown) {
  17158. console.log('signout error',
  17159. textStatus + ' (' + errorThrown + ')');
  17160. }
  17161. });
  17162. }
  17163. XMPP.disposeConference(true);
  17164. };
  17165. })();
  17166. function setupEvents() {
  17167. // In recent versions of FF the 'beforeunload' event is not fired when the
  17168. // window or the tab is closed. It is only fired when we leave the page
  17169. // (change URL). If this participant doesn't unload properly, then it
  17170. // becomes a ghost for the rest of the participants that stay in the
  17171. // conference. Thankfully handling the 'unload' event in addition to the
  17172. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  17173. // method at least once.
  17174. //
  17175. // The 'unload' method can safely be run multiple times, it will actually do
  17176. // something only the first time that it's run, so we're don't have to worry
  17177. // about browsers that fire both events.
  17178. $(window).bind('beforeunload', unload);
  17179. $(window).bind('unload', unload);
  17180. }
  17181. var XMPP = {
  17182. getConnection: function(){ return connection; },
  17183. sessionTerminated: false,
  17184. /**
  17185. * XMPP connection status
  17186. */
  17187. Status: Strophe.Status,
  17188. /**
  17189. * Remembers if we were muted by the focus.
  17190. * @type {boolean}
  17191. */
  17192. forceMuted: false,
  17193. start: function () {
  17194. setupEvents();
  17195. initStrophePlugins();
  17196. registerListeners();
  17197. Moderator.init(this, eventEmitter);
  17198. Recording.init();
  17199. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  17200. // Force authenticated domain if room is appended with '?login=true'
  17201. if (config.hosts.anonymousdomain &&
  17202. window.location.search.indexOf("login=true") !== -1) {
  17203. configDomain = config.hosts.domain;
  17204. }
  17205. var jid = configDomain || window.location.hostname;
  17206. connect(jid, null);
  17207. },
  17208. createConnection: function () {
  17209. var bosh = config.bosh || '/http-bind';
  17210. return new Strophe.Connection(bosh);
  17211. },
  17212. getStatusString: function (status) {
  17213. return Strophe.getStatusString(status);
  17214. },
  17215. promptLogin: function () {
  17216. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  17217. },
  17218. joinRoom: function(roomName, useNicks, nick) {
  17219. var roomjid = roomName;
  17220. if (useNicks) {
  17221. if (nick) {
  17222. roomjid += '/' + nick;
  17223. } else {
  17224. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  17225. }
  17226. } else {
  17227. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  17228. if(!authenticatedUser)
  17229. tmpJid = tmpJid.substr(0, 8);
  17230. roomjid += '/' + tmpJid;
  17231. }
  17232. connection.emuc.doJoin(roomjid);
  17233. },
  17234. myJid: function () {
  17235. if(!connection)
  17236. return null;
  17237. return connection.emuc.myroomjid;
  17238. },
  17239. myResource: function () {
  17240. if(!connection || ! connection.emuc.myroomjid)
  17241. return null;
  17242. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  17243. },
  17244. disposeConference: function (onUnload) {
  17245. var handler = connection.jingle.activecall;
  17246. if (handler && handler.peerconnection) {
  17247. // FIXME: probably removing streams is not required and close() should
  17248. // be enough
  17249. if (APP.RTC.localAudio) {
  17250. handler.peerconnection.removeStream(
  17251. APP.RTC.localAudio.getOriginalStream(), onUnload);
  17252. }
  17253. if (APP.RTC.localVideo) {
  17254. handler.peerconnection.removeStream(
  17255. APP.RTC.localVideo.getOriginalStream(), onUnload);
  17256. }
  17257. handler.peerconnection.close();
  17258. }
  17259. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  17260. connection.jingle.activecall = null;
  17261. if (!onUnload) {
  17262. this.sessionTerminated = true;
  17263. connection.emuc.doLeave();
  17264. }
  17265. },
  17266. addListener: function(type, listener) {
  17267. eventEmitter.on(type, listener);
  17268. },
  17269. removeListener: function (type, listener) {
  17270. eventEmitter.removeListener(type, listener);
  17271. },
  17272. allocateConferenceFocus: function(roomName, callback) {
  17273. Moderator.allocateConferenceFocus(roomName, callback);
  17274. },
  17275. getLoginUrl: function (roomName, callback) {
  17276. Moderator.getLoginUrl(roomName, callback);
  17277. },
  17278. getPopupLoginUrl: function (roomName, callback) {
  17279. Moderator.getPopupLoginUrl(roomName, callback);
  17280. },
  17281. isModerator: function () {
  17282. return Moderator.isModerator();
  17283. },
  17284. isSipGatewayEnabled: function () {
  17285. return Moderator.isSipGatewayEnabled();
  17286. },
  17287. isExternalAuthEnabled: function () {
  17288. return Moderator.isExternalAuthEnabled();
  17289. },
  17290. isConferenceInProgress: function () {
  17291. return connection && connection.jingle.activecall &&
  17292. connection.jingle.activecall.peerconnection;
  17293. },
  17294. switchStreams: function (stream, oldStream, callback, isAudio) {
  17295. if (this.isConferenceInProgress()) {
  17296. // FIXME: will block switchInProgress on true value in case of exception
  17297. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  17298. } else {
  17299. // We are done immediately
  17300. console.warn("No conference handler or conference not started yet");
  17301. callback();
  17302. }
  17303. },
  17304. sendVideoInfoPresence: function (mute) {
  17305. if(!connection)
  17306. return;
  17307. connection.emuc.addVideoInfoToPresence(mute);
  17308. connection.emuc.sendPresence();
  17309. },
  17310. setVideoMute: function (mute, callback, options) {
  17311. if(!connection)
  17312. return;
  17313. var self = this;
  17314. var localCallback = function (mute) {
  17315. self.sendVideoInfoPresence(mute);
  17316. return callback(mute);
  17317. };
  17318. if(connection.jingle.activecall)
  17319. {
  17320. connection.jingle.activecall.setVideoMute(
  17321. mute, localCallback, options);
  17322. }
  17323. else {
  17324. localCallback(mute);
  17325. }
  17326. },
  17327. setAudioMute: function (mute, callback) {
  17328. if (!(connection && APP.RTC.localAudio)) {
  17329. return false;
  17330. }
  17331. if (this.forceMuted && !mute) {
  17332. console.info("Asking focus for unmute");
  17333. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  17334. // FIXME: wait for result before resetting muted status
  17335. this.forceMuted = false;
  17336. }
  17337. if (mute == APP.RTC.localAudio.isMuted()) {
  17338. // Nothing to do
  17339. return true;
  17340. }
  17341. APP.RTC.localAudio.setMute(mute);
  17342. this.sendAudioInfoPresence(mute, callback);
  17343. return true;
  17344. },
  17345. sendAudioInfoPresence: function(mute, callback) {
  17346. if(connection) {
  17347. connection.emuc.addAudioInfoToPresence(mute);
  17348. connection.emuc.sendPresence();
  17349. }
  17350. callback();
  17351. return true;
  17352. },
  17353. toggleRecording: function (tokenEmptyCallback,
  17354. recordingStateChangeCallback) {
  17355. Recording.toggleRecording(tokenEmptyCallback,
  17356. recordingStateChangeCallback, connection);
  17357. },
  17358. addToPresence: function (name, value, dontSend) {
  17359. switch (name) {
  17360. case "displayName":
  17361. connection.emuc.addDisplayNameToPresence(value);
  17362. break;
  17363. case "prezi":
  17364. connection.emuc.addPreziToPresence(value, 0);
  17365. break;
  17366. case "preziSlide":
  17367. connection.emuc.addCurrentSlideToPresence(value);
  17368. break;
  17369. case "connectionQuality":
  17370. connection.emuc.addConnectionInfoToPresence(value);
  17371. break;
  17372. case "email":
  17373. connection.emuc.addEmailToPresence(value);
  17374. break;
  17375. case "devices":
  17376. connection.emuc.addDevicesToPresence(value);
  17377. break;
  17378. case "videoType":
  17379. connection.emuc.addVideoTypeToPresence(value);
  17380. break;
  17381. case "startMuted":
  17382. if(!Moderator.isModerator())
  17383. return;
  17384. connection.emuc.addStartMutedToPresence(value[0],
  17385. value[1]);
  17386. break;
  17387. default :
  17388. console.log("Unknown tag for presence: " + name);
  17389. return;
  17390. }
  17391. if (!dontSend)
  17392. connection.emuc.sendPresence();
  17393. },
  17394. /**
  17395. * Sends 'data' as a log message to the focus. Returns true iff a message
  17396. * was sent.
  17397. * @param data
  17398. * @returns {boolean} true iff a message was sent.
  17399. */
  17400. sendLogs: function (data) {
  17401. if(!connection.emuc.focusMucJid)
  17402. return false;
  17403. var deflate = true;
  17404. var content = JSON.stringify(data);
  17405. if (deflate) {
  17406. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  17407. }
  17408. content = Base64.encode(content);
  17409. // XEP-0337-ish
  17410. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  17411. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  17412. id: 'PeerConnectionStats'});
  17413. message.c('message').t(content).up();
  17414. if (deflate) {
  17415. message.c('tag', {name: "deflated", value: "true"}).up();
  17416. }
  17417. message.up();
  17418. connection.send(message);
  17419. return true;
  17420. },
  17421. // Gets the logs from strophe.jingle.
  17422. getJingleLog: function () {
  17423. return connection.jingle ? connection.jingle.getLog() : {};
  17424. },
  17425. // Gets the logs from strophe.
  17426. getXmppLog: function () {
  17427. return connection.logger ? connection.logger.log : null;
  17428. },
  17429. getPrezi: function () {
  17430. return connection.emuc.getPrezi(this.myJid());
  17431. },
  17432. removePreziFromPresence: function () {
  17433. connection.emuc.removePreziFromPresence();
  17434. connection.emuc.sendPresence();
  17435. },
  17436. sendChatMessage: function (message, nickname) {
  17437. connection.emuc.sendMessage(message, nickname);
  17438. },
  17439. setSubject: function (topic) {
  17440. connection.emuc.setSubject(topic);
  17441. },
  17442. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  17443. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  17444. },
  17445. dial: function (to, from, roomName,roomPass) {
  17446. connection.rayo.dial(to, from, roomName,roomPass);
  17447. },
  17448. setMute: function (jid, mute) {
  17449. connection.moderate.setMute(jid, mute);
  17450. },
  17451. eject: function (jid) {
  17452. connection.moderate.eject(jid);
  17453. },
  17454. logout: function (callback) {
  17455. Moderator.logout(callback);
  17456. },
  17457. findJidFromResource: function (resource) {
  17458. return connection.emuc.findJidFromResource(resource);
  17459. },
  17460. getMembers: function () {
  17461. return connection.emuc.members;
  17462. },
  17463. getJidFromSSRC: function (ssrc) {
  17464. if (!this.isConferenceInProgress())
  17465. return null;
  17466. return connection.jingle.activecall.getSsrcOwner(ssrc);
  17467. },
  17468. // Returns true iff we have joined the MUC.
  17469. isMUCJoined: function () {
  17470. return connection.emuc.joined;
  17471. },
  17472. getSessions: function () {
  17473. return connection.jingle.sessions;
  17474. },
  17475. removeStream: function (stream) {
  17476. if (!this.isConferenceInProgress())
  17477. return;
  17478. connection.jingle.activecall.peerconnection.removeStream(stream);
  17479. }
  17480. };
  17481. module.exports = XMPP;
  17482. },{"../../service/RTC/RTCEvents":165,"../../service/RTC/StreamEventTypes":167,"../../service/xmpp/XMPPEvents":174,"../settings/Settings":51,"./SDP":60,"./moderator":64,"./recording":65,"./strophe.emuc":66,"./strophe.jingle":67,"./strophe.logger":68,"./strophe.moderate":69,"./strophe.ping":70,"./strophe.rayo":71,"./strophe.util":72,"events":1,"pako":77,"retry":93}],74:[function(require,module,exports){
  17483. (function (process){
  17484. /*!
  17485. * async
  17486. * https://github.com/caolan/async
  17487. *
  17488. * Copyright 2010-2014 Caolan McMahon
  17489. * Released under the MIT license
  17490. */
  17491. /*jshint onevar: false, indent:4 */
  17492. /*global setImmediate: false, setTimeout: false, console: false */
  17493. (function () {
  17494. var async = {};
  17495. // global on the server, window in the browser
  17496. var root, previous_async;
  17497. root = this;
  17498. if (root != null) {
  17499. previous_async = root.async;
  17500. }
  17501. async.noConflict = function () {
  17502. root.async = previous_async;
  17503. return async;
  17504. };
  17505. function only_once(fn) {
  17506. var called = false;
  17507. return function() {
  17508. if (called) throw new Error("Callback was already called.");
  17509. called = true;
  17510. fn.apply(root, arguments);
  17511. }
  17512. }
  17513. //// cross-browser compatiblity functions ////
  17514. var _toString = Object.prototype.toString;
  17515. var _isArray = Array.isArray || function (obj) {
  17516. return _toString.call(obj) === '[object Array]';
  17517. };
  17518. var _each = function (arr, iterator) {
  17519. if (arr.forEach) {
  17520. return arr.forEach(iterator);
  17521. }
  17522. for (var i = 0; i < arr.length; i += 1) {
  17523. iterator(arr[i], i, arr);
  17524. }
  17525. };
  17526. var _map = function (arr, iterator) {
  17527. if (arr.map) {
  17528. return arr.map(iterator);
  17529. }
  17530. var results = [];
  17531. _each(arr, function (x, i, a) {
  17532. results.push(iterator(x, i, a));
  17533. });
  17534. return results;
  17535. };
  17536. var _reduce = function (arr, iterator, memo) {
  17537. if (arr.reduce) {
  17538. return arr.reduce(iterator, memo);
  17539. }
  17540. _each(arr, function (x, i, a) {
  17541. memo = iterator(memo, x, i, a);
  17542. });
  17543. return memo;
  17544. };
  17545. var _keys = function (obj) {
  17546. if (Object.keys) {
  17547. return Object.keys(obj);
  17548. }
  17549. var keys = [];
  17550. for (var k in obj) {
  17551. if (obj.hasOwnProperty(k)) {
  17552. keys.push(k);
  17553. }
  17554. }
  17555. return keys;
  17556. };
  17557. //// exported async module functions ////
  17558. //// nextTick implementation with browser-compatible fallback ////
  17559. if (typeof process === 'undefined' || !(process.nextTick)) {
  17560. if (typeof setImmediate === 'function') {
  17561. async.nextTick = function (fn) {
  17562. // not a direct alias for IE10 compatibility
  17563. setImmediate(fn);
  17564. };
  17565. async.setImmediate = async.nextTick;
  17566. }
  17567. else {
  17568. async.nextTick = function (fn) {
  17569. setTimeout(fn, 0);
  17570. };
  17571. async.setImmediate = async.nextTick;
  17572. }
  17573. }
  17574. else {
  17575. async.nextTick = process.nextTick;
  17576. if (typeof setImmediate !== 'undefined') {
  17577. async.setImmediate = function (fn) {
  17578. // not a direct alias for IE10 compatibility
  17579. setImmediate(fn);
  17580. };
  17581. }
  17582. else {
  17583. async.setImmediate = async.nextTick;
  17584. }
  17585. }
  17586. async.each = function (arr, iterator, callback) {
  17587. callback = callback || function () {};
  17588. if (!arr.length) {
  17589. return callback();
  17590. }
  17591. var completed = 0;
  17592. _each(arr, function (x) {
  17593. iterator(x, only_once(done) );
  17594. });
  17595. function done(err) {
  17596. if (err) {
  17597. callback(err);
  17598. callback = function () {};
  17599. }
  17600. else {
  17601. completed += 1;
  17602. if (completed >= arr.length) {
  17603. callback();
  17604. }
  17605. }
  17606. }
  17607. };
  17608. async.forEach = async.each;
  17609. async.eachSeries = function (arr, iterator, callback) {
  17610. callback = callback || function () {};
  17611. if (!arr.length) {
  17612. return callback();
  17613. }
  17614. var completed = 0;
  17615. var iterate = function () {
  17616. iterator(arr[completed], function (err) {
  17617. if (err) {
  17618. callback(err);
  17619. callback = function () {};
  17620. }
  17621. else {
  17622. completed += 1;
  17623. if (completed >= arr.length) {
  17624. callback();
  17625. }
  17626. else {
  17627. iterate();
  17628. }
  17629. }
  17630. });
  17631. };
  17632. iterate();
  17633. };
  17634. async.forEachSeries = async.eachSeries;
  17635. async.eachLimit = function (arr, limit, iterator, callback) {
  17636. var fn = _eachLimit(limit);
  17637. fn.apply(null, [arr, iterator, callback]);
  17638. };
  17639. async.forEachLimit = async.eachLimit;
  17640. var _eachLimit = function (limit) {
  17641. return function (arr, iterator, callback) {
  17642. callback = callback || function () {};
  17643. if (!arr.length || limit <= 0) {
  17644. return callback();
  17645. }
  17646. var completed = 0;
  17647. var started = 0;
  17648. var running = 0;
  17649. (function replenish () {
  17650. if (completed >= arr.length) {
  17651. return callback();
  17652. }
  17653. while (running < limit && started < arr.length) {
  17654. started += 1;
  17655. running += 1;
  17656. iterator(arr[started - 1], function (err) {
  17657. if (err) {
  17658. callback(err);
  17659. callback = function () {};
  17660. }
  17661. else {
  17662. completed += 1;
  17663. running -= 1;
  17664. if (completed >= arr.length) {
  17665. callback();
  17666. }
  17667. else {
  17668. replenish();
  17669. }
  17670. }
  17671. });
  17672. }
  17673. })();
  17674. };
  17675. };
  17676. var doParallel = function (fn) {
  17677. return function () {
  17678. var args = Array.prototype.slice.call(arguments);
  17679. return fn.apply(null, [async.each].concat(args));
  17680. };
  17681. };
  17682. var doParallelLimit = function(limit, fn) {
  17683. return function () {
  17684. var args = Array.prototype.slice.call(arguments);
  17685. return fn.apply(null, [_eachLimit(limit)].concat(args));
  17686. };
  17687. };
  17688. var doSeries = function (fn) {
  17689. return function () {
  17690. var args = Array.prototype.slice.call(arguments);
  17691. return fn.apply(null, [async.eachSeries].concat(args));
  17692. };
  17693. };
  17694. var _asyncMap = function (eachfn, arr, iterator, callback) {
  17695. arr = _map(arr, function (x, i) {
  17696. return {index: i, value: x};
  17697. });
  17698. if (!callback) {
  17699. eachfn(arr, function (x, callback) {
  17700. iterator(x.value, function (err) {
  17701. callback(err);
  17702. });
  17703. });
  17704. } else {
  17705. var results = [];
  17706. eachfn(arr, function (x, callback) {
  17707. iterator(x.value, function (err, v) {
  17708. results[x.index] = v;
  17709. callback(err);
  17710. });
  17711. }, function (err) {
  17712. callback(err, results);
  17713. });
  17714. }
  17715. };
  17716. async.map = doParallel(_asyncMap);
  17717. async.mapSeries = doSeries(_asyncMap);
  17718. async.mapLimit = function (arr, limit, iterator, callback) {
  17719. return _mapLimit(limit)(arr, iterator, callback);
  17720. };
  17721. var _mapLimit = function(limit) {
  17722. return doParallelLimit(limit, _asyncMap);
  17723. };
  17724. // reduce only has a series version, as doing reduce in parallel won't
  17725. // work in many situations.
  17726. async.reduce = function (arr, memo, iterator, callback) {
  17727. async.eachSeries(arr, function (x, callback) {
  17728. iterator(memo, x, function (err, v) {
  17729. memo = v;
  17730. callback(err);
  17731. });
  17732. }, function (err) {
  17733. callback(err, memo);
  17734. });
  17735. };
  17736. // inject alias
  17737. async.inject = async.reduce;
  17738. // foldl alias
  17739. async.foldl = async.reduce;
  17740. async.reduceRight = function (arr, memo, iterator, callback) {
  17741. var reversed = _map(arr, function (x) {
  17742. return x;
  17743. }).reverse();
  17744. async.reduce(reversed, memo, iterator, callback);
  17745. };
  17746. // foldr alias
  17747. async.foldr = async.reduceRight;
  17748. var _filter = function (eachfn, arr, iterator, callback) {
  17749. var results = [];
  17750. arr = _map(arr, function (x, i) {
  17751. return {index: i, value: x};
  17752. });
  17753. eachfn(arr, function (x, callback) {
  17754. iterator(x.value, function (v) {
  17755. if (v) {
  17756. results.push(x);
  17757. }
  17758. callback();
  17759. });
  17760. }, function (err) {
  17761. callback(_map(results.sort(function (a, b) {
  17762. return a.index - b.index;
  17763. }), function (x) {
  17764. return x.value;
  17765. }));
  17766. });
  17767. };
  17768. async.filter = doParallel(_filter);
  17769. async.filterSeries = doSeries(_filter);
  17770. // select alias
  17771. async.select = async.filter;
  17772. async.selectSeries = async.filterSeries;
  17773. var _reject = function (eachfn, arr, iterator, callback) {
  17774. var results = [];
  17775. arr = _map(arr, function (x, i) {
  17776. return {index: i, value: x};
  17777. });
  17778. eachfn(arr, function (x, callback) {
  17779. iterator(x.value, function (v) {
  17780. if (!v) {
  17781. results.push(x);
  17782. }
  17783. callback();
  17784. });
  17785. }, function (err) {
  17786. callback(_map(results.sort(function (a, b) {
  17787. return a.index - b.index;
  17788. }), function (x) {
  17789. return x.value;
  17790. }));
  17791. });
  17792. };
  17793. async.reject = doParallel(_reject);
  17794. async.rejectSeries = doSeries(_reject);
  17795. var _detect = function (eachfn, arr, iterator, main_callback) {
  17796. eachfn(arr, function (x, callback) {
  17797. iterator(x, function (result) {
  17798. if (result) {
  17799. main_callback(x);
  17800. main_callback = function () {};
  17801. }
  17802. else {
  17803. callback();
  17804. }
  17805. });
  17806. }, function (err) {
  17807. main_callback();
  17808. });
  17809. };
  17810. async.detect = doParallel(_detect);
  17811. async.detectSeries = doSeries(_detect);
  17812. async.some = function (arr, iterator, main_callback) {
  17813. async.each(arr, function (x, callback) {
  17814. iterator(x, function (v) {
  17815. if (v) {
  17816. main_callback(true);
  17817. main_callback = function () {};
  17818. }
  17819. callback();
  17820. });
  17821. }, function (err) {
  17822. main_callback(false);
  17823. });
  17824. };
  17825. // any alias
  17826. async.any = async.some;
  17827. async.every = function (arr, iterator, main_callback) {
  17828. async.each(arr, function (x, callback) {
  17829. iterator(x, function (v) {
  17830. if (!v) {
  17831. main_callback(false);
  17832. main_callback = function () {};
  17833. }
  17834. callback();
  17835. });
  17836. }, function (err) {
  17837. main_callback(true);
  17838. });
  17839. };
  17840. // all alias
  17841. async.all = async.every;
  17842. async.sortBy = function (arr, iterator, callback) {
  17843. async.map(arr, function (x, callback) {
  17844. iterator(x, function (err, criteria) {
  17845. if (err) {
  17846. callback(err);
  17847. }
  17848. else {
  17849. callback(null, {value: x, criteria: criteria});
  17850. }
  17851. });
  17852. }, function (err, results) {
  17853. if (err) {
  17854. return callback(err);
  17855. }
  17856. else {
  17857. var fn = function (left, right) {
  17858. var a = left.criteria, b = right.criteria;
  17859. return a < b ? -1 : a > b ? 1 : 0;
  17860. };
  17861. callback(null, _map(results.sort(fn), function (x) {
  17862. return x.value;
  17863. }));
  17864. }
  17865. });
  17866. };
  17867. async.auto = function (tasks, callback) {
  17868. callback = callback || function () {};
  17869. var keys = _keys(tasks);
  17870. var remainingTasks = keys.length
  17871. if (!remainingTasks) {
  17872. return callback();
  17873. }
  17874. var results = {};
  17875. var listeners = [];
  17876. var addListener = function (fn) {
  17877. listeners.unshift(fn);
  17878. };
  17879. var removeListener = function (fn) {
  17880. for (var i = 0; i < listeners.length; i += 1) {
  17881. if (listeners[i] === fn) {
  17882. listeners.splice(i, 1);
  17883. return;
  17884. }
  17885. }
  17886. };
  17887. var taskComplete = function () {
  17888. remainingTasks--
  17889. _each(listeners.slice(0), function (fn) {
  17890. fn();
  17891. });
  17892. };
  17893. addListener(function () {
  17894. if (!remainingTasks) {
  17895. var theCallback = callback;
  17896. // prevent final callback from calling itself if it errors
  17897. callback = function () {};
  17898. theCallback(null, results);
  17899. }
  17900. });
  17901. _each(keys, function (k) {
  17902. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17903. var taskCallback = function (err) {
  17904. var args = Array.prototype.slice.call(arguments, 1);
  17905. if (args.length <= 1) {
  17906. args = args[0];
  17907. }
  17908. if (err) {
  17909. var safeResults = {};
  17910. _each(_keys(results), function(rkey) {
  17911. safeResults[rkey] = results[rkey];
  17912. });
  17913. safeResults[k] = args;
  17914. callback(err, safeResults);
  17915. // stop subsequent errors hitting callback multiple times
  17916. callback = function () {};
  17917. }
  17918. else {
  17919. results[k] = args;
  17920. async.setImmediate(taskComplete);
  17921. }
  17922. };
  17923. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17924. var ready = function () {
  17925. return _reduce(requires, function (a, x) {
  17926. return (a && results.hasOwnProperty(x));
  17927. }, true) && !results.hasOwnProperty(k);
  17928. };
  17929. if (ready()) {
  17930. task[task.length - 1](taskCallback, results);
  17931. }
  17932. else {
  17933. var listener = function () {
  17934. if (ready()) {
  17935. removeListener(listener);
  17936. task[task.length - 1](taskCallback, results);
  17937. }
  17938. };
  17939. addListener(listener);
  17940. }
  17941. });
  17942. };
  17943. async.retry = function(times, task, callback) {
  17944. var DEFAULT_TIMES = 5;
  17945. var attempts = [];
  17946. // Use defaults if times not passed
  17947. if (typeof times === 'function') {
  17948. callback = task;
  17949. task = times;
  17950. times = DEFAULT_TIMES;
  17951. }
  17952. // Make sure times is a number
  17953. times = parseInt(times, 10) || DEFAULT_TIMES;
  17954. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17955. var retryAttempt = function(task, finalAttempt) {
  17956. return function(seriesCallback) {
  17957. task(function(err, result){
  17958. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17959. }, wrappedResults);
  17960. };
  17961. };
  17962. while (times) {
  17963. attempts.push(retryAttempt(task, !(times-=1)));
  17964. }
  17965. async.series(attempts, function(done, data){
  17966. data = data[data.length - 1];
  17967. (wrappedCallback || callback)(data.err, data.result);
  17968. });
  17969. }
  17970. // If a callback is passed, run this as a controll flow
  17971. return callback ? wrappedTask() : wrappedTask
  17972. };
  17973. async.waterfall = function (tasks, callback) {
  17974. callback = callback || function () {};
  17975. if (!_isArray(tasks)) {
  17976. var err = new Error('First argument to waterfall must be an array of functions');
  17977. return callback(err);
  17978. }
  17979. if (!tasks.length) {
  17980. return callback();
  17981. }
  17982. var wrapIterator = function (iterator) {
  17983. return function (err) {
  17984. if (err) {
  17985. callback.apply(null, arguments);
  17986. callback = function () {};
  17987. }
  17988. else {
  17989. var args = Array.prototype.slice.call(arguments, 1);
  17990. var next = iterator.next();
  17991. if (next) {
  17992. args.push(wrapIterator(next));
  17993. }
  17994. else {
  17995. args.push(callback);
  17996. }
  17997. async.setImmediate(function () {
  17998. iterator.apply(null, args);
  17999. });
  18000. }
  18001. };
  18002. };
  18003. wrapIterator(async.iterator(tasks))();
  18004. };
  18005. var _parallel = function(eachfn, tasks, callback) {
  18006. callback = callback || function () {};
  18007. if (_isArray(tasks)) {
  18008. eachfn.map(tasks, function (fn, callback) {
  18009. if (fn) {
  18010. fn(function (err) {
  18011. var args = Array.prototype.slice.call(arguments, 1);
  18012. if (args.length <= 1) {
  18013. args = args[0];
  18014. }
  18015. callback.call(null, err, args);
  18016. });
  18017. }
  18018. }, callback);
  18019. }
  18020. else {
  18021. var results = {};
  18022. eachfn.each(_keys(tasks), function (k, callback) {
  18023. tasks[k](function (err) {
  18024. var args = Array.prototype.slice.call(arguments, 1);
  18025. if (args.length <= 1) {
  18026. args = args[0];
  18027. }
  18028. results[k] = args;
  18029. callback(err);
  18030. });
  18031. }, function (err) {
  18032. callback(err, results);
  18033. });
  18034. }
  18035. };
  18036. async.parallel = function (tasks, callback) {
  18037. _parallel({ map: async.map, each: async.each }, tasks, callback);
  18038. };
  18039. async.parallelLimit = function(tasks, limit, callback) {
  18040. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  18041. };
  18042. async.series = function (tasks, callback) {
  18043. callback = callback || function () {};
  18044. if (_isArray(tasks)) {
  18045. async.mapSeries(tasks, function (fn, callback) {
  18046. if (fn) {
  18047. fn(function (err) {
  18048. var args = Array.prototype.slice.call(arguments, 1);
  18049. if (args.length <= 1) {
  18050. args = args[0];
  18051. }
  18052. callback.call(null, err, args);
  18053. });
  18054. }
  18055. }, callback);
  18056. }
  18057. else {
  18058. var results = {};
  18059. async.eachSeries(_keys(tasks), function (k, callback) {
  18060. tasks[k](function (err) {
  18061. var args = Array.prototype.slice.call(arguments, 1);
  18062. if (args.length <= 1) {
  18063. args = args[0];
  18064. }
  18065. results[k] = args;
  18066. callback(err);
  18067. });
  18068. }, function (err) {
  18069. callback(err, results);
  18070. });
  18071. }
  18072. };
  18073. async.iterator = function (tasks) {
  18074. var makeCallback = function (index) {
  18075. var fn = function () {
  18076. if (tasks.length) {
  18077. tasks[index].apply(null, arguments);
  18078. }
  18079. return fn.next();
  18080. };
  18081. fn.next = function () {
  18082. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  18083. };
  18084. return fn;
  18085. };
  18086. return makeCallback(0);
  18087. };
  18088. async.apply = function (fn) {
  18089. var args = Array.prototype.slice.call(arguments, 1);
  18090. return function () {
  18091. return fn.apply(
  18092. null, args.concat(Array.prototype.slice.call(arguments))
  18093. );
  18094. };
  18095. };
  18096. var _concat = function (eachfn, arr, fn, callback) {
  18097. var r = [];
  18098. eachfn(arr, function (x, cb) {
  18099. fn(x, function (err, y) {
  18100. r = r.concat(y || []);
  18101. cb(err);
  18102. });
  18103. }, function (err) {
  18104. callback(err, r);
  18105. });
  18106. };
  18107. async.concat = doParallel(_concat);
  18108. async.concatSeries = doSeries(_concat);
  18109. async.whilst = function (test, iterator, callback) {
  18110. if (test()) {
  18111. iterator(function (err) {
  18112. if (err) {
  18113. return callback(err);
  18114. }
  18115. async.whilst(test, iterator, callback);
  18116. });
  18117. }
  18118. else {
  18119. callback();
  18120. }
  18121. };
  18122. async.doWhilst = function (iterator, test, callback) {
  18123. iterator(function (err) {
  18124. if (err) {
  18125. return callback(err);
  18126. }
  18127. var args = Array.prototype.slice.call(arguments, 1);
  18128. if (test.apply(null, args)) {
  18129. async.doWhilst(iterator, test, callback);
  18130. }
  18131. else {
  18132. callback();
  18133. }
  18134. });
  18135. };
  18136. async.until = function (test, iterator, callback) {
  18137. if (!test()) {
  18138. iterator(function (err) {
  18139. if (err) {
  18140. return callback(err);
  18141. }
  18142. async.until(test, iterator, callback);
  18143. });
  18144. }
  18145. else {
  18146. callback();
  18147. }
  18148. };
  18149. async.doUntil = function (iterator, test, callback) {
  18150. iterator(function (err) {
  18151. if (err) {
  18152. return callback(err);
  18153. }
  18154. var args = Array.prototype.slice.call(arguments, 1);
  18155. if (!test.apply(null, args)) {
  18156. async.doUntil(iterator, test, callback);
  18157. }
  18158. else {
  18159. callback();
  18160. }
  18161. });
  18162. };
  18163. async.queue = function (worker, concurrency) {
  18164. if (concurrency === undefined) {
  18165. concurrency = 1;
  18166. }
  18167. function _insert(q, data, pos, callback) {
  18168. if (!q.started){
  18169. q.started = true;
  18170. }
  18171. if (!_isArray(data)) {
  18172. data = [data];
  18173. }
  18174. if(data.length == 0) {
  18175. // call drain immediately if there are no tasks
  18176. return async.setImmediate(function() {
  18177. if (q.drain) {
  18178. q.drain();
  18179. }
  18180. });
  18181. }
  18182. _each(data, function(task) {
  18183. var item = {
  18184. data: task,
  18185. callback: typeof callback === 'function' ? callback : null
  18186. };
  18187. if (pos) {
  18188. q.tasks.unshift(item);
  18189. } else {
  18190. q.tasks.push(item);
  18191. }
  18192. if (q.saturated && q.tasks.length === q.concurrency) {
  18193. q.saturated();
  18194. }
  18195. async.setImmediate(q.process);
  18196. });
  18197. }
  18198. var workers = 0;
  18199. var q = {
  18200. tasks: [],
  18201. concurrency: concurrency,
  18202. saturated: null,
  18203. empty: null,
  18204. drain: null,
  18205. started: false,
  18206. paused: false,
  18207. push: function (data, callback) {
  18208. _insert(q, data, false, callback);
  18209. },
  18210. kill: function () {
  18211. q.drain = null;
  18212. q.tasks = [];
  18213. },
  18214. unshift: function (data, callback) {
  18215. _insert(q, data, true, callback);
  18216. },
  18217. process: function () {
  18218. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  18219. var task = q.tasks.shift();
  18220. if (q.empty && q.tasks.length === 0) {
  18221. q.empty();
  18222. }
  18223. workers += 1;
  18224. var next = function () {
  18225. workers -= 1;
  18226. if (task.callback) {
  18227. task.callback.apply(task, arguments);
  18228. }
  18229. if (q.drain && q.tasks.length + workers === 0) {
  18230. q.drain();
  18231. }
  18232. q.process();
  18233. };
  18234. var cb = only_once(next);
  18235. worker(task.data, cb);
  18236. }
  18237. },
  18238. length: function () {
  18239. return q.tasks.length;
  18240. },
  18241. running: function () {
  18242. return workers;
  18243. },
  18244. idle: function() {
  18245. return q.tasks.length + workers === 0;
  18246. },
  18247. pause: function () {
  18248. if (q.paused === true) { return; }
  18249. q.paused = true;
  18250. q.process();
  18251. },
  18252. resume: function () {
  18253. if (q.paused === false) { return; }
  18254. q.paused = false;
  18255. q.process();
  18256. }
  18257. };
  18258. return q;
  18259. };
  18260. async.priorityQueue = function (worker, concurrency) {
  18261. function _compareTasks(a, b){
  18262. return a.priority - b.priority;
  18263. };
  18264. function _binarySearch(sequence, item, compare) {
  18265. var beg = -1,
  18266. end = sequence.length - 1;
  18267. while (beg < end) {
  18268. var mid = beg + ((end - beg + 1) >>> 1);
  18269. if (compare(item, sequence[mid]) >= 0) {
  18270. beg = mid;
  18271. } else {
  18272. end = mid - 1;
  18273. }
  18274. }
  18275. return beg;
  18276. }
  18277. function _insert(q, data, priority, callback) {
  18278. if (!q.started){
  18279. q.started = true;
  18280. }
  18281. if (!_isArray(data)) {
  18282. data = [data];
  18283. }
  18284. if(data.length == 0) {
  18285. // call drain immediately if there are no tasks
  18286. return async.setImmediate(function() {
  18287. if (q.drain) {
  18288. q.drain();
  18289. }
  18290. });
  18291. }
  18292. _each(data, function(task) {
  18293. var item = {
  18294. data: task,
  18295. priority: priority,
  18296. callback: typeof callback === 'function' ? callback : null
  18297. };
  18298. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  18299. if (q.saturated && q.tasks.length === q.concurrency) {
  18300. q.saturated();
  18301. }
  18302. async.setImmediate(q.process);
  18303. });
  18304. }
  18305. // Start with a normal queue
  18306. var q = async.queue(worker, concurrency);
  18307. // Override push to accept second parameter representing priority
  18308. q.push = function (data, priority, callback) {
  18309. _insert(q, data, priority, callback);
  18310. };
  18311. // Remove unshift function
  18312. delete q.unshift;
  18313. return q;
  18314. };
  18315. async.cargo = function (worker, payload) {
  18316. var working = false,
  18317. tasks = [];
  18318. var cargo = {
  18319. tasks: tasks,
  18320. payload: payload,
  18321. saturated: null,
  18322. empty: null,
  18323. drain: null,
  18324. drained: true,
  18325. push: function (data, callback) {
  18326. if (!_isArray(data)) {
  18327. data = [data];
  18328. }
  18329. _each(data, function(task) {
  18330. tasks.push({
  18331. data: task,
  18332. callback: typeof callback === 'function' ? callback : null
  18333. });
  18334. cargo.drained = false;
  18335. if (cargo.saturated && tasks.length === payload) {
  18336. cargo.saturated();
  18337. }
  18338. });
  18339. async.setImmediate(cargo.process);
  18340. },
  18341. process: function process() {
  18342. if (working) return;
  18343. if (tasks.length === 0) {
  18344. if(cargo.drain && !cargo.drained) cargo.drain();
  18345. cargo.drained = true;
  18346. return;
  18347. }
  18348. var ts = typeof payload === 'number'
  18349. ? tasks.splice(0, payload)
  18350. : tasks.splice(0, tasks.length);
  18351. var ds = _map(ts, function (task) {
  18352. return task.data;
  18353. });
  18354. if(cargo.empty) cargo.empty();
  18355. working = true;
  18356. worker(ds, function () {
  18357. working = false;
  18358. var args = arguments;
  18359. _each(ts, function (data) {
  18360. if (data.callback) {
  18361. data.callback.apply(null, args);
  18362. }
  18363. });
  18364. process();
  18365. });
  18366. },
  18367. length: function () {
  18368. return tasks.length;
  18369. },
  18370. running: function () {
  18371. return working;
  18372. }
  18373. };
  18374. return cargo;
  18375. };
  18376. var _console_fn = function (name) {
  18377. return function (fn) {
  18378. var args = Array.prototype.slice.call(arguments, 1);
  18379. fn.apply(null, args.concat([function (err) {
  18380. var args = Array.prototype.slice.call(arguments, 1);
  18381. if (typeof console !== 'undefined') {
  18382. if (err) {
  18383. if (console.error) {
  18384. console.error(err);
  18385. }
  18386. }
  18387. else if (console[name]) {
  18388. _each(args, function (x) {
  18389. console[name](x);
  18390. });
  18391. }
  18392. }
  18393. }]));
  18394. };
  18395. };
  18396. async.log = _console_fn('log');
  18397. async.dir = _console_fn('dir');
  18398. /*async.info = _console_fn('info');
  18399. async.warn = _console_fn('warn');
  18400. async.error = _console_fn('error');*/
  18401. async.memoize = function (fn, hasher) {
  18402. var memo = {};
  18403. var queues = {};
  18404. hasher = hasher || function (x) {
  18405. return x;
  18406. };
  18407. var memoized = function () {
  18408. var args = Array.prototype.slice.call(arguments);
  18409. var callback = args.pop();
  18410. var key = hasher.apply(null, args);
  18411. if (key in memo) {
  18412. async.nextTick(function () {
  18413. callback.apply(null, memo[key]);
  18414. });
  18415. }
  18416. else if (key in queues) {
  18417. queues[key].push(callback);
  18418. }
  18419. else {
  18420. queues[key] = [callback];
  18421. fn.apply(null, args.concat([function () {
  18422. memo[key] = arguments;
  18423. var q = queues[key];
  18424. delete queues[key];
  18425. for (var i = 0, l = q.length; i < l; i++) {
  18426. q[i].apply(null, arguments);
  18427. }
  18428. }]));
  18429. }
  18430. };
  18431. memoized.memo = memo;
  18432. memoized.unmemoized = fn;
  18433. return memoized;
  18434. };
  18435. async.unmemoize = function (fn) {
  18436. return function () {
  18437. return (fn.unmemoized || fn).apply(null, arguments);
  18438. };
  18439. };
  18440. async.times = function (count, iterator, callback) {
  18441. var counter = [];
  18442. for (var i = 0; i < count; i++) {
  18443. counter.push(i);
  18444. }
  18445. return async.map(counter, iterator, callback);
  18446. };
  18447. async.timesSeries = function (count, iterator, callback) {
  18448. var counter = [];
  18449. for (var i = 0; i < count; i++) {
  18450. counter.push(i);
  18451. }
  18452. return async.mapSeries(counter, iterator, callback);
  18453. };
  18454. async.seq = function (/* functions... */) {
  18455. var fns = arguments;
  18456. return function () {
  18457. var that = this;
  18458. var args = Array.prototype.slice.call(arguments);
  18459. var callback = args.pop();
  18460. async.reduce(fns, args, function (newargs, fn, cb) {
  18461. fn.apply(that, newargs.concat([function () {
  18462. var err = arguments[0];
  18463. var nextargs = Array.prototype.slice.call(arguments, 1);
  18464. cb(err, nextargs);
  18465. }]))
  18466. },
  18467. function (err, results) {
  18468. callback.apply(that, [err].concat(results));
  18469. });
  18470. };
  18471. };
  18472. async.compose = function (/* functions... */) {
  18473. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  18474. };
  18475. var _applyEach = function (eachfn, fns /*args...*/) {
  18476. var go = function () {
  18477. var that = this;
  18478. var args = Array.prototype.slice.call(arguments);
  18479. var callback = args.pop();
  18480. return eachfn(fns, function (fn, cb) {
  18481. fn.apply(that, args.concat([cb]));
  18482. },
  18483. callback);
  18484. };
  18485. if (arguments.length > 2) {
  18486. var args = Array.prototype.slice.call(arguments, 2);
  18487. return go.apply(this, args);
  18488. }
  18489. else {
  18490. return go;
  18491. }
  18492. };
  18493. async.applyEach = doParallel(_applyEach);
  18494. async.applyEachSeries = doSeries(_applyEach);
  18495. async.forever = function (fn, callback) {
  18496. function next(err) {
  18497. if (err) {
  18498. if (callback) {
  18499. return callback(err);
  18500. }
  18501. throw err;
  18502. }
  18503. fn(next);
  18504. }
  18505. next();
  18506. };
  18507. // Node.js
  18508. if (typeof module !== 'undefined' && module.exports) {
  18509. module.exports = async;
  18510. }
  18511. // AMD / RequireJS
  18512. else if (typeof define !== 'undefined' && define.amd) {
  18513. define([], function () {
  18514. return async;
  18515. });
  18516. }
  18517. // included directly via <script> tag
  18518. else {
  18519. root.async = async;
  18520. }
  18521. }());
  18522. }).call(this,require('_process'))
  18523. },{"_process":2}],75:[function(require,module,exports){
  18524. // i18next, v1.7.7
  18525. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  18526. // Distributed under MIT license
  18527. // http://i18next.com
  18528. (function() {
  18529. // add indexOf to non ECMA-262 standard compliant browsers
  18530. if (!Array.prototype.indexOf) {
  18531. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  18532. "use strict";
  18533. if (this == null) {
  18534. throw new TypeError();
  18535. }
  18536. var t = Object(this);
  18537. var len = t.length >>> 0;
  18538. if (len === 0) {
  18539. return -1;
  18540. }
  18541. var n = 0;
  18542. if (arguments.length > 0) {
  18543. n = Number(arguments[1]);
  18544. if (n != n) { // shortcut for verifying if it's NaN
  18545. n = 0;
  18546. } else if (n != 0 && n != Infinity && n != -Infinity) {
  18547. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  18548. }
  18549. }
  18550. if (n >= len) {
  18551. return -1;
  18552. }
  18553. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  18554. for (; k < len; k++) {
  18555. if (k in t && t[k] === searchElement) {
  18556. return k;
  18557. }
  18558. }
  18559. return -1;
  18560. }
  18561. }
  18562. // add lastIndexOf to non ECMA-262 standard compliant browsers
  18563. if (!Array.prototype.lastIndexOf) {
  18564. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  18565. "use strict";
  18566. if (this == null) {
  18567. throw new TypeError();
  18568. }
  18569. var t = Object(this);
  18570. var len = t.length >>> 0;
  18571. if (len === 0) {
  18572. return -1;
  18573. }
  18574. var n = len;
  18575. if (arguments.length > 1) {
  18576. n = Number(arguments[1]);
  18577. if (n != n) {
  18578. n = 0;
  18579. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  18580. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  18581. }
  18582. }
  18583. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  18584. for (; k >= 0; k--) {
  18585. if (k in t && t[k] === searchElement) {
  18586. return k;
  18587. }
  18588. }
  18589. return -1;
  18590. };
  18591. }
  18592. // Add string trim for IE8.
  18593. if (typeof String.prototype.trim !== 'function') {
  18594. String.prototype.trim = function() {
  18595. return this.replace(/^\s+|\s+$/g, '');
  18596. }
  18597. }
  18598. var root = this
  18599. , $ = root.jQuery || root.Zepto
  18600. , i18n = {}
  18601. , resStore = {}
  18602. , currentLng
  18603. , replacementCounter = 0
  18604. , languages = []
  18605. , initialized = false
  18606. , sync = {};
  18607. // Export the i18next object for **CommonJS**.
  18608. // If we're not in CommonJS, add `i18n` to the
  18609. // global object or to jquery.
  18610. if (typeof module !== 'undefined' && module.exports) {
  18611. if (!$) {
  18612. try {
  18613. $ = require('jquery');
  18614. } catch(e) {
  18615. // just ignore
  18616. }
  18617. }
  18618. if ($) {
  18619. $.i18n = $.i18n || i18n;
  18620. }
  18621. module.exports = i18n;
  18622. } else {
  18623. if ($) {
  18624. $.i18n = $.i18n || i18n;
  18625. }
  18626. root.i18n = root.i18n || i18n;
  18627. }
  18628. sync = {
  18629. load: function(lngs, options, cb) {
  18630. if (options.useLocalStorage) {
  18631. sync._loadLocal(lngs, options, function(err, store) {
  18632. var missingLngs = [];
  18633. for (var i = 0, len = lngs.length; i < len; i++) {
  18634. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  18635. }
  18636. if (missingLngs.length > 0) {
  18637. sync._fetch(missingLngs, options, function(err, fetched) {
  18638. f.extend(store, fetched);
  18639. sync._storeLocal(fetched);
  18640. cb(null, store);
  18641. });
  18642. } else {
  18643. cb(null, store);
  18644. }
  18645. });
  18646. } else {
  18647. sync._fetch(lngs, options, function(err, store){
  18648. cb(null, store);
  18649. });
  18650. }
  18651. },
  18652. _loadLocal: function(lngs, options, cb) {
  18653. var store = {}
  18654. , nowMS = new Date().getTime();
  18655. if(window.localStorage) {
  18656. var todo = lngs.length;
  18657. f.each(lngs, function(key, lng) {
  18658. var local = window.localStorage.getItem('res_' + lng);
  18659. if (local) {
  18660. local = JSON.parse(local);
  18661. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  18662. store[lng] = local;
  18663. }
  18664. }
  18665. todo--; // wait for all done befor callback
  18666. if (todo === 0) cb(null, store);
  18667. });
  18668. }
  18669. },
  18670. _storeLocal: function(store) {
  18671. if(window.localStorage) {
  18672. for (var m in store) {
  18673. store[m].i18nStamp = new Date().getTime();
  18674. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  18675. }
  18676. }
  18677. return;
  18678. },
  18679. _fetch: function(lngs, options, cb) {
  18680. var ns = options.ns
  18681. , store = {};
  18682. if (!options.dynamicLoad) {
  18683. var todo = ns.namespaces.length * lngs.length
  18684. , errors;
  18685. // load each file individual
  18686. f.each(ns.namespaces, function(nsIndex, nsValue) {
  18687. f.each(lngs, function(lngIndex, lngValue) {
  18688. // Call this once our translation has returned.
  18689. var loadComplete = function(err, data) {
  18690. if (err) {
  18691. errors = errors || [];
  18692. errors.push(err);
  18693. }
  18694. store[lngValue] = store[lngValue] || {};
  18695. store[lngValue][nsValue] = data;
  18696. todo--; // wait for all done befor callback
  18697. if (todo === 0) cb(errors, store);
  18698. };
  18699. if(typeof options.customLoad == 'function'){
  18700. // Use the specified custom callback.
  18701. options.customLoad(lngValue, nsValue, options, loadComplete);
  18702. } else {
  18703. //~ // Use our inbuilt sync.
  18704. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  18705. }
  18706. });
  18707. });
  18708. } else {
  18709. // Call this once our translation has returned.
  18710. var loadComplete = function(err, data) {
  18711. cb(null, data);
  18712. };
  18713. if(typeof options.customLoad == 'function'){
  18714. // Use the specified custom callback.
  18715. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  18716. } else {
  18717. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  18718. // load all needed stuff once
  18719. f.ajax({
  18720. url: url,
  18721. success: function(data, status, xhr) {
  18722. f.log('loaded: ' + url);
  18723. loadComplete(null, data);
  18724. },
  18725. error : function(xhr, status, error) {
  18726. f.log('failed loading: ' + url);
  18727. loadComplete('failed loading resource.json error: ' + error);
  18728. },
  18729. dataType: "json",
  18730. async : options.getAsync
  18731. });
  18732. }
  18733. }
  18734. },
  18735. _fetchOne: function(lng, ns, options, done) {
  18736. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  18737. f.ajax({
  18738. url: url,
  18739. success: function(data, status, xhr) {
  18740. f.log('loaded: ' + url);
  18741. done(null, data);
  18742. },
  18743. error : function(xhr, status, error) {
  18744. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  18745. // file loaded but invalid json, stop waste time !
  18746. f.error('There is a typo in: ' + url);
  18747. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  18748. f.log('Does not exist: ' + url);
  18749. } else {
  18750. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  18751. f.log(theStatus + ' when loading ' + url);
  18752. }
  18753. done(error, {});
  18754. },
  18755. dataType: "json",
  18756. async : options.getAsync
  18757. });
  18758. },
  18759. postMissing: function(lng, ns, key, defaultValue, lngs) {
  18760. var payload = {};
  18761. payload[key] = defaultValue;
  18762. var urls = [];
  18763. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  18764. for (var i = 0; i < o.fallbackLng.length; i++) {
  18765. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  18766. }
  18767. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  18768. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  18769. } else if (o.sendMissingTo === 'all') {
  18770. for (var i = 0, l = lngs.length; i < l; i++) {
  18771. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  18772. }
  18773. }
  18774. for (var y = 0, len = urls.length; y < len; y++) {
  18775. var item = urls[y];
  18776. f.ajax({
  18777. url: item.url,
  18778. type: o.sendType,
  18779. data: payload,
  18780. success: function(data, status, xhr) {
  18781. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  18782. // add key to resStore
  18783. var keys = key.split('.');
  18784. var x = 0;
  18785. var value = resStore[item.lng][ns];
  18786. while (keys[x]) {
  18787. if (x === keys.length - 1) {
  18788. value = value[keys[x]] = defaultValue;
  18789. } else {
  18790. value = value[keys[x]] = value[keys[x]] || {};
  18791. }
  18792. x++;
  18793. }
  18794. },
  18795. error : function(xhr, status, error) {
  18796. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  18797. },
  18798. dataType: "json",
  18799. async : o.postAsync
  18800. });
  18801. }
  18802. },
  18803. reload: reload
  18804. };
  18805. // defaults
  18806. var o = {
  18807. lng: undefined,
  18808. load: 'all',
  18809. preload: [],
  18810. lowerCaseLng: false,
  18811. returnObjectTrees: false,
  18812. fallbackLng: ['dev'],
  18813. fallbackNS: [],
  18814. detectLngQS: 'setLng',
  18815. detectLngFromLocalStorage: false,
  18816. ns: 'translation',
  18817. fallbackOnNull: true,
  18818. fallbackOnEmpty: false,
  18819. fallbackToDefaultNS: false,
  18820. nsseparator: ':',
  18821. keyseparator: '.',
  18822. selectorAttr: 'data-i18n',
  18823. debug: false,
  18824. resGetPath: 'locales/__lng__/__ns__.json',
  18825. resPostPath: 'locales/add/__lng__/__ns__',
  18826. getAsync: true,
  18827. postAsync: true,
  18828. resStore: undefined,
  18829. useLocalStorage: false,
  18830. localStorageExpirationTime: 7*24*60*60*1000,
  18831. dynamicLoad: false,
  18832. sendMissing: false,
  18833. sendMissingTo: 'fallback', // current | all
  18834. sendType: 'POST',
  18835. interpolationPrefix: '__',
  18836. interpolationSuffix: '__',
  18837. defaultVariables: false,
  18838. reusePrefix: '$t(',
  18839. reuseSuffix: ')',
  18840. pluralSuffix: '_plural',
  18841. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  18842. contextNotFound: ['context_not_found', Math.random()].join(''),
  18843. escapeInterpolation: false,
  18844. indefiniteSuffix: '_indefinite',
  18845. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  18846. setJqueryExt: true,
  18847. defaultValueFromContent: true,
  18848. useDataAttrOptions: false,
  18849. cookieExpirationTime: undefined,
  18850. useCookie: true,
  18851. cookieName: 'i18next',
  18852. cookieDomain: undefined,
  18853. objectTreeKeyHandler: undefined,
  18854. postProcess: undefined,
  18855. parseMissingKey: undefined,
  18856. missingKeyHandler: sync.postMissing,
  18857. shortcutFunction: 'sprintf' // or: defaultValue
  18858. };
  18859. function _extend(target, source) {
  18860. if (!source || typeof source === 'function') {
  18861. return target;
  18862. }
  18863. for (var attr in source) { target[attr] = source[attr]; }
  18864. return target;
  18865. }
  18866. function _deepExtend(target, source) {
  18867. for (var prop in source)
  18868. if (prop in target)
  18869. _deepExtend(target[prop], source[prop]);
  18870. else
  18871. target[prop] = source[prop];
  18872. return target;
  18873. }
  18874. function _each(object, callback, args) {
  18875. var name, i = 0,
  18876. length = object.length,
  18877. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  18878. if (args) {
  18879. if (isObj) {
  18880. for (name in object) {
  18881. if (callback.apply(object[name], args) === false) {
  18882. break;
  18883. }
  18884. }
  18885. } else {
  18886. for ( ; i < length; ) {
  18887. if (callback.apply(object[i++], args) === false) {
  18888. break;
  18889. }
  18890. }
  18891. }
  18892. // A special, fast, case for the most common use of each
  18893. } else {
  18894. if (isObj) {
  18895. for (name in object) {
  18896. if (callback.call(object[name], name, object[name]) === false) {
  18897. break;
  18898. }
  18899. }
  18900. } else {
  18901. for ( ; i < length; ) {
  18902. if (callback.call(object[i], i, object[i++]) === false) {
  18903. break;
  18904. }
  18905. }
  18906. }
  18907. }
  18908. return object;
  18909. }
  18910. var _entityMap = {
  18911. "&": "&amp;",
  18912. "<": "&lt;",
  18913. ">": "&gt;",
  18914. '"': '&quot;',
  18915. "'": '&#39;',
  18916. "/": '&#x2F;'
  18917. };
  18918. function _escape(data) {
  18919. if (typeof data === 'string') {
  18920. return data.replace(/[&<>"'\/]/g, function (s) {
  18921. return _entityMap[s];
  18922. });
  18923. }else{
  18924. return data;
  18925. }
  18926. }
  18927. function _ajax(options) {
  18928. // v0.5.0 of https://github.com/goloroden/http.js
  18929. var getXhr = function (callback) {
  18930. // Use the native XHR object if the browser supports it.
  18931. if (window.XMLHttpRequest) {
  18932. return callback(null, new XMLHttpRequest());
  18933. } else if (window.ActiveXObject) {
  18934. // In Internet Explorer check for ActiveX versions of the XHR object.
  18935. try {
  18936. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18937. } catch (e) {
  18938. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18939. }
  18940. }
  18941. // If no XHR support was found, throw an error.
  18942. return callback(new Error());
  18943. };
  18944. var encodeUsingUrlEncoding = function (data) {
  18945. if(typeof data === 'string') {
  18946. return data;
  18947. }
  18948. var result = [];
  18949. for(var dataItem in data) {
  18950. if(data.hasOwnProperty(dataItem)) {
  18951. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18952. }
  18953. }
  18954. return result.join('&');
  18955. };
  18956. var utf8 = function (text) {
  18957. text = text.replace(/\r\n/g, '\n');
  18958. var result = '';
  18959. for(var i = 0; i < text.length; i++) {
  18960. var c = text.charCodeAt(i);
  18961. if(c < 128) {
  18962. result += String.fromCharCode(c);
  18963. } else if((c > 127) && (c < 2048)) {
  18964. result += String.fromCharCode((c >> 6) | 192);
  18965. result += String.fromCharCode((c & 63) | 128);
  18966. } else {
  18967. result += String.fromCharCode((c >> 12) | 224);
  18968. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18969. result += String.fromCharCode((c & 63) | 128);
  18970. }
  18971. }
  18972. return result;
  18973. };
  18974. var base64 = function (text) {
  18975. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18976. text = utf8(text);
  18977. var result = '',
  18978. chr1, chr2, chr3,
  18979. enc1, enc2, enc3, enc4,
  18980. i = 0;
  18981. do {
  18982. chr1 = text.charCodeAt(i++);
  18983. chr2 = text.charCodeAt(i++);
  18984. chr3 = text.charCodeAt(i++);
  18985. enc1 = chr1 >> 2;
  18986. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18987. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18988. enc4 = chr3 & 63;
  18989. if(isNaN(chr2)) {
  18990. enc3 = enc4 = 64;
  18991. } else if(isNaN(chr3)) {
  18992. enc4 = 64;
  18993. }
  18994. result +=
  18995. keyStr.charAt(enc1) +
  18996. keyStr.charAt(enc2) +
  18997. keyStr.charAt(enc3) +
  18998. keyStr.charAt(enc4);
  18999. chr1 = chr2 = chr3 = '';
  19000. enc1 = enc2 = enc3 = enc4 = '';
  19001. } while(i < text.length);
  19002. return result;
  19003. };
  19004. var mergeHeaders = function () {
  19005. // Use the first header object as base.
  19006. var result = arguments[0];
  19007. // Iterate through the remaining header objects and add them.
  19008. for(var i = 1; i < arguments.length; i++) {
  19009. var currentHeaders = arguments[i];
  19010. for(var header in currentHeaders) {
  19011. if(currentHeaders.hasOwnProperty(header)) {
  19012. result[header] = currentHeaders[header];
  19013. }
  19014. }
  19015. }
  19016. // Return the merged headers.
  19017. return result;
  19018. };
  19019. var ajax = function (method, url, options, callback) {
  19020. // Adjust parameters.
  19021. if(typeof options === 'function') {
  19022. callback = options;
  19023. options = {};
  19024. }
  19025. // Set default parameter values.
  19026. options.cache = options.cache || false;
  19027. options.data = options.data || {};
  19028. options.headers = options.headers || {};
  19029. options.jsonp = options.jsonp || false;
  19030. options.async = options.async === undefined ? true : options.async;
  19031. // Merge the various header objects.
  19032. var headers = mergeHeaders({
  19033. 'accept': '*/*',
  19034. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  19035. }, ajax.headers, options.headers);
  19036. // Encode the data according to the content-type.
  19037. var payload;
  19038. if (headers['content-type'] === 'application/json') {
  19039. payload = JSON.stringify(options.data);
  19040. } else {
  19041. payload = encodeUsingUrlEncoding(options.data);
  19042. }
  19043. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  19044. // if neccessary.
  19045. if(method === 'GET') {
  19046. // Setup the query string.
  19047. var queryString = [];
  19048. if(payload) {
  19049. queryString.push(payload);
  19050. payload = null;
  19051. }
  19052. // Handle caching.
  19053. if(!options.cache) {
  19054. queryString.push('_=' + (new Date()).getTime());
  19055. }
  19056. // If neccessary prepare the query string for a JSONP call.
  19057. if(options.jsonp) {
  19058. queryString.push('callback=' + options.jsonp);
  19059. queryString.push('jsonp=' + options.jsonp);
  19060. }
  19061. // Merge the query string and attach it to the url.
  19062. queryString = queryString.join('&');
  19063. if (queryString.length > 1) {
  19064. if (url.indexOf('?') > -1) {
  19065. url += '&' + queryString;
  19066. } else {
  19067. url += '?' + queryString;
  19068. }
  19069. }
  19070. // Make a JSONP call if neccessary.
  19071. if(options.jsonp) {
  19072. var head = document.getElementsByTagName('head')[0];
  19073. var script = document.createElement('script');
  19074. script.type = 'text/javascript';
  19075. script.src = url;
  19076. head.appendChild(script);
  19077. return;
  19078. }
  19079. }
  19080. // Since we got here, it is no JSONP request, so make a normal XHR request.
  19081. getXhr(function (err, xhr) {
  19082. if(err) return callback(err);
  19083. // Open the request.
  19084. xhr.open(method, url, options.async);
  19085. // Set the request headers.
  19086. for(var header in headers) {
  19087. if(headers.hasOwnProperty(header)) {
  19088. xhr.setRequestHeader(header, headers[header]);
  19089. }
  19090. }
  19091. // Handle the request events.
  19092. xhr.onreadystatechange = function () {
  19093. if(xhr.readyState === 4) {
  19094. var data = xhr.responseText || '';
  19095. // If no callback is given, return.
  19096. if(!callback) {
  19097. return;
  19098. }
  19099. // Return an object that provides access to the data as text and JSON.
  19100. callback(xhr.status, {
  19101. text: function () {
  19102. return data;
  19103. },
  19104. json: function () {
  19105. try {
  19106. return JSON.parse(data)
  19107. } catch (e) {
  19108. f.error('Can not parse JSON. URL: ' + url);
  19109. return {};
  19110. }
  19111. }
  19112. });
  19113. }
  19114. };
  19115. // Actually send the XHR request.
  19116. xhr.send(payload);
  19117. });
  19118. };
  19119. // Define the external interface.
  19120. var http = {
  19121. authBasic: function (username, password) {
  19122. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  19123. },
  19124. connect: function (url, options, callback) {
  19125. return ajax('CONNECT', url, options, callback);
  19126. },
  19127. del: function (url, options, callback) {
  19128. return ajax('DELETE', url, options, callback);
  19129. },
  19130. get: function (url, options, callback) {
  19131. return ajax('GET', url, options, callback);
  19132. },
  19133. head: function (url, options, callback) {
  19134. return ajax('HEAD', url, options, callback);
  19135. },
  19136. headers: function (headers) {
  19137. ajax.headers = headers || {};
  19138. },
  19139. isAllowed: function (url, verb, callback) {
  19140. this.options(url, function (status, data) {
  19141. callback(data.text().indexOf(verb) !== -1);
  19142. });
  19143. },
  19144. options: function (url, options, callback) {
  19145. return ajax('OPTIONS', url, options, callback);
  19146. },
  19147. patch: function (url, options, callback) {
  19148. return ajax('PATCH', url, options, callback);
  19149. },
  19150. post: function (url, options, callback) {
  19151. return ajax('POST', url, options, callback);
  19152. },
  19153. put: function (url, options, callback) {
  19154. return ajax('PUT', url, options, callback);
  19155. },
  19156. trace: function (url, options, callback) {
  19157. return ajax('TRACE', url, options, callback);
  19158. }
  19159. };
  19160. var methode = options.type ? options.type.toLowerCase() : 'get';
  19161. http[methode](options.url, options, function (status, data) {
  19162. // file: protocol always gives status code 0, so check for data
  19163. if (status === 200 || (status === 0 && data.text())) {
  19164. options.success(data.json(), status, null);
  19165. } else {
  19166. options.error(data.text(), status, null);
  19167. }
  19168. });
  19169. }
  19170. var _cookie = {
  19171. create: function(name,value,minutes,domain) {
  19172. var expires;
  19173. if (minutes) {
  19174. var date = new Date();
  19175. date.setTime(date.getTime()+(minutes*60*1000));
  19176. expires = "; expires="+date.toGMTString();
  19177. }
  19178. else expires = "";
  19179. domain = (domain)? "domain="+domain+";" : "";
  19180. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  19181. },
  19182. read: function(name) {
  19183. var nameEQ = name + "=";
  19184. var ca = document.cookie.split(';');
  19185. for(var i=0;i < ca.length;i++) {
  19186. var c = ca[i];
  19187. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  19188. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  19189. }
  19190. return null;
  19191. },
  19192. remove: function(name) {
  19193. this.create(name,"",-1);
  19194. }
  19195. };
  19196. var cookie_noop = {
  19197. create: function(name,value,minutes,domain) {},
  19198. read: function(name) { return null; },
  19199. remove: function(name) {}
  19200. };
  19201. // move dependent functions to a container so that
  19202. // they can be overriden easier in no jquery environment (node.js)
  19203. var f = {
  19204. extend: $ ? $.extend : _extend,
  19205. deepExtend: _deepExtend,
  19206. each: $ ? $.each : _each,
  19207. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  19208. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  19209. detectLanguage: detectLanguage,
  19210. escape: _escape,
  19211. log: function(str) {
  19212. if (o.debug && typeof console !== "undefined") console.log(str);
  19213. },
  19214. error: function(str) {
  19215. if (typeof console !== "undefined") console.error(str);
  19216. },
  19217. getCountyIndexOfLng: function(lng) {
  19218. var lng_index = 0;
  19219. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  19220. return lng_index;
  19221. },
  19222. toLanguages: function(lng) {
  19223. var log = this.log;
  19224. function applyCase(l) {
  19225. var ret = l;
  19226. if (typeof l === 'string' && l.indexOf('-') > -1) {
  19227. var parts = l.split('-');
  19228. ret = o.lowerCaseLng ?
  19229. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19230. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19231. } else {
  19232. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  19233. }
  19234. return ret;
  19235. }
  19236. var languages = [];
  19237. var whitelist = o.lngWhitelist || false;
  19238. var addLanguage = function(language){
  19239. //reject langs not whitelisted
  19240. if(!whitelist || whitelist.indexOf(language) > -1){
  19241. languages.push(language);
  19242. }else{
  19243. log('rejecting non-whitelisted language: ' + language);
  19244. }
  19245. };
  19246. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  19247. var parts = lng.split('-');
  19248. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  19249. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  19250. } else {
  19251. addLanguage(applyCase(lng));
  19252. }
  19253. for (var i = 0; i < o.fallbackLng.length; i++) {
  19254. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  19255. }
  19256. return languages;
  19257. },
  19258. regexEscape: function(str) {
  19259. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  19260. },
  19261. regexReplacementEscape: function(strOrFn) {
  19262. if (typeof strOrFn === 'string') {
  19263. return strOrFn.replace(/\$/g, "$$$$");
  19264. } else {
  19265. return strOrFn;
  19266. }
  19267. },
  19268. localStorage: {
  19269. setItem: function(key, value) {
  19270. if (window.localStorage) {
  19271. try {
  19272. window.localStorage.setItem(key, value);
  19273. } catch (e) {
  19274. f.log('failed to set value for key "' + key + '" to localStorage.');
  19275. }
  19276. }
  19277. }
  19278. }
  19279. };
  19280. function init(options, cb) {
  19281. if (typeof options === 'function') {
  19282. cb = options;
  19283. options = {};
  19284. }
  19285. options = options || {};
  19286. // override defaults with passed in options
  19287. f.extend(o, options);
  19288. delete o.fixLng; /* passed in each time */
  19289. // override functions: .log(), .detectLanguage(), etc
  19290. if (o.functions) {
  19291. delete o.functions;
  19292. f.extend(f, options.functions);
  19293. }
  19294. // create namespace object if namespace is passed in as string
  19295. if (typeof o.ns == 'string') {
  19296. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  19297. }
  19298. // fallback namespaces
  19299. if (typeof o.fallbackNS == 'string') {
  19300. o.fallbackNS = [o.fallbackNS];
  19301. }
  19302. // fallback languages
  19303. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  19304. o.fallbackLng = [o.fallbackLng];
  19305. }
  19306. // escape prefix/suffix
  19307. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  19308. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  19309. if (!o.lng) o.lng = f.detectLanguage();
  19310. languages = f.toLanguages(o.lng);
  19311. currentLng = languages[0];
  19312. f.log('currentLng set to: ' + currentLng);
  19313. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  19314. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  19315. }
  19316. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  19317. f.localStorage.setItem('i18next_lng', currentLng);
  19318. }
  19319. var lngTranslate = translate;
  19320. if (options.fixLng) {
  19321. lngTranslate = function(key, options) {
  19322. options = options || {};
  19323. options.lng = options.lng || lngTranslate.lng;
  19324. return translate(key, options);
  19325. };
  19326. lngTranslate.lng = currentLng;
  19327. }
  19328. pluralExtensions.setCurrentLng(currentLng);
  19329. // add JQuery extensions
  19330. if ($ && o.setJqueryExt) addJqueryFunct();
  19331. // jQuery deferred
  19332. var deferred;
  19333. if ($ && $.Deferred) {
  19334. deferred = $.Deferred();
  19335. }
  19336. // return immidiatly if res are passed in
  19337. if (o.resStore) {
  19338. resStore = o.resStore;
  19339. initialized = true;
  19340. if (cb) cb(lngTranslate);
  19341. if (deferred) deferred.resolve(lngTranslate);
  19342. if (deferred) return deferred.promise();
  19343. return;
  19344. }
  19345. // languages to load
  19346. var lngsToLoad = f.toLanguages(o.lng);
  19347. if (typeof o.preload === 'string') o.preload = [o.preload];
  19348. for (var i = 0, l = o.preload.length; i < l; i++) {
  19349. var pres = f.toLanguages(o.preload[i]);
  19350. for (var y = 0, len = pres.length; y < len; y++) {
  19351. if (lngsToLoad.indexOf(pres[y]) < 0) {
  19352. lngsToLoad.push(pres[y]);
  19353. }
  19354. }
  19355. }
  19356. // else load them
  19357. i18n.sync.load(lngsToLoad, o, function(err, store) {
  19358. resStore = store;
  19359. initialized = true;
  19360. if (cb) cb(lngTranslate);
  19361. if (deferred) deferred.resolve(lngTranslate);
  19362. });
  19363. if (deferred) return deferred.promise();
  19364. }
  19365. function preload(lngs, cb) {
  19366. if (typeof lngs === 'string') lngs = [lngs];
  19367. for (var i = 0, l = lngs.length; i < l; i++) {
  19368. if (o.preload.indexOf(lngs[i]) < 0) {
  19369. o.preload.push(lngs[i]);
  19370. }
  19371. }
  19372. return init(cb);
  19373. }
  19374. function addResourceBundle(lng, ns, resources, deep) {
  19375. if (typeof ns !== 'string') {
  19376. resources = ns;
  19377. ns = o.ns.defaultNs;
  19378. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19379. o.ns.namespaces.push(ns);
  19380. }
  19381. resStore[lng] = resStore[lng] || {};
  19382. resStore[lng][ns] = resStore[lng][ns] || {};
  19383. if (deep) {
  19384. f.deepExtend(resStore[lng][ns], resources);
  19385. } else {
  19386. f.extend(resStore[lng][ns], resources);
  19387. }
  19388. }
  19389. function hasResourceBundle(lng, ns) {
  19390. if (typeof ns !== 'string') {
  19391. ns = o.ns.defaultNs;
  19392. }
  19393. resStore[lng] = resStore[lng] || {};
  19394. var res = resStore[lng][ns] || {};
  19395. var hasValues = false;
  19396. for(var prop in res) {
  19397. if (res.hasOwnProperty(prop)) {
  19398. hasValues = true;
  19399. }
  19400. }
  19401. return hasValues;
  19402. }
  19403. function removeResourceBundle(lng, ns) {
  19404. if (typeof ns !== 'string') {
  19405. ns = o.ns.defaultNs;
  19406. }
  19407. resStore[lng] = resStore[lng] || {};
  19408. resStore[lng][ns] = {};
  19409. }
  19410. function addResource(lng, ns, key, value) {
  19411. if (typeof ns !== 'string') {
  19412. resource = ns;
  19413. ns = o.ns.defaultNs;
  19414. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19415. o.ns.namespaces.push(ns);
  19416. }
  19417. resStore[lng] = resStore[lng] || {};
  19418. resStore[lng][ns] = resStore[lng][ns] || {};
  19419. var keys = key.split(o.keyseparator);
  19420. var x = 0;
  19421. var node = resStore[lng][ns];
  19422. var origRef = node;
  19423. while (keys[x]) {
  19424. if (x == keys.length - 1)
  19425. node[keys[x]] = value;
  19426. else {
  19427. if (node[keys[x]] == null)
  19428. node[keys[x]] = {};
  19429. node = node[keys[x]];
  19430. }
  19431. x++;
  19432. }
  19433. }
  19434. function addResources(lng, ns, resources) {
  19435. if (typeof ns !== 'string') {
  19436. resource = ns;
  19437. ns = o.ns.defaultNs;
  19438. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19439. o.ns.namespaces.push(ns);
  19440. }
  19441. for (var m in resources) {
  19442. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  19443. }
  19444. }
  19445. function setDefaultNamespace(ns) {
  19446. o.ns.defaultNs = ns;
  19447. }
  19448. function loadNamespace(namespace, cb) {
  19449. loadNamespaces([namespace], cb);
  19450. }
  19451. function loadNamespaces(namespaces, cb) {
  19452. var opts = {
  19453. dynamicLoad: o.dynamicLoad,
  19454. resGetPath: o.resGetPath,
  19455. getAsync: o.getAsync,
  19456. customLoad: o.customLoad,
  19457. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  19458. };
  19459. // languages to load
  19460. var lngsToLoad = f.toLanguages(o.lng);
  19461. if (typeof o.preload === 'string') o.preload = [o.preload];
  19462. for (var i = 0, l = o.preload.length; i < l; i++) {
  19463. var pres = f.toLanguages(o.preload[i]);
  19464. for (var y = 0, len = pres.length; y < len; y++) {
  19465. if (lngsToLoad.indexOf(pres[y]) < 0) {
  19466. lngsToLoad.push(pres[y]);
  19467. }
  19468. }
  19469. }
  19470. // check if we have to load
  19471. var lngNeedLoad = [];
  19472. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  19473. var needLoad = false;
  19474. var resSet = resStore[lngsToLoad[a]];
  19475. if (resSet) {
  19476. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  19477. if (!resSet[namespaces[b]]) needLoad = true;
  19478. }
  19479. } else {
  19480. needLoad = true;
  19481. }
  19482. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  19483. }
  19484. if (lngNeedLoad.length) {
  19485. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  19486. var todo = namespaces.length * lngNeedLoad.length;
  19487. // load each file individual
  19488. f.each(namespaces, function(nsIndex, nsValue) {
  19489. // append namespace to namespace array
  19490. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  19491. o.ns.namespaces.push(nsValue);
  19492. }
  19493. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  19494. resStore[lngValue] = resStore[lngValue] || {};
  19495. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  19496. todo--; // wait for all done befor callback
  19497. if (todo === 0 && cb) {
  19498. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  19499. cb();
  19500. }
  19501. });
  19502. });
  19503. });
  19504. } else {
  19505. if (cb) cb();
  19506. }
  19507. }
  19508. function setLng(lng, options, cb) {
  19509. if (typeof options === 'function') {
  19510. cb = options;
  19511. options = {};
  19512. } else if (!options) {
  19513. options = {};
  19514. }
  19515. options.lng = lng;
  19516. return init(options, cb);
  19517. }
  19518. function lng() {
  19519. return currentLng;
  19520. }
  19521. function reload(cb) {
  19522. resStore = {};
  19523. setLng(currentLng, cb);
  19524. }
  19525. function addJqueryFunct() {
  19526. // $.t shortcut
  19527. $.t = $.t || translate;
  19528. function parse(ele, key, options) {
  19529. if (key.length === 0) return;
  19530. var attr = 'text';
  19531. if (key.indexOf('[') === 0) {
  19532. var parts = key.split(']');
  19533. key = parts[1];
  19534. attr = parts[0].substr(1, parts[0].length-1);
  19535. }
  19536. if (key.indexOf(';') === key.length-1) {
  19537. key = key.substr(0, key.length-2);
  19538. }
  19539. var optionsToUse;
  19540. if (attr === 'html') {
  19541. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19542. ele.html($.t(key, optionsToUse));
  19543. } else if (attr === 'text') {
  19544. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  19545. ele.text($.t(key, optionsToUse));
  19546. } else if (attr === 'prepend') {
  19547. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19548. ele.prepend($.t(key, optionsToUse));
  19549. } else if (attr === 'append') {
  19550. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19551. ele.append($.t(key, optionsToUse));
  19552. } else if (attr.indexOf("data-") === 0) {
  19553. var dataAttr = attr.substr(("data-").length);
  19554. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  19555. var translated = $.t(key, optionsToUse);
  19556. //we change into the data cache
  19557. ele.data(dataAttr, translated);
  19558. //we change into the dom
  19559. ele.attr(attr, translated);
  19560. } else {
  19561. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  19562. ele.attr(attr, $.t(key, optionsToUse));
  19563. }
  19564. }
  19565. function localize(ele, options) {
  19566. var key = ele.attr(o.selectorAttr);
  19567. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  19568. if (!key) return;
  19569. var target = ele
  19570. , targetSelector = ele.data("i18n-target");
  19571. if (targetSelector) {
  19572. target = ele.find(targetSelector) || ele;
  19573. }
  19574. if (!options && o.useDataAttrOptions === true) {
  19575. options = ele.data("i18n-options");
  19576. }
  19577. options = options || {};
  19578. if (key.indexOf(';') >= 0) {
  19579. var keys = key.split(';');
  19580. $.each(keys, function(m, k) {
  19581. if (k !== '') parse(target, k, options);
  19582. });
  19583. } else {
  19584. parse(target, key, options);
  19585. }
  19586. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  19587. }
  19588. // fn
  19589. $.fn.i18n = function (options) {
  19590. return this.each(function() {
  19591. // localize element itself
  19592. localize($(this), options);
  19593. // localize childs
  19594. var elements = $(this).find('[' + o.selectorAttr + ']');
  19595. elements.each(function() {
  19596. localize($(this), options);
  19597. });
  19598. });
  19599. };
  19600. }
  19601. function applyReplacement(str, replacementHash, nestedKey, options) {
  19602. if (!str) return str;
  19603. options = options || replacementHash; // first call uses replacement hash combined with options
  19604. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  19605. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  19606. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  19607. , unEscapingSuffix = 'HTML'+suffix;
  19608. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  19609. f.each(hash, function(key, value) {
  19610. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  19611. if (typeof value === 'object' && value !== null) {
  19612. str = applyReplacement(str, value, nextKey, options);
  19613. } else {
  19614. if (options.escapeInterpolation || o.escapeInterpolation) {
  19615. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  19616. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  19617. } else {
  19618. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  19619. }
  19620. // str = options.escapeInterpolation;
  19621. }
  19622. });
  19623. return str;
  19624. }
  19625. // append it to functions
  19626. f.applyReplacement = applyReplacement;
  19627. function applyReuse(translated, options) {
  19628. var comma = ',';
  19629. var options_open = '{';
  19630. var options_close = '}';
  19631. var opts = f.extend({}, options);
  19632. delete opts.postProcess;
  19633. while (translated.indexOf(o.reusePrefix) != -1) {
  19634. replacementCounter++;
  19635. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  19636. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  19637. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  19638. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  19639. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  19640. if (index_of_end_of_closing <= index_of_opening) {
  19641. f.error('there is an missing closing in following translation value', translated);
  19642. return '';
  19643. }
  19644. if (token_without_symbols.indexOf(comma) != -1) {
  19645. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  19646. if (token_without_symbols.indexOf(options_open, index_of_token_end_of_closing) != -1 && token_without_symbols.indexOf(options_close, index_of_token_end_of_closing) != -1) {
  19647. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  19648. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  19649. try {
  19650. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  19651. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  19652. } catch (e) {
  19653. }
  19654. }
  19655. }
  19656. var translated_token = _translate(token_without_symbols, opts);
  19657. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  19658. }
  19659. return translated;
  19660. }
  19661. function hasContext(options) {
  19662. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  19663. }
  19664. function needsPlural(options, lng) {
  19665. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  19666. }
  19667. function needsIndefiniteArticle(options) {
  19668. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  19669. }
  19670. function exists(key, options) {
  19671. options = options || {};
  19672. var notFound = _getDefaultValue(key, options)
  19673. , found = _find(key, options);
  19674. return found !== undefined || found === notFound;
  19675. }
  19676. function translate(key, options) {
  19677. options = options || {};
  19678. if (!initialized) {
  19679. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  19680. return options.defaultValue || '';
  19681. };
  19682. replacementCounter = 0;
  19683. return _translate.apply(null, arguments);
  19684. }
  19685. function _getDefaultValue(key, options) {
  19686. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  19687. }
  19688. function _injectSprintfProcessor() {
  19689. var values = [];
  19690. // mh: build array from second argument onwards
  19691. for (var i = 1; i < arguments.length; i++) {
  19692. values.push(arguments[i]);
  19693. }
  19694. return {
  19695. postProcess: 'sprintf',
  19696. sprintf: values
  19697. };
  19698. }
  19699. function _translate(potentialKeys, options) {
  19700. if (options && typeof options !== 'object') {
  19701. if (o.shortcutFunction === 'sprintf') {
  19702. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  19703. options = _injectSprintfProcessor.apply(null, arguments);
  19704. } else if (o.shortcutFunction === 'defaultValue') {
  19705. options = {
  19706. defaultValue: options
  19707. }
  19708. }
  19709. } else {
  19710. options = options || {};
  19711. }
  19712. if (typeof o.defaultVariables === 'object') {
  19713. options = f.extend({}, o.defaultVariables, options);
  19714. }
  19715. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  19716. if (typeof potentialKeys === 'string') {
  19717. potentialKeys = [potentialKeys];
  19718. }
  19719. var key = potentialKeys[0];
  19720. if (potentialKeys.length > 1) {
  19721. for (var i = 0; i < potentialKeys.length; i++) {
  19722. key = potentialKeys[i];
  19723. if (exists(key, options)) {
  19724. break;
  19725. }
  19726. }
  19727. }
  19728. var notFound = _getDefaultValue(key, options)
  19729. , found = _find(key, options)
  19730. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  19731. , ns = options.ns || o.ns.defaultNs
  19732. , parts;
  19733. // split ns and key
  19734. if (key.indexOf(o.nsseparator) > -1) {
  19735. parts = key.split(o.nsseparator);
  19736. ns = parts[0];
  19737. key = parts[1];
  19738. }
  19739. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  19740. if (options.lng) {
  19741. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  19742. } else {
  19743. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  19744. }
  19745. }
  19746. var postProcessor = options.postProcess || o.postProcess;
  19747. if (found !== undefined && postProcessor) {
  19748. if (postProcessors[postProcessor]) {
  19749. found = postProcessors[postProcessor](found, key, options);
  19750. }
  19751. }
  19752. // process notFound if function exists
  19753. var splitNotFound = notFound;
  19754. if (notFound.indexOf(o.nsseparator) > -1) {
  19755. parts = notFound.split(o.nsseparator);
  19756. splitNotFound = parts[1];
  19757. }
  19758. if (splitNotFound === key && o.parseMissingKey) {
  19759. notFound = o.parseMissingKey(notFound);
  19760. }
  19761. if (found === undefined) {
  19762. notFound = applyReplacement(notFound, options);
  19763. notFound = applyReuse(notFound, options);
  19764. if (postProcessor && postProcessors[postProcessor]) {
  19765. var val = _getDefaultValue(key, options);
  19766. found = postProcessors[postProcessor](val, key, options);
  19767. }
  19768. }
  19769. return (found !== undefined) ? found : notFound;
  19770. }
  19771. function _find(key, options) {
  19772. options = options || {};
  19773. var optionWithoutCount, translated
  19774. , notFound = _getDefaultValue(key, options)
  19775. , lngs = languages;
  19776. if (!resStore) { return notFound; } // no resStore to translate from
  19777. // CI mode
  19778. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  19779. // passed in lng
  19780. if (options.lngs) lngs = options.lngs;
  19781. if (options.lng) {
  19782. lngs = f.toLanguages(options.lng, options.fallbackLng);
  19783. if (!resStore[lngs[0]]) {
  19784. var oldAsync = o.getAsync;
  19785. o.getAsync = false;
  19786. i18n.sync.load(lngs, o, function(err, store) {
  19787. f.extend(resStore, store);
  19788. o.getAsync = oldAsync;
  19789. });
  19790. }
  19791. }
  19792. var ns = options.ns || o.ns.defaultNs;
  19793. if (key.indexOf(o.nsseparator) > -1) {
  19794. var parts = key.split(o.nsseparator);
  19795. ns = parts[0];
  19796. key = parts[1];
  19797. }
  19798. if (hasContext(options)) {
  19799. optionWithoutCount = f.extend({}, options);
  19800. delete optionWithoutCount.context;
  19801. optionWithoutCount.defaultValue = o.contextNotFound;
  19802. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  19803. translated = translate(contextKey, optionWithoutCount);
  19804. if (translated != o.contextNotFound) {
  19805. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  19806. } // else continue translation with original/nonContext key
  19807. }
  19808. if (needsPlural(options, lngs[0])) {
  19809. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  19810. delete optionWithoutCount.count;
  19811. delete optionWithoutCount.lng;
  19812. optionWithoutCount.defaultValue = o.pluralNotFound;
  19813. var pluralKey;
  19814. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  19815. pluralKey = ns + o.nsseparator + key;
  19816. } else {
  19817. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  19818. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  19819. if (pluralExtension >= 0) {
  19820. pluralKey = pluralKey + '_' + pluralExtension;
  19821. } else if (pluralExtension === 1) {
  19822. pluralKey = ns + o.nsseparator + key; // singular
  19823. }
  19824. }
  19825. translated = translate(pluralKey, optionWithoutCount);
  19826. if (translated != o.pluralNotFound) {
  19827. return applyReplacement(translated, {
  19828. count: options.count,
  19829. interpolationPrefix: options.interpolationPrefix,
  19830. interpolationSuffix: options.interpolationSuffix
  19831. }); // apply replacement for count only
  19832. } else if (lngs.length > 1) {
  19833. // remove failed lng
  19834. var clone = lngs.slice();
  19835. clone.shift();
  19836. options = f.extend(options, { lngs: clone });
  19837. delete options.lng;
  19838. // retry with fallbacks
  19839. translated = translate(ns + o.nsseparator + key, options);
  19840. if (translated != o.pluralNotFound) return translated;
  19841. } else {
  19842. return translated;
  19843. }
  19844. }
  19845. if (needsIndefiniteArticle(options)) {
  19846. var optionsWithoutIndef = f.extend({}, options);
  19847. delete optionsWithoutIndef.indefinite_article;
  19848. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  19849. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  19850. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  19851. translated = translate(indefiniteKey, optionsWithoutIndef);
  19852. if (translated != o.indefiniteNotFound) {
  19853. return translated;
  19854. }
  19855. }
  19856. var found;
  19857. var keys = key.split(o.keyseparator);
  19858. for (var i = 0, len = lngs.length; i < len; i++ ) {
  19859. if (found !== undefined) break;
  19860. var l = lngs[i];
  19861. var x = 0;
  19862. var value = resStore[l] && resStore[l][ns];
  19863. while (keys[x]) {
  19864. value = value && value[keys[x]];
  19865. x++;
  19866. }
  19867. if (value !== undefined) {
  19868. var valueType = Object.prototype.toString.apply(value);
  19869. if (typeof value === 'string') {
  19870. value = applyReplacement(value, options);
  19871. value = applyReuse(value, options);
  19872. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  19873. value = value.join('\n');
  19874. value = applyReplacement(value, options);
  19875. value = applyReuse(value, options);
  19876. } else if (value === null && o.fallbackOnNull === true) {
  19877. value = undefined;
  19878. } else if (value !== null) {
  19879. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  19880. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  19881. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  19882. } else {
  19883. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  19884. 'returned an object instead of string.';
  19885. f.log(value);
  19886. }
  19887. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  19888. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  19889. f.each(value, function(m) {
  19890. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  19891. });
  19892. value = copy;
  19893. }
  19894. }
  19895. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  19896. value = undefined;
  19897. found = value;
  19898. }
  19899. }
  19900. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19901. // set flag for fallback lookup - avoid recursion
  19902. options.isFallbackLookup = true;
  19903. if (o.fallbackNS.length) {
  19904. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19905. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19906. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19907. /* compare value without namespace */
  19908. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19909. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19910. if (foundValue !== notFoundValue) break;
  19911. }
  19912. }
  19913. } else {
  19914. found = _find(key, options); // fallback to default NS
  19915. }
  19916. options.isFallbackLookup = false;
  19917. }
  19918. return found;
  19919. }
  19920. function detectLanguage() {
  19921. var detectedLng;
  19922. var whitelist = o.lngWhitelist || [];
  19923. var userLngChoices = [];
  19924. // get from qs
  19925. var qsParm = [];
  19926. if (typeof window !== 'undefined') {
  19927. (function() {
  19928. var query = window.location.search.substring(1);
  19929. var params = query.split('&');
  19930. for (var i=0; i<params.length; i++) {
  19931. var pos = params[i].indexOf('=');
  19932. if (pos > 0) {
  19933. var key = params[i].substring(0,pos);
  19934. if (key == o.detectLngQS) {
  19935. userLngChoices.push(params[i].substring(pos+1));
  19936. }
  19937. }
  19938. }
  19939. })();
  19940. }
  19941. // get from cookie
  19942. if (o.useCookie && typeof document !== 'undefined') {
  19943. var c = f.cookie.read(o.cookieName);
  19944. if (c) userLngChoices.push(c);
  19945. }
  19946. // get from localStorage
  19947. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19948. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19949. }
  19950. // get from navigator
  19951. if (typeof navigator !== 'undefined') {
  19952. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19953. for (var i=0;i<navigator.languages.length;i++) {
  19954. userLngChoices.push(navigator.languages[i]);
  19955. }
  19956. }
  19957. if (navigator.userLanguage) {
  19958. userLngChoices.push(navigator.userLanguage);
  19959. }
  19960. if (navigator.language) {
  19961. userLngChoices.push(navigator.language);
  19962. }
  19963. }
  19964. (function() {
  19965. for (var i=0;i<userLngChoices.length;i++) {
  19966. var lng = userLngChoices[i];
  19967. if (lng.indexOf('-') > -1) {
  19968. var parts = lng.split('-');
  19969. lng = o.lowerCaseLng ?
  19970. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19971. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19972. }
  19973. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19974. detectedLng = lng;
  19975. break;
  19976. }
  19977. }
  19978. })();
  19979. //fallback
  19980. if (!detectedLng){
  19981. detectedLng = o.fallbackLng[0];
  19982. }
  19983. return detectedLng;
  19984. }
  19985. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19986. /* [code, name, numbers, pluralsType] */
  19987. var _rules = [
  19988. ["ach", "Acholi", [1,2], 1],
  19989. ["af", "Afrikaans",[1,2], 2],
  19990. ["ak", "Akan", [1,2], 1],
  19991. ["am", "Amharic", [1,2], 1],
  19992. ["an", "Aragonese",[1,2], 2],
  19993. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19994. ["arn", "Mapudungun",[1,2], 1],
  19995. ["ast", "Asturian", [1,2], 2],
  19996. ["ay", "Aymará", [1], 3],
  19997. ["az", "Azerbaijani",[1,2],2],
  19998. ["be", "Belarusian",[1,2,5],4],
  19999. ["bg", "Bulgarian",[1,2], 2],
  20000. ["bn", "Bengali", [1,2], 2],
  20001. ["bo", "Tibetan", [1], 3],
  20002. ["br", "Breton", [1,2], 1],
  20003. ["bs", "Bosnian", [1,2,5],4],
  20004. ["ca", "Catalan", [1,2], 2],
  20005. ["cgg", "Chiga", [1], 3],
  20006. ["cs", "Czech", [1,2,5],6],
  20007. ["csb", "Kashubian",[1,2,5],7],
  20008. ["cy", "Welsh", [1,2,3,8],8],
  20009. ["da", "Danish", [1,2], 2],
  20010. ["de", "German", [1,2], 2],
  20011. ["dev", "Development Fallback", [1,2], 2],
  20012. ["dz", "Dzongkha", [1], 3],
  20013. ["el", "Greek", [1,2], 2],
  20014. ["en", "English", [1,2], 2],
  20015. ["eo", "Esperanto",[1,2], 2],
  20016. ["es", "Spanish", [1,2], 2],
  20017. ["es_ar","Argentinean Spanish", [1,2], 2],
  20018. ["et", "Estonian", [1,2], 2],
  20019. ["eu", "Basque", [1,2], 2],
  20020. ["fa", "Persian", [1], 3],
  20021. ["fi", "Finnish", [1,2], 2],
  20022. ["fil", "Filipino", [1,2], 1],
  20023. ["fo", "Faroese", [1,2], 2],
  20024. ["fr", "French", [1,2], 9],
  20025. ["fur", "Friulian", [1,2], 2],
  20026. ["fy", "Frisian", [1,2], 2],
  20027. ["ga", "Irish", [1,2,3,7,11],10],
  20028. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  20029. ["gl", "Galician", [1,2], 2],
  20030. ["gu", "Gujarati", [1,2], 2],
  20031. ["gun", "Gun", [1,2], 1],
  20032. ["ha", "Hausa", [1,2], 2],
  20033. ["he", "Hebrew", [1,2], 2],
  20034. ["hi", "Hindi", [1,2], 2],
  20035. ["hr", "Croatian", [1,2,5],4],
  20036. ["hu", "Hungarian",[1,2], 2],
  20037. ["hy", "Armenian", [1,2], 2],
  20038. ["ia", "Interlingua",[1,2],2],
  20039. ["id", "Indonesian",[1], 3],
  20040. ["is", "Icelandic",[1,2], 12],
  20041. ["it", "Italian", [1,2], 2],
  20042. ["ja", "Japanese", [1], 3],
  20043. ["jbo", "Lojban", [1], 3],
  20044. ["jv", "Javanese", [0,1], 13],
  20045. ["ka", "Georgian", [1], 3],
  20046. ["kk", "Kazakh", [1], 3],
  20047. ["km", "Khmer", [1], 3],
  20048. ["kn", "Kannada", [1,2], 2],
  20049. ["ko", "Korean", [1], 3],
  20050. ["ku", "Kurdish", [1,2], 2],
  20051. ["kw", "Cornish", [1,2,3,4],14],
  20052. ["ky", "Kyrgyz", [1], 3],
  20053. ["lb", "Letzeburgesch",[1,2],2],
  20054. ["ln", "Lingala", [1,2], 1],
  20055. ["lo", "Lao", [1], 3],
  20056. ["lt", "Lithuanian",[1,2,10],15],
  20057. ["lv", "Latvian", [1,2,0],16],
  20058. ["mai", "Maithili", [1,2], 2],
  20059. ["mfe", "Mauritian Creole",[1,2],1],
  20060. ["mg", "Malagasy", [1,2], 1],
  20061. ["mi", "Maori", [1,2], 1],
  20062. ["mk", "Macedonian",[1,2],17],
  20063. ["ml", "Malayalam",[1,2], 2],
  20064. ["mn", "Mongolian",[1,2], 2],
  20065. ["mnk", "Mandinka", [0,1,2],18],
  20066. ["mr", "Marathi", [1,2], 2],
  20067. ["ms", "Malay", [1], 3],
  20068. ["mt", "Maltese", [1,2,11,20],19],
  20069. ["nah", "Nahuatl", [1,2], 2],
  20070. ["nap", "Neapolitan",[1,2], 2],
  20071. ["nb", "Norwegian Bokmal",[1,2],2],
  20072. ["ne", "Nepali", [1,2], 2],
  20073. ["nl", "Dutch", [1,2], 2],
  20074. ["nn", "Norwegian Nynorsk",[1,2],2],
  20075. ["no", "Norwegian",[1,2], 2],
  20076. ["nso", "Northern Sotho",[1,2],2],
  20077. ["oc", "Occitan", [1,2], 1],
  20078. ["or", "Oriya", [2,1], 2],
  20079. ["pa", "Punjabi", [1,2], 2],
  20080. ["pap", "Papiamento",[1,2], 2],
  20081. ["pl", "Polish", [1,2,5],7],
  20082. ["pms", "Piemontese",[1,2], 2],
  20083. ["ps", "Pashto", [1,2], 2],
  20084. ["pt", "Portuguese",[1,2], 2],
  20085. ["pt_br","Brazilian Portuguese",[1,2], 2],
  20086. ["rm", "Romansh", [1,2], 2],
  20087. ["ro", "Romanian", [1,2,20],20],
  20088. ["ru", "Russian", [1,2,5],4],
  20089. ["sah", "Yakut", [1], 3],
  20090. ["sco", "Scots", [1,2], 2],
  20091. ["se", "Northern Sami",[1,2], 2],
  20092. ["si", "Sinhala", [1,2], 2],
  20093. ["sk", "Slovak", [1,2,5],6],
  20094. ["sl", "Slovenian",[5,1,2,3],21],
  20095. ["so", "Somali", [1,2], 2],
  20096. ["son", "Songhay", [1,2], 2],
  20097. ["sq", "Albanian", [1,2], 2],
  20098. ["sr", "Serbian", [1,2,5],4],
  20099. ["su", "Sundanese",[1], 3],
  20100. ["sv", "Swedish", [1,2], 2],
  20101. ["sw", "Swahili", [1,2], 2],
  20102. ["ta", "Tamil", [1,2], 2],
  20103. ["te", "Telugu", [1,2], 2],
  20104. ["tg", "Tajik", [1,2], 1],
  20105. ["th", "Thai", [1], 3],
  20106. ["ti", "Tigrinya", [1,2], 1],
  20107. ["tk", "Turkmen", [1,2], 2],
  20108. ["tr", "Turkish", [1,2], 1],
  20109. ["tt", "Tatar", [1], 3],
  20110. ["ug", "Uyghur", [1], 3],
  20111. ["uk", "Ukrainian",[1,2,5],4],
  20112. ["ur", "Urdu", [1,2], 2],
  20113. ["uz", "Uzbek", [1,2], 1],
  20114. ["vi", "Vietnamese",[1], 3],
  20115. ["wa", "Walloon", [1,2], 1],
  20116. ["wo", "Wolof", [1], 3],
  20117. ["yo", "Yoruba", [1,2], 2],
  20118. ["zh", "Chinese", [1], 3]
  20119. ];
  20120. var _rulesPluralsTypes = {
  20121. 1: function(n) {return Number(n > 1);},
  20122. 2: function(n) {return Number(n != 1);},
  20123. 3: function(n) {return 0;},
  20124. 4: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  20125. 5: function(n) {return Number(n===0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);},
  20126. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  20127. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  20128. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  20129. 9: function(n) {return Number(n >= 2);},
  20130. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  20131. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  20132. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  20133. 13: function(n) {return Number(n !== 0);},
  20134. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  20135. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  20136. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  20137. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  20138. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  20139. 19: function(n) {return Number(n==1 ? 0 : n===0 || ( n%100>1 && n%100<11) ? 1 : (n%100>10 && n%100<20 ) ? 2 : 3);},
  20140. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  20141. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  20142. };
  20143. var pluralExtensions = {
  20144. rules: (function () {
  20145. var l, rules = {};
  20146. for (l=_rules.length; l-- ;) {
  20147. rules[_rules[l][0]] = {
  20148. name: _rules[l][1],
  20149. numbers: _rules[l][2],
  20150. plurals: _rulesPluralsTypes[_rules[l][3]]
  20151. }
  20152. }
  20153. return rules;
  20154. }()),
  20155. // you can add your own pluralExtensions
  20156. addRule: function(lng, obj) {
  20157. pluralExtensions.rules[lng] = obj;
  20158. },
  20159. setCurrentLng: function(lng) {
  20160. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  20161. var parts = lng.split('-');
  20162. pluralExtensions.currentRule = {
  20163. lng: lng,
  20164. rule: pluralExtensions.rules[parts[0]]
  20165. };
  20166. }
  20167. },
  20168. needsPlural: function(lng, count) {
  20169. var parts = lng.split('-');
  20170. var ext;
  20171. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  20172. ext = pluralExtensions.currentRule.rule;
  20173. } else {
  20174. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  20175. }
  20176. if (ext && ext.numbers.length <= 1) {
  20177. return false;
  20178. } else {
  20179. return this.get(lng, count) !== 1;
  20180. }
  20181. },
  20182. get: function(lng, count) {
  20183. var parts = lng.split('-');
  20184. function getResult(l, c) {
  20185. var ext;
  20186. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  20187. ext = pluralExtensions.currentRule.rule;
  20188. } else {
  20189. ext = pluralExtensions.rules[l];
  20190. }
  20191. if (ext) {
  20192. var i;
  20193. if (ext.noAbs) {
  20194. i = ext.plurals(c);
  20195. } else {
  20196. i = ext.plurals(Math.abs(c));
  20197. }
  20198. var number = ext.numbers[i];
  20199. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  20200. if (number === 2) {
  20201. number = -1; // regular plural
  20202. } else if (number === 1) {
  20203. number = 1; // singular
  20204. }
  20205. }//console.log(count + '-' + number);
  20206. return number;
  20207. } else {
  20208. return c === 1 ? '1' : '-1';
  20209. }
  20210. }
  20211. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  20212. }
  20213. };
  20214. var postProcessors = {};
  20215. var addPostProcessor = function(name, fc) {
  20216. postProcessors[name] = fc;
  20217. };
  20218. // sprintf support
  20219. var sprintf = (function() {
  20220. function get_type(variable) {
  20221. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  20222. }
  20223. function str_repeat(input, multiplier) {
  20224. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  20225. return output.join('');
  20226. }
  20227. var str_format = function() {
  20228. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  20229. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  20230. }
  20231. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  20232. };
  20233. str_format.format = function(parse_tree, argv) {
  20234. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  20235. for (i = 0; i < tree_length; i++) {
  20236. node_type = get_type(parse_tree[i]);
  20237. if (node_type === 'string') {
  20238. output.push(parse_tree[i]);
  20239. }
  20240. else if (node_type === 'array') {
  20241. match = parse_tree[i]; // convenience purposes only
  20242. if (match[2]) { // keyword argument
  20243. arg = argv[cursor];
  20244. for (k = 0; k < match[2].length; k++) {
  20245. if (!arg.hasOwnProperty(match[2][k])) {
  20246. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  20247. }
  20248. arg = arg[match[2][k]];
  20249. }
  20250. }
  20251. else if (match[1]) { // positional argument (explicit)
  20252. arg = argv[match[1]];
  20253. }
  20254. else { // positional argument (implicit)
  20255. arg = argv[cursor++];
  20256. }
  20257. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  20258. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  20259. }
  20260. switch (match[8]) {
  20261. case 'b': arg = arg.toString(2); break;
  20262. case 'c': arg = String.fromCharCode(arg); break;
  20263. case 'd': arg = parseInt(arg, 10); break;
  20264. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  20265. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  20266. case 'o': arg = arg.toString(8); break;
  20267. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  20268. case 'u': arg = Math.abs(arg); break;
  20269. case 'x': arg = arg.toString(16); break;
  20270. case 'X': arg = arg.toString(16).toUpperCase(); break;
  20271. }
  20272. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  20273. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  20274. pad_length = match[6] - String(arg).length;
  20275. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  20276. output.push(match[5] ? arg + pad : pad + arg);
  20277. }
  20278. }
  20279. return output.join('');
  20280. };
  20281. str_format.cache = {};
  20282. str_format.parse = function(fmt) {
  20283. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  20284. while (_fmt) {
  20285. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  20286. parse_tree.push(match[0]);
  20287. }
  20288. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  20289. parse_tree.push('%');
  20290. }
  20291. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  20292. if (match[2]) {
  20293. arg_names |= 1;
  20294. var field_list = [], replacement_field = match[2], field_match = [];
  20295. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  20296. field_list.push(field_match[1]);
  20297. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  20298. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  20299. field_list.push(field_match[1]);
  20300. }
  20301. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  20302. field_list.push(field_match[1]);
  20303. }
  20304. else {
  20305. throw('[sprintf] huh?');
  20306. }
  20307. }
  20308. }
  20309. else {
  20310. throw('[sprintf] huh?');
  20311. }
  20312. match[2] = field_list;
  20313. }
  20314. else {
  20315. arg_names |= 2;
  20316. }
  20317. if (arg_names === 3) {
  20318. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  20319. }
  20320. parse_tree.push(match);
  20321. }
  20322. else {
  20323. throw('[sprintf] huh?');
  20324. }
  20325. _fmt = _fmt.substring(match[0].length);
  20326. }
  20327. return parse_tree;
  20328. };
  20329. return str_format;
  20330. })();
  20331. var vsprintf = function(fmt, argv) {
  20332. argv.unshift(fmt);
  20333. return sprintf.apply(null, argv);
  20334. };
  20335. addPostProcessor("sprintf", function(val, key, opts) {
  20336. if (!opts.sprintf) return val;
  20337. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  20338. return vsprintf(val, opts.sprintf);
  20339. } else if (typeof opts.sprintf === 'object') {
  20340. return sprintf(val, opts.sprintf);
  20341. }
  20342. return val;
  20343. });
  20344. // public api interface
  20345. i18n.init = init;
  20346. i18n.setLng = setLng;
  20347. i18n.preload = preload;
  20348. i18n.addResourceBundle = addResourceBundle;
  20349. i18n.hasResourceBundle = hasResourceBundle;
  20350. i18n.addResource = addResource;
  20351. i18n.addResources = addResources;
  20352. i18n.removeResourceBundle = removeResourceBundle;
  20353. i18n.loadNamespace = loadNamespace;
  20354. i18n.loadNamespaces = loadNamespaces;
  20355. i18n.setDefaultNamespace = setDefaultNamespace;
  20356. i18n.t = translate;
  20357. i18n.translate = translate;
  20358. i18n.exists = exists;
  20359. i18n.detectLanguage = f.detectLanguage;
  20360. i18n.pluralExtensions = pluralExtensions;
  20361. i18n.sync = sync;
  20362. i18n.functions = f;
  20363. i18n.lng = lng;
  20364. i18n.addPostProcessor = addPostProcessor;
  20365. i18n.options = o;
  20366. })();
  20367. },{"jquery":"jquery"}],76:[function(require,module,exports){
  20368. /*
  20369. A JavaScript implementation of the SHA family of hashes, as
  20370. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  20371. as defined in FIPS PUB 198a
  20372. Copyright Brian Turek 2008-2013
  20373. Distributed under the BSD License
  20374. See http://caligatio.github.com/jsSHA/ for more information
  20375. Several functions taken from Paul Johnston
  20376. */
  20377. (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"!==
  20378. 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";
  20379. 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"===
  20380. 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|
  20381. (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,
  20382. 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,
  20383. 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=
  20384. {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):
  20385. 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,
  20386. 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>>>
  20387. 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>>>
  20388. 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>>>
  20389. 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-
  20390. 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,
  20391. 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,
  20392. 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],
  20393. 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),
  20394. 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),
  20395. 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,
  20396. 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,
  20397. 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?
  20398. 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,
  20399. 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);
  20400. },{}],77:[function(require,module,exports){
  20401. // Top level file is just a mixin of submodules & constants
  20402. 'use strict';
  20403. var assign = require('./lib/utils/common').assign;
  20404. var deflate = require('./lib/deflate');
  20405. var inflate = require('./lib/inflate');
  20406. var constants = require('./lib/zlib/constants');
  20407. var pako = {};
  20408. assign(pako, deflate, inflate, constants);
  20409. module.exports = pako;
  20410. },{"./lib/deflate":78,"./lib/inflate":79,"./lib/utils/common":80,"./lib/zlib/constants":83}],78:[function(require,module,exports){
  20411. 'use strict';
  20412. var zlib_deflate = require('./zlib/deflate.js');
  20413. var utils = require('./utils/common');
  20414. var strings = require('./utils/strings');
  20415. var msg = require('./zlib/messages');
  20416. var zstream = require('./zlib/zstream');
  20417. var toString = Object.prototype.toString;
  20418. /* Public constants ==========================================================*/
  20419. /* ===========================================================================*/
  20420. var Z_NO_FLUSH = 0;
  20421. var Z_FINISH = 4;
  20422. var Z_OK = 0;
  20423. var Z_STREAM_END = 1;
  20424. var Z_SYNC_FLUSH = 2;
  20425. var Z_DEFAULT_COMPRESSION = -1;
  20426. var Z_DEFAULT_STRATEGY = 0;
  20427. var Z_DEFLATED = 8;
  20428. /* ===========================================================================*/
  20429. /**
  20430. * class Deflate
  20431. *
  20432. * Generic JS-style wrapper for zlib calls. If you don't need
  20433. * streaming behaviour - use more simple functions: [[deflate]],
  20434. * [[deflateRaw]] and [[gzip]].
  20435. **/
  20436. /* internal
  20437. * Deflate.chunks -> Array
  20438. *
  20439. * Chunks of output data, if [[Deflate#onData]] not overriden.
  20440. **/
  20441. /**
  20442. * Deflate.result -> Uint8Array|Array
  20443. *
  20444. * Compressed result, generated by default [[Deflate#onData]]
  20445. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  20446. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  20447. * push a chunk with explicit flush (call [[Deflate#push]] with
  20448. * `Z_SYNC_FLUSH` param).
  20449. **/
  20450. /**
  20451. * Deflate.err -> Number
  20452. *
  20453. * Error code after deflate finished. 0 (Z_OK) on success.
  20454. * You will not need it in real life, because deflate errors
  20455. * are possible only on wrong options or bad `onData` / `onEnd`
  20456. * custom handlers.
  20457. **/
  20458. /**
  20459. * Deflate.msg -> String
  20460. *
  20461. * Error message, if [[Deflate.err]] != 0
  20462. **/
  20463. /**
  20464. * new Deflate(options)
  20465. * - options (Object): zlib deflate options.
  20466. *
  20467. * Creates new deflator instance with specified params. Throws exception
  20468. * on bad params. Supported options:
  20469. *
  20470. * - `level`
  20471. * - `windowBits`
  20472. * - `memLevel`
  20473. * - `strategy`
  20474. *
  20475. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20476. * for more information on these.
  20477. *
  20478. * Additional options, for internal needs:
  20479. *
  20480. * - `chunkSize` - size of generated data chunks (16K by default)
  20481. * - `raw` (Boolean) - do raw deflate
  20482. * - `gzip` (Boolean) - create gzip wrapper
  20483. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20484. * (each char code [0..255])
  20485. * - `header` (Object) - custom header for gzip
  20486. * - `text` (Boolean) - true if compressed data believed to be text
  20487. * - `time` (Number) - modification time, unix timestamp
  20488. * - `os` (Number) - operation system code
  20489. * - `extra` (Array) - array of bytes with extra data (max 65536)
  20490. * - `name` (String) - file name (binary string)
  20491. * - `comment` (String) - comment (binary string)
  20492. * - `hcrc` (Boolean) - true if header crc should be added
  20493. *
  20494. * ##### Example:
  20495. *
  20496. * ```javascript
  20497. * var pako = require('pako')
  20498. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20499. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20500. *
  20501. * var deflate = new pako.Deflate({ level: 3});
  20502. *
  20503. * deflate.push(chunk1, false);
  20504. * deflate.push(chunk2, true); // true -> last chunk
  20505. *
  20506. * if (deflate.err) { throw new Error(deflate.err); }
  20507. *
  20508. * console.log(deflate.result);
  20509. * ```
  20510. **/
  20511. var Deflate = function(options) {
  20512. this.options = utils.assign({
  20513. level: Z_DEFAULT_COMPRESSION,
  20514. method: Z_DEFLATED,
  20515. chunkSize: 16384,
  20516. windowBits: 15,
  20517. memLevel: 8,
  20518. strategy: Z_DEFAULT_STRATEGY,
  20519. to: ''
  20520. }, options || {});
  20521. var opt = this.options;
  20522. if (opt.raw && (opt.windowBits > 0)) {
  20523. opt.windowBits = -opt.windowBits;
  20524. }
  20525. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  20526. opt.windowBits += 16;
  20527. }
  20528. this.err = 0; // error code, if happens (0 = Z_OK)
  20529. this.msg = ''; // error message
  20530. this.ended = false; // used to avoid multiple onEnd() calls
  20531. this.chunks = []; // chunks of compressed data
  20532. this.strm = new zstream();
  20533. this.strm.avail_out = 0;
  20534. var status = zlib_deflate.deflateInit2(
  20535. this.strm,
  20536. opt.level,
  20537. opt.method,
  20538. opt.windowBits,
  20539. opt.memLevel,
  20540. opt.strategy
  20541. );
  20542. if (status !== Z_OK) {
  20543. throw new Error(msg[status]);
  20544. }
  20545. if (opt.header) {
  20546. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  20547. }
  20548. };
  20549. /**
  20550. * Deflate#push(data[, mode]) -> Boolean
  20551. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  20552. * converted to utf8 byte sequence.
  20553. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20554. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20555. *
  20556. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  20557. * new compressed chunks. Returns `true` on success. The last data block must have
  20558. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20559. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20560. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  20561. *
  20562. * On fail call [[Deflate#onEnd]] with error code and return false.
  20563. *
  20564. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20565. * array format is detected automatically). Also, don't skip last param and always
  20566. * use the same type in your code (boolean or number). That will improve JS speed.
  20567. *
  20568. * For regular `Array`-s make sure all elements are [0..255].
  20569. *
  20570. * ##### Example
  20571. *
  20572. * ```javascript
  20573. * push(chunk, false); // push one of data chunks
  20574. * ...
  20575. * push(chunk, true); // push last chunk
  20576. * ```
  20577. **/
  20578. Deflate.prototype.push = function(data, mode) {
  20579. var strm = this.strm;
  20580. var chunkSize = this.options.chunkSize;
  20581. var status, _mode;
  20582. if (this.ended) { return false; }
  20583. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  20584. // Convert data if needed
  20585. if (typeof data === 'string') {
  20586. // If we need to compress text, change encoding to utf8.
  20587. strm.input = strings.string2buf(data);
  20588. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20589. strm.input = new Uint8Array(data);
  20590. } else {
  20591. strm.input = data;
  20592. }
  20593. strm.next_in = 0;
  20594. strm.avail_in = strm.input.length;
  20595. do {
  20596. if (strm.avail_out === 0) {
  20597. strm.output = new utils.Buf8(chunkSize);
  20598. strm.next_out = 0;
  20599. strm.avail_out = chunkSize;
  20600. }
  20601. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  20602. if (status !== Z_STREAM_END && status !== Z_OK) {
  20603. this.onEnd(status);
  20604. this.ended = true;
  20605. return false;
  20606. }
  20607. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  20608. if (this.options.to === 'string') {
  20609. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  20610. } else {
  20611. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20612. }
  20613. }
  20614. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  20615. // Finalize on the last chunk.
  20616. if (_mode === Z_FINISH) {
  20617. status = zlib_deflate.deflateEnd(this.strm);
  20618. this.onEnd(status);
  20619. this.ended = true;
  20620. return status === Z_OK;
  20621. }
  20622. // callback interim results if Z_SYNC_FLUSH.
  20623. if (_mode === Z_SYNC_FLUSH) {
  20624. this.onEnd(Z_OK);
  20625. strm.avail_out = 0;
  20626. return true;
  20627. }
  20628. return true;
  20629. };
  20630. /**
  20631. * Deflate#onData(chunk) -> Void
  20632. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20633. * on js engine support. When string output requested, each chunk
  20634. * will be string.
  20635. *
  20636. * By default, stores data blocks in `chunks[]` property and glue
  20637. * those in `onEnd`. Override this handler, if you need another behaviour.
  20638. **/
  20639. Deflate.prototype.onData = function(chunk) {
  20640. this.chunks.push(chunk);
  20641. };
  20642. /**
  20643. * Deflate#onEnd(status) -> Void
  20644. * - status (Number): deflate status. 0 (Z_OK) on success,
  20645. * other if not.
  20646. *
  20647. * Called once after you tell deflate that the input stream is
  20648. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20649. * or if an error happened. By default - join collected chunks,
  20650. * free memory and fill `results` / `err` properties.
  20651. **/
  20652. Deflate.prototype.onEnd = function(status) {
  20653. // On success - join
  20654. if (status === Z_OK) {
  20655. if (this.options.to === 'string') {
  20656. this.result = this.chunks.join('');
  20657. } else {
  20658. this.result = utils.flattenChunks(this.chunks);
  20659. }
  20660. }
  20661. this.chunks = [];
  20662. this.err = status;
  20663. this.msg = this.strm.msg;
  20664. };
  20665. /**
  20666. * deflate(data[, options]) -> Uint8Array|Array|String
  20667. * - data (Uint8Array|Array|String): input data to compress.
  20668. * - options (Object): zlib deflate options.
  20669. *
  20670. * Compress `data` with deflate alrorythm and `options`.
  20671. *
  20672. * Supported options are:
  20673. *
  20674. * - level
  20675. * - windowBits
  20676. * - memLevel
  20677. * - strategy
  20678. *
  20679. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20680. * for more information on these.
  20681. *
  20682. * Sugar (options):
  20683. *
  20684. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20685. * negative windowBits implicitly.
  20686. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20687. * (each char code [0..255])
  20688. *
  20689. * ##### Example:
  20690. *
  20691. * ```javascript
  20692. * var pako = require('pako')
  20693. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  20694. *
  20695. * console.log(pako.deflate(data));
  20696. * ```
  20697. **/
  20698. function deflate(input, options) {
  20699. var deflator = new Deflate(options);
  20700. deflator.push(input, true);
  20701. // That will never happens, if you don't cheat with options :)
  20702. if (deflator.err) { throw deflator.msg; }
  20703. return deflator.result;
  20704. }
  20705. /**
  20706. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  20707. * - data (Uint8Array|Array|String): input data to compress.
  20708. * - options (Object): zlib deflate options.
  20709. *
  20710. * The same as [[deflate]], but creates raw data, without wrapper
  20711. * (header and adler32 crc).
  20712. **/
  20713. function deflateRaw(input, options) {
  20714. options = options || {};
  20715. options.raw = true;
  20716. return deflate(input, options);
  20717. }
  20718. /**
  20719. * gzip(data[, options]) -> Uint8Array|Array|String
  20720. * - data (Uint8Array|Array|String): input data to compress.
  20721. * - options (Object): zlib deflate options.
  20722. *
  20723. * The same as [[deflate]], but create gzip wrapper instead of
  20724. * deflate one.
  20725. **/
  20726. function gzip(input, options) {
  20727. options = options || {};
  20728. options.gzip = true;
  20729. return deflate(input, options);
  20730. }
  20731. exports.Deflate = Deflate;
  20732. exports.deflate = deflate;
  20733. exports.deflateRaw = deflateRaw;
  20734. exports.gzip = gzip;
  20735. },{"./utils/common":80,"./utils/strings":81,"./zlib/deflate.js":85,"./zlib/messages":90,"./zlib/zstream":92}],79:[function(require,module,exports){
  20736. 'use strict';
  20737. var zlib_inflate = require('./zlib/inflate.js');
  20738. var utils = require('./utils/common');
  20739. var strings = require('./utils/strings');
  20740. var c = require('./zlib/constants');
  20741. var msg = require('./zlib/messages');
  20742. var zstream = require('./zlib/zstream');
  20743. var gzheader = require('./zlib/gzheader');
  20744. var toString = Object.prototype.toString;
  20745. /**
  20746. * class Inflate
  20747. *
  20748. * Generic JS-style wrapper for zlib calls. If you don't need
  20749. * streaming behaviour - use more simple functions: [[inflate]]
  20750. * and [[inflateRaw]].
  20751. **/
  20752. /* internal
  20753. * inflate.chunks -> Array
  20754. *
  20755. * Chunks of output data, if [[Inflate#onData]] not overriden.
  20756. **/
  20757. /**
  20758. * Inflate.result -> Uint8Array|Array|String
  20759. *
  20760. * Uncompressed result, generated by default [[Inflate#onData]]
  20761. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  20762. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  20763. * push a chunk with explicit flush (call [[Inflate#push]] with
  20764. * `Z_SYNC_FLUSH` param).
  20765. **/
  20766. /**
  20767. * Inflate.err -> Number
  20768. *
  20769. * Error code after inflate finished. 0 (Z_OK) on success.
  20770. * Should be checked if broken data possible.
  20771. **/
  20772. /**
  20773. * Inflate.msg -> String
  20774. *
  20775. * Error message, if [[Inflate.err]] != 0
  20776. **/
  20777. /**
  20778. * new Inflate(options)
  20779. * - options (Object): zlib inflate options.
  20780. *
  20781. * Creates new inflator instance with specified params. Throws exception
  20782. * on bad params. Supported options:
  20783. *
  20784. * - `windowBits`
  20785. *
  20786. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20787. * for more information on these.
  20788. *
  20789. * Additional options, for internal needs:
  20790. *
  20791. * - `chunkSize` - size of generated data chunks (16K by default)
  20792. * - `raw` (Boolean) - do raw inflate
  20793. * - `to` (String) - if equal to 'string', then result will be converted
  20794. * from utf8 to utf16 (javascript) string. When string output requested,
  20795. * chunk length can differ from `chunkSize`, depending on content.
  20796. *
  20797. * By default, when no options set, autodetect deflate/gzip data format via
  20798. * wrapper header.
  20799. *
  20800. * ##### Example:
  20801. *
  20802. * ```javascript
  20803. * var pako = require('pako')
  20804. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20805. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20806. *
  20807. * var inflate = new pako.Inflate({ level: 3});
  20808. *
  20809. * inflate.push(chunk1, false);
  20810. * inflate.push(chunk2, true); // true -> last chunk
  20811. *
  20812. * if (inflate.err) { throw new Error(inflate.err); }
  20813. *
  20814. * console.log(inflate.result);
  20815. * ```
  20816. **/
  20817. var Inflate = function(options) {
  20818. this.options = utils.assign({
  20819. chunkSize: 16384,
  20820. windowBits: 0,
  20821. to: ''
  20822. }, options || {});
  20823. var opt = this.options;
  20824. // Force window size for `raw` data, if not set directly,
  20825. // because we have no header for autodetect.
  20826. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  20827. opt.windowBits = -opt.windowBits;
  20828. if (opt.windowBits === 0) { opt.windowBits = -15; }
  20829. }
  20830. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  20831. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  20832. !(options && options.windowBits)) {
  20833. opt.windowBits += 32;
  20834. }
  20835. // Gzip header has no info about windows size, we can do autodetect only
  20836. // for deflate. So, if window size not set, force it to max when gzip possible
  20837. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  20838. // bit 3 (16) -> gzipped data
  20839. // bit 4 (32) -> autodetect gzip/deflate
  20840. if ((opt.windowBits & 15) === 0) {
  20841. opt.windowBits |= 15;
  20842. }
  20843. }
  20844. this.err = 0; // error code, if happens (0 = Z_OK)
  20845. this.msg = ''; // error message
  20846. this.ended = false; // used to avoid multiple onEnd() calls
  20847. this.chunks = []; // chunks of compressed data
  20848. this.strm = new zstream();
  20849. this.strm.avail_out = 0;
  20850. var status = zlib_inflate.inflateInit2(
  20851. this.strm,
  20852. opt.windowBits
  20853. );
  20854. if (status !== c.Z_OK) {
  20855. throw new Error(msg[status]);
  20856. }
  20857. this.header = new gzheader();
  20858. zlib_inflate.inflateGetHeader(this.strm, this.header);
  20859. };
  20860. /**
  20861. * Inflate#push(data[, mode]) -> Boolean
  20862. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  20863. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20864. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20865. *
  20866. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  20867. * new output chunks. Returns `true` on success. The last data block must have
  20868. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20869. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20870. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  20871. *
  20872. * On fail call [[Inflate#onEnd]] with error code and return false.
  20873. *
  20874. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20875. * format is detected automatically). Also, don't skip last param and always
  20876. * use the same type in your code (boolean or number). That will improve JS speed.
  20877. *
  20878. * For regular `Array`-s make sure all elements are [0..255].
  20879. *
  20880. * ##### Example
  20881. *
  20882. * ```javascript
  20883. * push(chunk, false); // push one of data chunks
  20884. * ...
  20885. * push(chunk, true); // push last chunk
  20886. * ```
  20887. **/
  20888. Inflate.prototype.push = function(data, mode) {
  20889. var strm = this.strm;
  20890. var chunkSize = this.options.chunkSize;
  20891. var status, _mode;
  20892. var next_out_utf8, tail, utf8str;
  20893. if (this.ended) { return false; }
  20894. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  20895. // Convert data if needed
  20896. if (typeof data === 'string') {
  20897. // Only binary strings can be decompressed on practice
  20898. strm.input = strings.binstring2buf(data);
  20899. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20900. strm.input = new Uint8Array(data);
  20901. } else {
  20902. strm.input = data;
  20903. }
  20904. strm.next_in = 0;
  20905. strm.avail_in = strm.input.length;
  20906. do {
  20907. if (strm.avail_out === 0) {
  20908. strm.output = new utils.Buf8(chunkSize);
  20909. strm.next_out = 0;
  20910. strm.avail_out = chunkSize;
  20911. }
  20912. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20913. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20914. this.onEnd(status);
  20915. this.ended = true;
  20916. return false;
  20917. }
  20918. if (strm.next_out) {
  20919. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20920. if (this.options.to === 'string') {
  20921. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20922. tail = strm.next_out - next_out_utf8;
  20923. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20924. // move tail
  20925. strm.next_out = tail;
  20926. strm.avail_out = chunkSize - tail;
  20927. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20928. this.onData(utf8str);
  20929. } else {
  20930. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20931. }
  20932. }
  20933. }
  20934. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20935. if (status === c.Z_STREAM_END) {
  20936. _mode = c.Z_FINISH;
  20937. }
  20938. // Finalize on the last chunk.
  20939. if (_mode === c.Z_FINISH) {
  20940. status = zlib_inflate.inflateEnd(this.strm);
  20941. this.onEnd(status);
  20942. this.ended = true;
  20943. return status === c.Z_OK;
  20944. }
  20945. // callback interim results if Z_SYNC_FLUSH.
  20946. if (_mode === c.Z_SYNC_FLUSH) {
  20947. this.onEnd(c.Z_OK);
  20948. strm.avail_out = 0;
  20949. return true;
  20950. }
  20951. return true;
  20952. };
  20953. /**
  20954. * Inflate#onData(chunk) -> Void
  20955. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20956. * on js engine support. When string output requested, each chunk
  20957. * will be string.
  20958. *
  20959. * By default, stores data blocks in `chunks[]` property and glue
  20960. * those in `onEnd`. Override this handler, if you need another behaviour.
  20961. **/
  20962. Inflate.prototype.onData = function(chunk) {
  20963. this.chunks.push(chunk);
  20964. };
  20965. /**
  20966. * Inflate#onEnd(status) -> Void
  20967. * - status (Number): inflate status. 0 (Z_OK) on success,
  20968. * other if not.
  20969. *
  20970. * Called either after you tell inflate that the input stream is
  20971. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20972. * or if an error happened. By default - join collected chunks,
  20973. * free memory and fill `results` / `err` properties.
  20974. **/
  20975. Inflate.prototype.onEnd = function(status) {
  20976. // On success - join
  20977. if (status === c.Z_OK) {
  20978. if (this.options.to === 'string') {
  20979. // Glue & convert here, until we teach pako to send
  20980. // utf8 alligned strings to onData
  20981. this.result = this.chunks.join('');
  20982. } else {
  20983. this.result = utils.flattenChunks(this.chunks);
  20984. }
  20985. }
  20986. this.chunks = [];
  20987. this.err = status;
  20988. this.msg = this.strm.msg;
  20989. };
  20990. /**
  20991. * inflate(data[, options]) -> Uint8Array|Array|String
  20992. * - data (Uint8Array|Array|String): input data to decompress.
  20993. * - options (Object): zlib inflate options.
  20994. *
  20995. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20996. * format via wrapper header by default. That's why we don't provide
  20997. * separate `ungzip` method.
  20998. *
  20999. * Supported options are:
  21000. *
  21001. * - windowBits
  21002. *
  21003. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  21004. * for more information.
  21005. *
  21006. * Sugar (options):
  21007. *
  21008. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  21009. * negative windowBits implicitly.
  21010. * - `to` (String) - if equal to 'string', then result will be converted
  21011. * from utf8 to utf16 (javascript) string. When string output requested,
  21012. * chunk length can differ from `chunkSize`, depending on content.
  21013. *
  21014. *
  21015. * ##### Example:
  21016. *
  21017. * ```javascript
  21018. * var pako = require('pako')
  21019. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  21020. * , output;
  21021. *
  21022. * try {
  21023. * output = pako.inflate(input);
  21024. * } catch (err)
  21025. * console.log(err);
  21026. * }
  21027. * ```
  21028. **/
  21029. function inflate(input, options) {
  21030. var inflator = new Inflate(options);
  21031. inflator.push(input, true);
  21032. // That will never happens, if you don't cheat with options :)
  21033. if (inflator.err) { throw inflator.msg; }
  21034. return inflator.result;
  21035. }
  21036. /**
  21037. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  21038. * - data (Uint8Array|Array|String): input data to decompress.
  21039. * - options (Object): zlib inflate options.
  21040. *
  21041. * The same as [[inflate]], but creates raw data, without wrapper
  21042. * (header and adler32 crc).
  21043. **/
  21044. function inflateRaw(input, options) {
  21045. options = options || {};
  21046. options.raw = true;
  21047. return inflate(input, options);
  21048. }
  21049. /**
  21050. * ungzip(data[, options]) -> Uint8Array|Array|String
  21051. * - data (Uint8Array|Array|String): input data to decompress.
  21052. * - options (Object): zlib inflate options.
  21053. *
  21054. * Just shortcut to [[inflate]], because it autodetects format
  21055. * by header.content. Done for convenience.
  21056. **/
  21057. exports.Inflate = Inflate;
  21058. exports.inflate = inflate;
  21059. exports.inflateRaw = inflateRaw;
  21060. exports.ungzip = inflate;
  21061. },{"./utils/common":80,"./utils/strings":81,"./zlib/constants":83,"./zlib/gzheader":86,"./zlib/inflate.js":88,"./zlib/messages":90,"./zlib/zstream":92}],80:[function(require,module,exports){
  21062. 'use strict';
  21063. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  21064. (typeof Uint16Array !== 'undefined') &&
  21065. (typeof Int32Array !== 'undefined');
  21066. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  21067. var sources = Array.prototype.slice.call(arguments, 1);
  21068. while (sources.length) {
  21069. var source = sources.shift();
  21070. if (!source) { continue; }
  21071. if (typeof source !== 'object') {
  21072. throw new TypeError(source + 'must be non-object');
  21073. }
  21074. for (var p in source) {
  21075. if (source.hasOwnProperty(p)) {
  21076. obj[p] = source[p];
  21077. }
  21078. }
  21079. }
  21080. return obj;
  21081. };
  21082. // reduce buffer size, avoiding mem copy
  21083. exports.shrinkBuf = function (buf, size) {
  21084. if (buf.length === size) { return buf; }
  21085. if (buf.subarray) { return buf.subarray(0, size); }
  21086. buf.length = size;
  21087. return buf;
  21088. };
  21089. var fnTyped = {
  21090. arraySet: function (dest, src, src_offs, len, dest_offs) {
  21091. if (src.subarray && dest.subarray) {
  21092. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  21093. return;
  21094. }
  21095. // Fallback to ordinary array
  21096. for (var i=0; i<len; i++) {
  21097. dest[dest_offs + i] = src[src_offs + i];
  21098. }
  21099. },
  21100. // Join array of chunks to single array.
  21101. flattenChunks: function(chunks) {
  21102. var i, l, len, pos, chunk, result;
  21103. // calculate data length
  21104. len = 0;
  21105. for (i=0, l=chunks.length; i<l; i++) {
  21106. len += chunks[i].length;
  21107. }
  21108. // join chunks
  21109. result = new Uint8Array(len);
  21110. pos = 0;
  21111. for (i=0, l=chunks.length; i<l; i++) {
  21112. chunk = chunks[i];
  21113. result.set(chunk, pos);
  21114. pos += chunk.length;
  21115. }
  21116. return result;
  21117. }
  21118. };
  21119. var fnUntyped = {
  21120. arraySet: function (dest, src, src_offs, len, dest_offs) {
  21121. for (var i=0; i<len; i++) {
  21122. dest[dest_offs + i] = src[src_offs + i];
  21123. }
  21124. },
  21125. // Join array of chunks to single array.
  21126. flattenChunks: function(chunks) {
  21127. return [].concat.apply([], chunks);
  21128. }
  21129. };
  21130. // Enable/Disable typed arrays use, for testing
  21131. //
  21132. exports.setTyped = function (on) {
  21133. if (on) {
  21134. exports.Buf8 = Uint8Array;
  21135. exports.Buf16 = Uint16Array;
  21136. exports.Buf32 = Int32Array;
  21137. exports.assign(exports, fnTyped);
  21138. } else {
  21139. exports.Buf8 = Array;
  21140. exports.Buf16 = Array;
  21141. exports.Buf32 = Array;
  21142. exports.assign(exports, fnUntyped);
  21143. }
  21144. };
  21145. exports.setTyped(TYPED_OK);
  21146. },{}],81:[function(require,module,exports){
  21147. // String encode/decode helpers
  21148. 'use strict';
  21149. var utils = require('./common');
  21150. // Quick check if we can use fast array to bin string conversion
  21151. //
  21152. // - apply(Array) can fail on Android 2.2
  21153. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  21154. //
  21155. var STR_APPLY_OK = true;
  21156. var STR_APPLY_UIA_OK = true;
  21157. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  21158. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  21159. // Table with utf8 lengths (calculated by first byte of sequence)
  21160. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  21161. // because max possible codepoint is 0x10ffff
  21162. var _utf8len = new utils.Buf8(256);
  21163. for (var q=0; q<256; q++) {
  21164. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  21165. }
  21166. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  21167. // convert string to array (typed, when possible)
  21168. exports.string2buf = function (str) {
  21169. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  21170. // count binary size
  21171. for (m_pos = 0; m_pos < str_len; m_pos++) {
  21172. c = str.charCodeAt(m_pos);
  21173. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  21174. c2 = str.charCodeAt(m_pos+1);
  21175. if ((c2 & 0xfc00) === 0xdc00) {
  21176. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  21177. m_pos++;
  21178. }
  21179. }
  21180. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  21181. }
  21182. // allocate buffer
  21183. buf = new utils.Buf8(buf_len);
  21184. // convert
  21185. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  21186. c = str.charCodeAt(m_pos);
  21187. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  21188. c2 = str.charCodeAt(m_pos+1);
  21189. if ((c2 & 0xfc00) === 0xdc00) {
  21190. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  21191. m_pos++;
  21192. }
  21193. }
  21194. if (c < 0x80) {
  21195. /* one byte */
  21196. buf[i++] = c;
  21197. } else if (c < 0x800) {
  21198. /* two bytes */
  21199. buf[i++] = 0xC0 | (c >>> 6);
  21200. buf[i++] = 0x80 | (c & 0x3f);
  21201. } else if (c < 0x10000) {
  21202. /* three bytes */
  21203. buf[i++] = 0xE0 | (c >>> 12);
  21204. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  21205. buf[i++] = 0x80 | (c & 0x3f);
  21206. } else {
  21207. /* four bytes */
  21208. buf[i++] = 0xf0 | (c >>> 18);
  21209. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  21210. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  21211. buf[i++] = 0x80 | (c & 0x3f);
  21212. }
  21213. }
  21214. return buf;
  21215. };
  21216. // Helper (used in 2 places)
  21217. function buf2binstring(buf, len) {
  21218. // use fallback for big arrays to avoid stack overflow
  21219. if (len < 65537) {
  21220. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  21221. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  21222. }
  21223. }
  21224. var result = '';
  21225. for (var i=0; i < len; i++) {
  21226. result += String.fromCharCode(buf[i]);
  21227. }
  21228. return result;
  21229. }
  21230. // Convert byte array to binary string
  21231. exports.buf2binstring = function(buf) {
  21232. return buf2binstring(buf, buf.length);
  21233. };
  21234. // Convert binary string (typed, when possible)
  21235. exports.binstring2buf = function(str) {
  21236. var buf = new utils.Buf8(str.length);
  21237. for (var i=0, len=buf.length; i < len; i++) {
  21238. buf[i] = str.charCodeAt(i);
  21239. }
  21240. return buf;
  21241. };
  21242. // convert array to string
  21243. exports.buf2string = function (buf, max) {
  21244. var i, out, c, c_len;
  21245. var len = max || buf.length;
  21246. // Reserve max possible length (2 words per char)
  21247. // NB: by unknown reasons, Array is significantly faster for
  21248. // String.fromCharCode.apply than Uint16Array.
  21249. var utf16buf = new Array(len*2);
  21250. for (out=0, i=0; i<len;) {
  21251. c = buf[i++];
  21252. // quick process ascii
  21253. if (c < 0x80) { utf16buf[out++] = c; continue; }
  21254. c_len = _utf8len[c];
  21255. // skip 5 & 6 byte codes
  21256. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  21257. // apply mask on first byte
  21258. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  21259. // join the rest
  21260. while (c_len > 1 && i < len) {
  21261. c = (c << 6) | (buf[i++] & 0x3f);
  21262. c_len--;
  21263. }
  21264. // terminated by end of string?
  21265. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  21266. if (c < 0x10000) {
  21267. utf16buf[out++] = c;
  21268. } else {
  21269. c -= 0x10000;
  21270. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  21271. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  21272. }
  21273. }
  21274. return buf2binstring(utf16buf, out);
  21275. };
  21276. // Calculate max possible position in utf8 buffer,
  21277. // that will not break sequence. If that's not possible
  21278. // - (very small limits) return max size as is.
  21279. //
  21280. // buf[] - utf8 bytes array
  21281. // max - length limit (mandatory);
  21282. exports.utf8border = function(buf, max) {
  21283. var pos;
  21284. max = max || buf.length;
  21285. if (max > buf.length) { max = buf.length; }
  21286. // go back from last position, until start of sequence found
  21287. pos = max-1;
  21288. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  21289. // Fuckup - very small and broken sequence,
  21290. // return max, because we should return something anyway.
  21291. if (pos < 0) { return max; }
  21292. // If we came to start of buffer - that means vuffer is too small,
  21293. // return max too.
  21294. if (pos === 0) { return max; }
  21295. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  21296. };
  21297. },{"./common":80}],82:[function(require,module,exports){
  21298. 'use strict';
  21299. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  21300. // It doesn't worth to make additional optimizationa as in original.
  21301. // Small size is preferable.
  21302. function adler32(adler, buf, len, pos) {
  21303. var s1 = (adler & 0xffff) |0,
  21304. s2 = ((adler >>> 16) & 0xffff) |0,
  21305. n = 0;
  21306. while (len !== 0) {
  21307. // Set limit ~ twice less than 5552, to keep
  21308. // s2 in 31-bits, because we force signed ints.
  21309. // in other case %= will fail.
  21310. n = len > 2000 ? 2000 : len;
  21311. len -= n;
  21312. do {
  21313. s1 = (s1 + buf[pos++]) |0;
  21314. s2 = (s2 + s1) |0;
  21315. } while (--n);
  21316. s1 %= 65521;
  21317. s2 %= 65521;
  21318. }
  21319. return (s1 | (s2 << 16)) |0;
  21320. }
  21321. module.exports = adler32;
  21322. },{}],83:[function(require,module,exports){
  21323. module.exports = {
  21324. /* Allowed flush values; see deflate() and inflate() below for details */
  21325. Z_NO_FLUSH: 0,
  21326. Z_PARTIAL_FLUSH: 1,
  21327. Z_SYNC_FLUSH: 2,
  21328. Z_FULL_FLUSH: 3,
  21329. Z_FINISH: 4,
  21330. Z_BLOCK: 5,
  21331. Z_TREES: 6,
  21332. /* Return codes for the compression/decompression functions. Negative values
  21333. * are errors, positive values are used for special but normal events.
  21334. */
  21335. Z_OK: 0,
  21336. Z_STREAM_END: 1,
  21337. Z_NEED_DICT: 2,
  21338. Z_ERRNO: -1,
  21339. Z_STREAM_ERROR: -2,
  21340. Z_DATA_ERROR: -3,
  21341. //Z_MEM_ERROR: -4,
  21342. Z_BUF_ERROR: -5,
  21343. //Z_VERSION_ERROR: -6,
  21344. /* compression levels */
  21345. Z_NO_COMPRESSION: 0,
  21346. Z_BEST_SPEED: 1,
  21347. Z_BEST_COMPRESSION: 9,
  21348. Z_DEFAULT_COMPRESSION: -1,
  21349. Z_FILTERED: 1,
  21350. Z_HUFFMAN_ONLY: 2,
  21351. Z_RLE: 3,
  21352. Z_FIXED: 4,
  21353. Z_DEFAULT_STRATEGY: 0,
  21354. /* Possible values of the data_type field (though see inflate()) */
  21355. Z_BINARY: 0,
  21356. Z_TEXT: 1,
  21357. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  21358. Z_UNKNOWN: 2,
  21359. /* The deflate compression method */
  21360. Z_DEFLATED: 8
  21361. //Z_NULL: null // Use -1 or null inline, depending on var type
  21362. };
  21363. },{}],84:[function(require,module,exports){
  21364. 'use strict';
  21365. // Note: we can't get significant speed boost here.
  21366. // So write code to minimize size - no pregenerated tables
  21367. // and array tools dependencies.
  21368. // Use ordinary array, since untyped makes no boost here
  21369. function makeTable() {
  21370. var c, table = [];
  21371. for (var n =0; n < 256; n++) {
  21372. c = n;
  21373. for (var k =0; k < 8; k++) {
  21374. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  21375. }
  21376. table[n] = c;
  21377. }
  21378. return table;
  21379. }
  21380. // Create table on load. Just 255 signed longs. Not a problem.
  21381. var crcTable = makeTable();
  21382. function crc32(crc, buf, len, pos) {
  21383. var t = crcTable,
  21384. end = pos + len;
  21385. crc = crc ^ (-1);
  21386. for (var i = pos; i < end; i++) {
  21387. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  21388. }
  21389. return (crc ^ (-1)); // >>> 0;
  21390. }
  21391. module.exports = crc32;
  21392. },{}],85:[function(require,module,exports){
  21393. 'use strict';
  21394. var utils = require('../utils/common');
  21395. var trees = require('./trees');
  21396. var adler32 = require('./adler32');
  21397. var crc32 = require('./crc32');
  21398. var msg = require('./messages');
  21399. /* Public constants ==========================================================*/
  21400. /* ===========================================================================*/
  21401. /* Allowed flush values; see deflate() and inflate() below for details */
  21402. var Z_NO_FLUSH = 0;
  21403. var Z_PARTIAL_FLUSH = 1;
  21404. //var Z_SYNC_FLUSH = 2;
  21405. var Z_FULL_FLUSH = 3;
  21406. var Z_FINISH = 4;
  21407. var Z_BLOCK = 5;
  21408. //var Z_TREES = 6;
  21409. /* Return codes for the compression/decompression functions. Negative values
  21410. * are errors, positive values are used for special but normal events.
  21411. */
  21412. var Z_OK = 0;
  21413. var Z_STREAM_END = 1;
  21414. //var Z_NEED_DICT = 2;
  21415. //var Z_ERRNO = -1;
  21416. var Z_STREAM_ERROR = -2;
  21417. var Z_DATA_ERROR = -3;
  21418. //var Z_MEM_ERROR = -4;
  21419. var Z_BUF_ERROR = -5;
  21420. //var Z_VERSION_ERROR = -6;
  21421. /* compression levels */
  21422. //var Z_NO_COMPRESSION = 0;
  21423. //var Z_BEST_SPEED = 1;
  21424. //var Z_BEST_COMPRESSION = 9;
  21425. var Z_DEFAULT_COMPRESSION = -1;
  21426. var Z_FILTERED = 1;
  21427. var Z_HUFFMAN_ONLY = 2;
  21428. var Z_RLE = 3;
  21429. var Z_FIXED = 4;
  21430. var Z_DEFAULT_STRATEGY = 0;
  21431. /* Possible values of the data_type field (though see inflate()) */
  21432. //var Z_BINARY = 0;
  21433. //var Z_TEXT = 1;
  21434. //var Z_ASCII = 1; // = Z_TEXT
  21435. var Z_UNKNOWN = 2;
  21436. /* The deflate compression method */
  21437. var Z_DEFLATED = 8;
  21438. /*============================================================================*/
  21439. var MAX_MEM_LEVEL = 9;
  21440. /* Maximum value for memLevel in deflateInit2 */
  21441. var MAX_WBITS = 15;
  21442. /* 32K LZ77 window */
  21443. var DEF_MEM_LEVEL = 8;
  21444. var LENGTH_CODES = 29;
  21445. /* number of length codes, not counting the special END_BLOCK code */
  21446. var LITERALS = 256;
  21447. /* number of literal bytes 0..255 */
  21448. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21449. /* number of Literal or Length codes, including the END_BLOCK code */
  21450. var D_CODES = 30;
  21451. /* number of distance codes */
  21452. var BL_CODES = 19;
  21453. /* number of codes used to transfer the bit lengths */
  21454. var HEAP_SIZE = 2*L_CODES + 1;
  21455. /* maximum heap size */
  21456. var MAX_BITS = 15;
  21457. /* All codes must not exceed MAX_BITS bits */
  21458. var MIN_MATCH = 3;
  21459. var MAX_MATCH = 258;
  21460. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  21461. var PRESET_DICT = 0x20;
  21462. var INIT_STATE = 42;
  21463. var EXTRA_STATE = 69;
  21464. var NAME_STATE = 73;
  21465. var COMMENT_STATE = 91;
  21466. var HCRC_STATE = 103;
  21467. var BUSY_STATE = 113;
  21468. var FINISH_STATE = 666;
  21469. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  21470. var BS_BLOCK_DONE = 2; /* block flush performed */
  21471. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  21472. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  21473. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  21474. function err(strm, errorCode) {
  21475. strm.msg = msg[errorCode];
  21476. return errorCode;
  21477. }
  21478. function rank(f) {
  21479. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  21480. }
  21481. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21482. /* =========================================================================
  21483. * Flush as much pending output as possible. All deflate() output goes
  21484. * through this function so some applications may wish to modify it
  21485. * to avoid allocating a large strm->output buffer and copying into it.
  21486. * (See also read_buf()).
  21487. */
  21488. function flush_pending(strm) {
  21489. var s = strm.state;
  21490. //_tr_flush_bits(s);
  21491. var len = s.pending;
  21492. if (len > strm.avail_out) {
  21493. len = strm.avail_out;
  21494. }
  21495. if (len === 0) { return; }
  21496. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  21497. strm.next_out += len;
  21498. s.pending_out += len;
  21499. strm.total_out += len;
  21500. strm.avail_out -= len;
  21501. s.pending -= len;
  21502. if (s.pending === 0) {
  21503. s.pending_out = 0;
  21504. }
  21505. }
  21506. function flush_block_only (s, last) {
  21507. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  21508. s.block_start = s.strstart;
  21509. flush_pending(s.strm);
  21510. }
  21511. function put_byte(s, b) {
  21512. s.pending_buf[s.pending++] = b;
  21513. }
  21514. /* =========================================================================
  21515. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  21516. * IN assertion: the stream state is correct and there is enough room in
  21517. * pending_buf.
  21518. */
  21519. function putShortMSB(s, b) {
  21520. // put_byte(s, (Byte)(b >> 8));
  21521. // put_byte(s, (Byte)(b & 0xff));
  21522. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  21523. s.pending_buf[s.pending++] = b & 0xff;
  21524. }
  21525. /* ===========================================================================
  21526. * Read a new buffer from the current input stream, update the adler32
  21527. * and total number of bytes read. All deflate() input goes through
  21528. * this function so some applications may wish to modify it to avoid
  21529. * allocating a large strm->input buffer and copying from it.
  21530. * (See also flush_pending()).
  21531. */
  21532. function read_buf(strm, buf, start, size) {
  21533. var len = strm.avail_in;
  21534. if (len > size) { len = size; }
  21535. if (len === 0) { return 0; }
  21536. strm.avail_in -= len;
  21537. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  21538. if (strm.state.wrap === 1) {
  21539. strm.adler = adler32(strm.adler, buf, len, start);
  21540. }
  21541. else if (strm.state.wrap === 2) {
  21542. strm.adler = crc32(strm.adler, buf, len, start);
  21543. }
  21544. strm.next_in += len;
  21545. strm.total_in += len;
  21546. return len;
  21547. }
  21548. /* ===========================================================================
  21549. * Set match_start to the longest match starting at the given string and
  21550. * return its length. Matches shorter or equal to prev_length are discarded,
  21551. * in which case the result is equal to prev_length and match_start is
  21552. * garbage.
  21553. * IN assertions: cur_match is the head of the hash chain for the current
  21554. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  21555. * OUT assertion: the match length is not greater than s->lookahead.
  21556. */
  21557. function longest_match(s, cur_match) {
  21558. var chain_length = s.max_chain_length; /* max hash chain length */
  21559. var scan = s.strstart; /* current string */
  21560. var match; /* matched string */
  21561. var len; /* length of current match */
  21562. var best_len = s.prev_length; /* best match length so far */
  21563. var nice_match = s.nice_match; /* stop if match long enough */
  21564. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  21565. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  21566. var _win = s.window; // shortcut
  21567. var wmask = s.w_mask;
  21568. var prev = s.prev;
  21569. /* Stop when cur_match becomes <= limit. To simplify the code,
  21570. * we prevent matches with the string of window index 0.
  21571. */
  21572. var strend = s.strstart + MAX_MATCH;
  21573. var scan_end1 = _win[scan + best_len - 1];
  21574. var scan_end = _win[scan + best_len];
  21575. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  21576. * It is easy to get rid of this optimization if necessary.
  21577. */
  21578. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  21579. /* Do not waste too much time if we already have a good match: */
  21580. if (s.prev_length >= s.good_match) {
  21581. chain_length >>= 2;
  21582. }
  21583. /* Do not look for matches beyond the end of the input. This is necessary
  21584. * to make deflate deterministic.
  21585. */
  21586. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  21587. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  21588. do {
  21589. // Assert(cur_match < s->strstart, "no future");
  21590. match = cur_match;
  21591. /* Skip to next match if the match length cannot increase
  21592. * or if the match length is less than 2. Note that the checks below
  21593. * for insufficient lookahead only occur occasionally for performance
  21594. * reasons. Therefore uninitialized memory will be accessed, and
  21595. * conditional jumps will be made that depend on those values.
  21596. * However the length of the match is limited to the lookahead, so
  21597. * the output of deflate is not affected by the uninitialized values.
  21598. */
  21599. if (_win[match + best_len] !== scan_end ||
  21600. _win[match + best_len - 1] !== scan_end1 ||
  21601. _win[match] !== _win[scan] ||
  21602. _win[++match] !== _win[scan + 1]) {
  21603. continue;
  21604. }
  21605. /* The check at best_len-1 can be removed because it will be made
  21606. * again later. (This heuristic is not always a win.)
  21607. * It is not necessary to compare scan[2] and match[2] since they
  21608. * are always equal when the other bytes match, given that
  21609. * the hash keys are equal and that HASH_BITS >= 8.
  21610. */
  21611. scan += 2;
  21612. match++;
  21613. // Assert(*scan == *match, "match[2]?");
  21614. /* We check for insufficient lookahead only every 8th comparison;
  21615. * the 256th check will be made at strstart+258.
  21616. */
  21617. do {
  21618. /*jshint noempty:false*/
  21619. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21620. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21621. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21622. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21623. scan < strend);
  21624. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  21625. len = MAX_MATCH - (strend - scan);
  21626. scan = strend - MAX_MATCH;
  21627. if (len > best_len) {
  21628. s.match_start = cur_match;
  21629. best_len = len;
  21630. if (len >= nice_match) {
  21631. break;
  21632. }
  21633. scan_end1 = _win[scan + best_len - 1];
  21634. scan_end = _win[scan + best_len];
  21635. }
  21636. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  21637. if (best_len <= s.lookahead) {
  21638. return best_len;
  21639. }
  21640. return s.lookahead;
  21641. }
  21642. /* ===========================================================================
  21643. * Fill the window when the lookahead becomes insufficient.
  21644. * Updates strstart and lookahead.
  21645. *
  21646. * IN assertion: lookahead < MIN_LOOKAHEAD
  21647. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  21648. * At least one byte has been read, or avail_in == 0; reads are
  21649. * performed for at least two bytes (required for the zip translate_eol
  21650. * option -- not supported here).
  21651. */
  21652. function fill_window(s) {
  21653. var _w_size = s.w_size;
  21654. var p, n, m, more, str;
  21655. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  21656. do {
  21657. more = s.window_size - s.lookahead - s.strstart;
  21658. // JS ints have 32 bit, block below not needed
  21659. /* Deal with !@#$% 64K limit: */
  21660. //if (sizeof(int) <= 2) {
  21661. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  21662. // more = wsize;
  21663. //
  21664. // } else if (more == (unsigned)(-1)) {
  21665. // /* Very unlikely, but possible on 16 bit machine if
  21666. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  21667. // */
  21668. // more--;
  21669. // }
  21670. //}
  21671. /* If the window is almost full and there is insufficient lookahead,
  21672. * move the upper half to the lower one to make room in the upper half.
  21673. */
  21674. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  21675. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  21676. s.match_start -= _w_size;
  21677. s.strstart -= _w_size;
  21678. /* we now have strstart >= MAX_DIST */
  21679. s.block_start -= _w_size;
  21680. /* Slide the hash table (could be avoided with 32 bit values
  21681. at the expense of memory usage). We slide even when level == 0
  21682. to keep the hash table consistent if we switch back to level > 0
  21683. later. (Using level 0 permanently is not an optimal usage of
  21684. zlib, so we don't care about this pathological case.)
  21685. */
  21686. n = s.hash_size;
  21687. p = n;
  21688. do {
  21689. m = s.head[--p];
  21690. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  21691. } while (--n);
  21692. n = _w_size;
  21693. p = n;
  21694. do {
  21695. m = s.prev[--p];
  21696. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  21697. /* If n is not on any hash chain, prev[n] is garbage but
  21698. * its value will never be used.
  21699. */
  21700. } while (--n);
  21701. more += _w_size;
  21702. }
  21703. if (s.strm.avail_in === 0) {
  21704. break;
  21705. }
  21706. /* If there was no sliding:
  21707. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  21708. * more == window_size - lookahead - strstart
  21709. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  21710. * => more >= window_size - 2*WSIZE + 2
  21711. * In the BIG_MEM or MMAP case (not yet supported),
  21712. * window_size == input_size + MIN_LOOKAHEAD &&
  21713. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  21714. * Otherwise, window_size == 2*WSIZE so more >= 2.
  21715. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  21716. */
  21717. //Assert(more >= 2, "more < 2");
  21718. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  21719. s.lookahead += n;
  21720. /* Initialize the hash value now that we have some input: */
  21721. if (s.lookahead + s.insert >= MIN_MATCH) {
  21722. str = s.strstart - s.insert;
  21723. s.ins_h = s.window[str];
  21724. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  21725. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  21726. //#if MIN_MATCH != 3
  21727. // Call update_hash() MIN_MATCH-3 more times
  21728. //#endif
  21729. while (s.insert) {
  21730. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  21731. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  21732. s.prev[str & s.w_mask] = s.head[s.ins_h];
  21733. s.head[s.ins_h] = str;
  21734. str++;
  21735. s.insert--;
  21736. if (s.lookahead + s.insert < MIN_MATCH) {
  21737. break;
  21738. }
  21739. }
  21740. }
  21741. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  21742. * but this is not important since only literal bytes will be emitted.
  21743. */
  21744. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  21745. /* If the WIN_INIT bytes after the end of the current data have never been
  21746. * written, then zero those bytes in order to avoid memory check reports of
  21747. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  21748. * the longest match routines. Update the high water mark for the next
  21749. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  21750. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  21751. */
  21752. // if (s.high_water < s.window_size) {
  21753. // var curr = s.strstart + s.lookahead;
  21754. // var init = 0;
  21755. //
  21756. // if (s.high_water < curr) {
  21757. // /* Previous high water mark below current data -- zero WIN_INIT
  21758. // * bytes or up to end of window, whichever is less.
  21759. // */
  21760. // init = s.window_size - curr;
  21761. // if (init > WIN_INIT)
  21762. // init = WIN_INIT;
  21763. // zmemzero(s->window + curr, (unsigned)init);
  21764. // s->high_water = curr + init;
  21765. // }
  21766. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  21767. // /* High water mark at or above current data, but below current data
  21768. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  21769. // * to end of window, whichever is less.
  21770. // */
  21771. // init = (ulg)curr + WIN_INIT - s->high_water;
  21772. // if (init > s->window_size - s->high_water)
  21773. // init = s->window_size - s->high_water;
  21774. // zmemzero(s->window + s->high_water, (unsigned)init);
  21775. // s->high_water += init;
  21776. // }
  21777. // }
  21778. //
  21779. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  21780. // "not enough room for search");
  21781. }
  21782. /* ===========================================================================
  21783. * Copy without compression as much as possible from the input stream, return
  21784. * the current block state.
  21785. * This function does not insert new strings in the dictionary since
  21786. * uncompressible data is probably not useful. This function is used
  21787. * only for the level=0 compression option.
  21788. * NOTE: this function should be optimized to avoid extra copying from
  21789. * window to pending_buf.
  21790. */
  21791. function deflate_stored(s, flush) {
  21792. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  21793. * to pending_buf_size, and each stored block has a 5 byte header:
  21794. */
  21795. var max_block_size = 0xffff;
  21796. if (max_block_size > s.pending_buf_size - 5) {
  21797. max_block_size = s.pending_buf_size - 5;
  21798. }
  21799. /* Copy as much as possible from input to output: */
  21800. for (;;) {
  21801. /* Fill the window as much as possible: */
  21802. if (s.lookahead <= 1) {
  21803. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  21804. // s->block_start >= (long)s->w_size, "slide too late");
  21805. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  21806. // s.block_start >= s.w_size)) {
  21807. // throw new Error("slide too late");
  21808. // }
  21809. fill_window(s);
  21810. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  21811. return BS_NEED_MORE;
  21812. }
  21813. if (s.lookahead === 0) {
  21814. break;
  21815. }
  21816. /* flush the current block */
  21817. }
  21818. //Assert(s->block_start >= 0L, "block gone");
  21819. // if (s.block_start < 0) throw new Error("block gone");
  21820. s.strstart += s.lookahead;
  21821. s.lookahead = 0;
  21822. /* Emit a stored block if pending_buf will be full: */
  21823. var max_start = s.block_start + max_block_size;
  21824. if (s.strstart === 0 || s.strstart >= max_start) {
  21825. /* strstart == 0 is possible when wraparound on 16-bit machine */
  21826. s.lookahead = s.strstart - max_start;
  21827. s.strstart = max_start;
  21828. /*** FLUSH_BLOCK(s, 0); ***/
  21829. flush_block_only(s, false);
  21830. if (s.strm.avail_out === 0) {
  21831. return BS_NEED_MORE;
  21832. }
  21833. /***/
  21834. }
  21835. /* Flush if we may have to slide, otherwise block_start may become
  21836. * negative and the data will be gone:
  21837. */
  21838. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  21839. /*** FLUSH_BLOCK(s, 0); ***/
  21840. flush_block_only(s, false);
  21841. if (s.strm.avail_out === 0) {
  21842. return BS_NEED_MORE;
  21843. }
  21844. /***/
  21845. }
  21846. }
  21847. s.insert = 0;
  21848. if (flush === Z_FINISH) {
  21849. /*** FLUSH_BLOCK(s, 1); ***/
  21850. flush_block_only(s, true);
  21851. if (s.strm.avail_out === 0) {
  21852. return BS_FINISH_STARTED;
  21853. }
  21854. /***/
  21855. return BS_FINISH_DONE;
  21856. }
  21857. if (s.strstart > s.block_start) {
  21858. /*** FLUSH_BLOCK(s, 0); ***/
  21859. flush_block_only(s, false);
  21860. if (s.strm.avail_out === 0) {
  21861. return BS_NEED_MORE;
  21862. }
  21863. /***/
  21864. }
  21865. return BS_NEED_MORE;
  21866. }
  21867. /* ===========================================================================
  21868. * Compress as much as possible from the input stream, return the current
  21869. * block state.
  21870. * This function does not perform lazy evaluation of matches and inserts
  21871. * new strings in the dictionary only for unmatched strings or for short
  21872. * matches. It is used only for the fast compression options.
  21873. */
  21874. function deflate_fast(s, flush) {
  21875. var hash_head; /* head of the hash chain */
  21876. var bflush; /* set if current block must be flushed */
  21877. for (;;) {
  21878. /* Make sure that we always have enough lookahead, except
  21879. * at the end of the input file. We need MAX_MATCH bytes
  21880. * for the next match, plus MIN_MATCH bytes to insert the
  21881. * string following the next match.
  21882. */
  21883. if (s.lookahead < MIN_LOOKAHEAD) {
  21884. fill_window(s);
  21885. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21886. return BS_NEED_MORE;
  21887. }
  21888. if (s.lookahead === 0) {
  21889. break; /* flush the current block */
  21890. }
  21891. }
  21892. /* Insert the string window[strstart .. strstart+2] in the
  21893. * dictionary, and set hash_head to the head of the hash chain:
  21894. */
  21895. hash_head = 0/*NIL*/;
  21896. if (s.lookahead >= MIN_MATCH) {
  21897. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21898. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21899. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21900. s.head[s.ins_h] = s.strstart;
  21901. /***/
  21902. }
  21903. /* Find the longest match, discarding those <= prev_length.
  21904. * At this point we have always match_length < MIN_MATCH
  21905. */
  21906. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  21907. /* To simplify the code, we prevent matches with the string
  21908. * of window index 0 (in particular we have to avoid a match
  21909. * of the string with itself at the start of the input file).
  21910. */
  21911. s.match_length = longest_match(s, hash_head);
  21912. /* longest_match() sets match_start */
  21913. }
  21914. if (s.match_length >= MIN_MATCH) {
  21915. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  21916. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  21917. s.match_length - MIN_MATCH, bflush); ***/
  21918. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  21919. s.lookahead -= s.match_length;
  21920. /* Insert new strings in the hash table only if the match length
  21921. * is not too large. This saves time but degrades compression.
  21922. */
  21923. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  21924. s.match_length--; /* string at strstart already in table */
  21925. do {
  21926. s.strstart++;
  21927. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21928. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21929. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21930. s.head[s.ins_h] = s.strstart;
  21931. /***/
  21932. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21933. * always MIN_MATCH bytes ahead.
  21934. */
  21935. } while (--s.match_length !== 0);
  21936. s.strstart++;
  21937. } else
  21938. {
  21939. s.strstart += s.match_length;
  21940. s.match_length = 0;
  21941. s.ins_h = s.window[s.strstart];
  21942. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21943. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21944. //#if MIN_MATCH != 3
  21945. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21946. //#endif
  21947. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21948. * matter since it will be recomputed at next deflate call.
  21949. */
  21950. }
  21951. } else {
  21952. /* No match, output a literal byte */
  21953. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21954. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21955. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21956. s.lookahead--;
  21957. s.strstart++;
  21958. }
  21959. if (bflush) {
  21960. /*** FLUSH_BLOCK(s, 0); ***/
  21961. flush_block_only(s, false);
  21962. if (s.strm.avail_out === 0) {
  21963. return BS_NEED_MORE;
  21964. }
  21965. /***/
  21966. }
  21967. }
  21968. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21969. if (flush === Z_FINISH) {
  21970. /*** FLUSH_BLOCK(s, 1); ***/
  21971. flush_block_only(s, true);
  21972. if (s.strm.avail_out === 0) {
  21973. return BS_FINISH_STARTED;
  21974. }
  21975. /***/
  21976. return BS_FINISH_DONE;
  21977. }
  21978. if (s.last_lit) {
  21979. /*** FLUSH_BLOCK(s, 0); ***/
  21980. flush_block_only(s, false);
  21981. if (s.strm.avail_out === 0) {
  21982. return BS_NEED_MORE;
  21983. }
  21984. /***/
  21985. }
  21986. return BS_BLOCK_DONE;
  21987. }
  21988. /* ===========================================================================
  21989. * Same as above, but achieves better compression. We use a lazy
  21990. * evaluation for matches: a match is finally adopted only if there is
  21991. * no better match at the next window position.
  21992. */
  21993. function deflate_slow(s, flush) {
  21994. var hash_head; /* head of hash chain */
  21995. var bflush; /* set if current block must be flushed */
  21996. var max_insert;
  21997. /* Process the input block. */
  21998. for (;;) {
  21999. /* Make sure that we always have enough lookahead, except
  22000. * at the end of the input file. We need MAX_MATCH bytes
  22001. * for the next match, plus MIN_MATCH bytes to insert the
  22002. * string following the next match.
  22003. */
  22004. if (s.lookahead < MIN_LOOKAHEAD) {
  22005. fill_window(s);
  22006. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  22007. return BS_NEED_MORE;
  22008. }
  22009. if (s.lookahead === 0) { break; } /* flush the current block */
  22010. }
  22011. /* Insert the string window[strstart .. strstart+2] in the
  22012. * dictionary, and set hash_head to the head of the hash chain:
  22013. */
  22014. hash_head = 0/*NIL*/;
  22015. if (s.lookahead >= MIN_MATCH) {
  22016. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  22017. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  22018. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  22019. s.head[s.ins_h] = s.strstart;
  22020. /***/
  22021. }
  22022. /* Find the longest match, discarding those <= prev_length.
  22023. */
  22024. s.prev_length = s.match_length;
  22025. s.prev_match = s.match_start;
  22026. s.match_length = MIN_MATCH-1;
  22027. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  22028. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  22029. /* To simplify the code, we prevent matches with the string
  22030. * of window index 0 (in particular we have to avoid a match
  22031. * of the string with itself at the start of the input file).
  22032. */
  22033. s.match_length = longest_match(s, hash_head);
  22034. /* longest_match() sets match_start */
  22035. if (s.match_length <= 5 &&
  22036. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  22037. /* If prev_match is also MIN_MATCH, match_start is garbage
  22038. * but we will ignore the current match anyway.
  22039. */
  22040. s.match_length = MIN_MATCH-1;
  22041. }
  22042. }
  22043. /* If there was a match at the previous step and the current
  22044. * match is not better, output the previous match:
  22045. */
  22046. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  22047. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  22048. /* Do not insert strings in hash table beyond this. */
  22049. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  22050. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  22051. s.prev_length - MIN_MATCH, bflush);***/
  22052. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  22053. /* Insert in hash table all strings up to the end of the match.
  22054. * strstart-1 and strstart are already inserted. If there is not
  22055. * enough lookahead, the last two strings are not inserted in
  22056. * the hash table.
  22057. */
  22058. s.lookahead -= s.prev_length-1;
  22059. s.prev_length -= 2;
  22060. do {
  22061. if (++s.strstart <= max_insert) {
  22062. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  22063. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  22064. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  22065. s.head[s.ins_h] = s.strstart;
  22066. /***/
  22067. }
  22068. } while (--s.prev_length !== 0);
  22069. s.match_available = 0;
  22070. s.match_length = MIN_MATCH-1;
  22071. s.strstart++;
  22072. if (bflush) {
  22073. /*** FLUSH_BLOCK(s, 0); ***/
  22074. flush_block_only(s, false);
  22075. if (s.strm.avail_out === 0) {
  22076. return BS_NEED_MORE;
  22077. }
  22078. /***/
  22079. }
  22080. } else if (s.match_available) {
  22081. /* If there was no match at the previous position, output a
  22082. * single literal. If there was a match but the current match
  22083. * is longer, truncate the previous match to a single literal.
  22084. */
  22085. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  22086. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  22087. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  22088. if (bflush) {
  22089. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  22090. flush_block_only(s, false);
  22091. /***/
  22092. }
  22093. s.strstart++;
  22094. s.lookahead--;
  22095. if (s.strm.avail_out === 0) {
  22096. return BS_NEED_MORE;
  22097. }
  22098. } else {
  22099. /* There is no previous match to compare with, wait for
  22100. * the next step to decide.
  22101. */
  22102. s.match_available = 1;
  22103. s.strstart++;
  22104. s.lookahead--;
  22105. }
  22106. }
  22107. //Assert (flush != Z_NO_FLUSH, "no flush?");
  22108. if (s.match_available) {
  22109. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  22110. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  22111. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  22112. s.match_available = 0;
  22113. }
  22114. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  22115. if (flush === Z_FINISH) {
  22116. /*** FLUSH_BLOCK(s, 1); ***/
  22117. flush_block_only(s, true);
  22118. if (s.strm.avail_out === 0) {
  22119. return BS_FINISH_STARTED;
  22120. }
  22121. /***/
  22122. return BS_FINISH_DONE;
  22123. }
  22124. if (s.last_lit) {
  22125. /*** FLUSH_BLOCK(s, 0); ***/
  22126. flush_block_only(s, false);
  22127. if (s.strm.avail_out === 0) {
  22128. return BS_NEED_MORE;
  22129. }
  22130. /***/
  22131. }
  22132. return BS_BLOCK_DONE;
  22133. }
  22134. /* ===========================================================================
  22135. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  22136. * one. Do not maintain a hash table. (It will be regenerated if this run of
  22137. * deflate switches away from Z_RLE.)
  22138. */
  22139. function deflate_rle(s, flush) {
  22140. var bflush; /* set if current block must be flushed */
  22141. var prev; /* byte at distance one to match */
  22142. var scan, strend; /* scan goes up to strend for length of run */
  22143. var _win = s.window;
  22144. for (;;) {
  22145. /* Make sure that we always have enough lookahead, except
  22146. * at the end of the input file. We need MAX_MATCH bytes
  22147. * for the longest run, plus one for the unrolled loop.
  22148. */
  22149. if (s.lookahead <= MAX_MATCH) {
  22150. fill_window(s);
  22151. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  22152. return BS_NEED_MORE;
  22153. }
  22154. if (s.lookahead === 0) { break; } /* flush the current block */
  22155. }
  22156. /* See how many times the previous byte repeats */
  22157. s.match_length = 0;
  22158. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  22159. scan = s.strstart - 1;
  22160. prev = _win[scan];
  22161. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  22162. strend = s.strstart + MAX_MATCH;
  22163. do {
  22164. /*jshint noempty:false*/
  22165. } while (prev === _win[++scan] && prev === _win[++scan] &&
  22166. prev === _win[++scan] && prev === _win[++scan] &&
  22167. prev === _win[++scan] && prev === _win[++scan] &&
  22168. prev === _win[++scan] && prev === _win[++scan] &&
  22169. scan < strend);
  22170. s.match_length = MAX_MATCH - (strend - scan);
  22171. if (s.match_length > s.lookahead) {
  22172. s.match_length = s.lookahead;
  22173. }
  22174. }
  22175. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  22176. }
  22177. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  22178. if (s.match_length >= MIN_MATCH) {
  22179. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  22180. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  22181. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  22182. s.lookahead -= s.match_length;
  22183. s.strstart += s.match_length;
  22184. s.match_length = 0;
  22185. } else {
  22186. /* No match, output a literal byte */
  22187. //Tracevv((stderr,"%c", s->window[s->strstart]));
  22188. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  22189. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  22190. s.lookahead--;
  22191. s.strstart++;
  22192. }
  22193. if (bflush) {
  22194. /*** FLUSH_BLOCK(s, 0); ***/
  22195. flush_block_only(s, false);
  22196. if (s.strm.avail_out === 0) {
  22197. return BS_NEED_MORE;
  22198. }
  22199. /***/
  22200. }
  22201. }
  22202. s.insert = 0;
  22203. if (flush === Z_FINISH) {
  22204. /*** FLUSH_BLOCK(s, 1); ***/
  22205. flush_block_only(s, true);
  22206. if (s.strm.avail_out === 0) {
  22207. return BS_FINISH_STARTED;
  22208. }
  22209. /***/
  22210. return BS_FINISH_DONE;
  22211. }
  22212. if (s.last_lit) {
  22213. /*** FLUSH_BLOCK(s, 0); ***/
  22214. flush_block_only(s, false);
  22215. if (s.strm.avail_out === 0) {
  22216. return BS_NEED_MORE;
  22217. }
  22218. /***/
  22219. }
  22220. return BS_BLOCK_DONE;
  22221. }
  22222. /* ===========================================================================
  22223. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  22224. * (It will be regenerated if this run of deflate switches away from Huffman.)
  22225. */
  22226. function deflate_huff(s, flush) {
  22227. var bflush; /* set if current block must be flushed */
  22228. for (;;) {
  22229. /* Make sure that we have a literal to write. */
  22230. if (s.lookahead === 0) {
  22231. fill_window(s);
  22232. if (s.lookahead === 0) {
  22233. if (flush === Z_NO_FLUSH) {
  22234. return BS_NEED_MORE;
  22235. }
  22236. break; /* flush the current block */
  22237. }
  22238. }
  22239. /* Output a literal byte */
  22240. s.match_length = 0;
  22241. //Tracevv((stderr,"%c", s->window[s->strstart]));
  22242. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  22243. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  22244. s.lookahead--;
  22245. s.strstart++;
  22246. if (bflush) {
  22247. /*** FLUSH_BLOCK(s, 0); ***/
  22248. flush_block_only(s, false);
  22249. if (s.strm.avail_out === 0) {
  22250. return BS_NEED_MORE;
  22251. }
  22252. /***/
  22253. }
  22254. }
  22255. s.insert = 0;
  22256. if (flush === Z_FINISH) {
  22257. /*** FLUSH_BLOCK(s, 1); ***/
  22258. flush_block_only(s, true);
  22259. if (s.strm.avail_out === 0) {
  22260. return BS_FINISH_STARTED;
  22261. }
  22262. /***/
  22263. return BS_FINISH_DONE;
  22264. }
  22265. if (s.last_lit) {
  22266. /*** FLUSH_BLOCK(s, 0); ***/
  22267. flush_block_only(s, false);
  22268. if (s.strm.avail_out === 0) {
  22269. return BS_NEED_MORE;
  22270. }
  22271. /***/
  22272. }
  22273. return BS_BLOCK_DONE;
  22274. }
  22275. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  22276. * the desired pack level (0..9). The values given below have been tuned to
  22277. * exclude worst case performance for pathological files. Better values may be
  22278. * found for specific files.
  22279. */
  22280. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  22281. this.good_length = good_length;
  22282. this.max_lazy = max_lazy;
  22283. this.nice_length = nice_length;
  22284. this.max_chain = max_chain;
  22285. this.func = func;
  22286. };
  22287. var configuration_table;
  22288. configuration_table = [
  22289. /* good lazy nice chain */
  22290. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  22291. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  22292. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  22293. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  22294. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  22295. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  22296. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  22297. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  22298. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  22299. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  22300. ];
  22301. /* ===========================================================================
  22302. * Initialize the "longest match" routines for a new zlib stream
  22303. */
  22304. function lm_init(s) {
  22305. s.window_size = 2 * s.w_size;
  22306. /*** CLEAR_HASH(s); ***/
  22307. zero(s.head); // Fill with NIL (= 0);
  22308. /* Set the default configuration parameters:
  22309. */
  22310. s.max_lazy_match = configuration_table[s.level].max_lazy;
  22311. s.good_match = configuration_table[s.level].good_length;
  22312. s.nice_match = configuration_table[s.level].nice_length;
  22313. s.max_chain_length = configuration_table[s.level].max_chain;
  22314. s.strstart = 0;
  22315. s.block_start = 0;
  22316. s.lookahead = 0;
  22317. s.insert = 0;
  22318. s.match_length = s.prev_length = MIN_MATCH - 1;
  22319. s.match_available = 0;
  22320. s.ins_h = 0;
  22321. }
  22322. function DeflateState() {
  22323. this.strm = null; /* pointer back to this zlib stream */
  22324. this.status = 0; /* as the name implies */
  22325. this.pending_buf = null; /* output still pending */
  22326. this.pending_buf_size = 0; /* size of pending_buf */
  22327. this.pending_out = 0; /* next pending byte to output to the stream */
  22328. this.pending = 0; /* nb of bytes in the pending buffer */
  22329. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22330. this.gzhead = null; /* gzip header information to write */
  22331. this.gzindex = 0; /* where in extra, name, or comment */
  22332. this.method = Z_DEFLATED; /* can only be DEFLATED */
  22333. this.last_flush = -1; /* value of flush param for previous deflate call */
  22334. this.w_size = 0; /* LZ77 window size (32K by default) */
  22335. this.w_bits = 0; /* log2(w_size) (8..16) */
  22336. this.w_mask = 0; /* w_size - 1 */
  22337. this.window = null;
  22338. /* Sliding window. Input bytes are read into the second half of the window,
  22339. * and move to the first half later to keep a dictionary of at least wSize
  22340. * bytes. With this organization, matches are limited to a distance of
  22341. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  22342. * performed with a length multiple of the block size.
  22343. */
  22344. this.window_size = 0;
  22345. /* Actual size of window: 2*wSize, except when the user input buffer
  22346. * is directly used as sliding window.
  22347. */
  22348. this.prev = null;
  22349. /* Link to older string with same hash index. To limit the size of this
  22350. * array to 64K, this link is maintained only for the last 32K strings.
  22351. * An index in this array is thus a window index modulo 32K.
  22352. */
  22353. this.head = null; /* Heads of the hash chains or NIL. */
  22354. this.ins_h = 0; /* hash index of string to be inserted */
  22355. this.hash_size = 0; /* number of elements in hash table */
  22356. this.hash_bits = 0; /* log2(hash_size) */
  22357. this.hash_mask = 0; /* hash_size-1 */
  22358. this.hash_shift = 0;
  22359. /* Number of bits by which ins_h must be shifted at each input
  22360. * step. It must be such that after MIN_MATCH steps, the oldest
  22361. * byte no longer takes part in the hash key, that is:
  22362. * hash_shift * MIN_MATCH >= hash_bits
  22363. */
  22364. this.block_start = 0;
  22365. /* Window position at the beginning of the current output block. Gets
  22366. * negative when the window is moved backwards.
  22367. */
  22368. this.match_length = 0; /* length of best match */
  22369. this.prev_match = 0; /* previous match */
  22370. this.match_available = 0; /* set if previous match exists */
  22371. this.strstart = 0; /* start of string to insert */
  22372. this.match_start = 0; /* start of matching string */
  22373. this.lookahead = 0; /* number of valid bytes ahead in window */
  22374. this.prev_length = 0;
  22375. /* Length of the best match at previous step. Matches not greater than this
  22376. * are discarded. This is used in the lazy match evaluation.
  22377. */
  22378. this.max_chain_length = 0;
  22379. /* To speed up deflation, hash chains are never searched beyond this
  22380. * length. A higher limit improves compression ratio but degrades the
  22381. * speed.
  22382. */
  22383. this.max_lazy_match = 0;
  22384. /* Attempt to find a better match only when the current match is strictly
  22385. * smaller than this value. This mechanism is used only for compression
  22386. * levels >= 4.
  22387. */
  22388. // That's alias to max_lazy_match, don't use directly
  22389. //this.max_insert_length = 0;
  22390. /* Insert new strings in the hash table only if the match length is not
  22391. * greater than this length. This saves time but degrades compression.
  22392. * max_insert_length is used only for compression levels <= 3.
  22393. */
  22394. this.level = 0; /* compression level (1..9) */
  22395. this.strategy = 0; /* favor or force Huffman coding*/
  22396. this.good_match = 0;
  22397. /* Use a faster search when the previous match is longer than this */
  22398. this.nice_match = 0; /* Stop searching when current match exceeds this */
  22399. /* used by trees.c: */
  22400. /* Didn't use ct_data typedef below to suppress compiler warning */
  22401. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  22402. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  22403. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  22404. // Use flat array of DOUBLE size, with interleaved fata,
  22405. // because JS does not support effective
  22406. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  22407. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  22408. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  22409. zero(this.dyn_ltree);
  22410. zero(this.dyn_dtree);
  22411. zero(this.bl_tree);
  22412. this.l_desc = null; /* desc. for literal tree */
  22413. this.d_desc = null; /* desc. for distance tree */
  22414. this.bl_desc = null; /* desc. for bit length tree */
  22415. //ush bl_count[MAX_BITS+1];
  22416. this.bl_count = new utils.Buf16(MAX_BITS+1);
  22417. /* number of codes at each bit length for an optimal tree */
  22418. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  22419. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  22420. zero(this.heap);
  22421. this.heap_len = 0; /* number of elements in the heap */
  22422. this.heap_max = 0; /* element of largest frequency */
  22423. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  22424. * The same heap array is used to build all trees.
  22425. */
  22426. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  22427. zero(this.depth);
  22428. /* Depth of each subtree used as tie breaker for trees of equal frequency
  22429. */
  22430. this.l_buf = 0; /* buffer index for literals or lengths */
  22431. this.lit_bufsize = 0;
  22432. /* Size of match buffer for literals/lengths. There are 4 reasons for
  22433. * limiting lit_bufsize to 64K:
  22434. * - frequencies can be kept in 16 bit counters
  22435. * - if compression is not successful for the first block, all input
  22436. * data is still in the window so we can still emit a stored block even
  22437. * when input comes from standard input. (This can also be done for
  22438. * all blocks if lit_bufsize is not greater than 32K.)
  22439. * - if compression is not successful for a file smaller than 64K, we can
  22440. * even emit a stored file instead of a stored block (saving 5 bytes).
  22441. * This is applicable only for zip (not gzip or zlib).
  22442. * - creating new Huffman trees less frequently may not provide fast
  22443. * adaptation to changes in the input data statistics. (Take for
  22444. * example a binary file with poorly compressible code followed by
  22445. * a highly compressible string table.) Smaller buffer sizes give
  22446. * fast adaptation but have of course the overhead of transmitting
  22447. * trees more frequently.
  22448. * - I can't count above 4
  22449. */
  22450. this.last_lit = 0; /* running index in l_buf */
  22451. this.d_buf = 0;
  22452. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  22453. * the same number of elements. To use different lengths, an extra flag
  22454. * array would be necessary.
  22455. */
  22456. this.opt_len = 0; /* bit length of current block with optimal trees */
  22457. this.static_len = 0; /* bit length of current block with static trees */
  22458. this.matches = 0; /* number of string matches in current block */
  22459. this.insert = 0; /* bytes at end of window left to insert */
  22460. this.bi_buf = 0;
  22461. /* Output buffer. bits are inserted starting at the bottom (least
  22462. * significant bits).
  22463. */
  22464. this.bi_valid = 0;
  22465. /* Number of valid bits in bi_buf. All bits above the last valid bit
  22466. * are always zero.
  22467. */
  22468. // Used for window memory init. We safely ignore it for JS. That makes
  22469. // sense only for pointers and memory check tools.
  22470. //this.high_water = 0;
  22471. /* High water mark offset in window for initialized bytes -- bytes above
  22472. * this are set to zero in order to avoid memory check warnings when
  22473. * longest match routines access bytes past the input. This is then
  22474. * updated to the new high water mark.
  22475. */
  22476. }
  22477. function deflateResetKeep(strm) {
  22478. var s;
  22479. if (!strm || !strm.state) {
  22480. return err(strm, Z_STREAM_ERROR);
  22481. }
  22482. strm.total_in = strm.total_out = 0;
  22483. strm.data_type = Z_UNKNOWN;
  22484. s = strm.state;
  22485. s.pending = 0;
  22486. s.pending_out = 0;
  22487. if (s.wrap < 0) {
  22488. s.wrap = -s.wrap;
  22489. /* was made negative by deflate(..., Z_FINISH); */
  22490. }
  22491. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  22492. strm.adler = (s.wrap === 2) ?
  22493. 0 // crc32(0, Z_NULL, 0)
  22494. :
  22495. 1; // adler32(0, Z_NULL, 0)
  22496. s.last_flush = Z_NO_FLUSH;
  22497. trees._tr_init(s);
  22498. return Z_OK;
  22499. }
  22500. function deflateReset(strm) {
  22501. var ret = deflateResetKeep(strm);
  22502. if (ret === Z_OK) {
  22503. lm_init(strm.state);
  22504. }
  22505. return ret;
  22506. }
  22507. function deflateSetHeader(strm, head) {
  22508. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22509. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  22510. strm.state.gzhead = head;
  22511. return Z_OK;
  22512. }
  22513. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  22514. if (!strm) { // === Z_NULL
  22515. return Z_STREAM_ERROR;
  22516. }
  22517. var wrap = 1;
  22518. if (level === Z_DEFAULT_COMPRESSION) {
  22519. level = 6;
  22520. }
  22521. if (windowBits < 0) { /* suppress zlib wrapper */
  22522. wrap = 0;
  22523. windowBits = -windowBits;
  22524. }
  22525. else if (windowBits > 15) {
  22526. wrap = 2; /* write gzip wrapper instead */
  22527. windowBits -= 16;
  22528. }
  22529. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  22530. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  22531. strategy < 0 || strategy > Z_FIXED) {
  22532. return err(strm, Z_STREAM_ERROR);
  22533. }
  22534. if (windowBits === 8) {
  22535. windowBits = 9;
  22536. }
  22537. /* until 256-byte window bug fixed */
  22538. var s = new DeflateState();
  22539. strm.state = s;
  22540. s.strm = strm;
  22541. s.wrap = wrap;
  22542. s.gzhead = null;
  22543. s.w_bits = windowBits;
  22544. s.w_size = 1 << s.w_bits;
  22545. s.w_mask = s.w_size - 1;
  22546. s.hash_bits = memLevel + 7;
  22547. s.hash_size = 1 << s.hash_bits;
  22548. s.hash_mask = s.hash_size - 1;
  22549. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  22550. s.window = new utils.Buf8(s.w_size * 2);
  22551. s.head = new utils.Buf16(s.hash_size);
  22552. s.prev = new utils.Buf16(s.w_size);
  22553. // Don't need mem init magic for JS.
  22554. //s.high_water = 0; /* nothing written to s->window yet */
  22555. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  22556. s.pending_buf_size = s.lit_bufsize * 4;
  22557. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  22558. s.d_buf = s.lit_bufsize >> 1;
  22559. s.l_buf = (1 + 2) * s.lit_bufsize;
  22560. s.level = level;
  22561. s.strategy = strategy;
  22562. s.method = method;
  22563. return deflateReset(strm);
  22564. }
  22565. function deflateInit(strm, level) {
  22566. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  22567. }
  22568. function deflate(strm, flush) {
  22569. var old_flush, s;
  22570. var beg, val; // for gzip header write only
  22571. if (!strm || !strm.state ||
  22572. flush > Z_BLOCK || flush < 0) {
  22573. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  22574. }
  22575. s = strm.state;
  22576. if (!strm.output ||
  22577. (!strm.input && strm.avail_in !== 0) ||
  22578. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  22579. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  22580. }
  22581. s.strm = strm; /* just in case */
  22582. old_flush = s.last_flush;
  22583. s.last_flush = flush;
  22584. /* Write the header */
  22585. if (s.status === INIT_STATE) {
  22586. if (s.wrap === 2) { // GZIP header
  22587. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22588. put_byte(s, 31);
  22589. put_byte(s, 139);
  22590. put_byte(s, 8);
  22591. if (!s.gzhead) { // s->gzhead == Z_NULL
  22592. put_byte(s, 0);
  22593. put_byte(s, 0);
  22594. put_byte(s, 0);
  22595. put_byte(s, 0);
  22596. put_byte(s, 0);
  22597. put_byte(s, s.level === 9 ? 2 :
  22598. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22599. 4 : 0));
  22600. put_byte(s, OS_CODE);
  22601. s.status = BUSY_STATE;
  22602. }
  22603. else {
  22604. put_byte(s, (s.gzhead.text ? 1 : 0) +
  22605. (s.gzhead.hcrc ? 2 : 0) +
  22606. (!s.gzhead.extra ? 0 : 4) +
  22607. (!s.gzhead.name ? 0 : 8) +
  22608. (!s.gzhead.comment ? 0 : 16)
  22609. );
  22610. put_byte(s, s.gzhead.time & 0xff);
  22611. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  22612. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  22613. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  22614. put_byte(s, s.level === 9 ? 2 :
  22615. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22616. 4 : 0));
  22617. put_byte(s, s.gzhead.os & 0xff);
  22618. if (s.gzhead.extra && s.gzhead.extra.length) {
  22619. put_byte(s, s.gzhead.extra.length & 0xff);
  22620. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  22621. }
  22622. if (s.gzhead.hcrc) {
  22623. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  22624. }
  22625. s.gzindex = 0;
  22626. s.status = EXTRA_STATE;
  22627. }
  22628. }
  22629. else // DEFLATE header
  22630. {
  22631. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  22632. var level_flags = -1;
  22633. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  22634. level_flags = 0;
  22635. } else if (s.level < 6) {
  22636. level_flags = 1;
  22637. } else if (s.level === 6) {
  22638. level_flags = 2;
  22639. } else {
  22640. level_flags = 3;
  22641. }
  22642. header |= (level_flags << 6);
  22643. if (s.strstart !== 0) { header |= PRESET_DICT; }
  22644. header += 31 - (header % 31);
  22645. s.status = BUSY_STATE;
  22646. putShortMSB(s, header);
  22647. /* Save the adler32 of the preset dictionary: */
  22648. if (s.strstart !== 0) {
  22649. putShortMSB(s, strm.adler >>> 16);
  22650. putShortMSB(s, strm.adler & 0xffff);
  22651. }
  22652. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  22653. }
  22654. }
  22655. //#ifdef GZIP
  22656. if (s.status === EXTRA_STATE) {
  22657. if (s.gzhead.extra/* != Z_NULL*/) {
  22658. beg = s.pending; /* start of bytes to update crc */
  22659. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  22660. if (s.pending === s.pending_buf_size) {
  22661. if (s.gzhead.hcrc && s.pending > beg) {
  22662. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22663. }
  22664. flush_pending(strm);
  22665. beg = s.pending;
  22666. if (s.pending === s.pending_buf_size) {
  22667. break;
  22668. }
  22669. }
  22670. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  22671. s.gzindex++;
  22672. }
  22673. if (s.gzhead.hcrc && s.pending > beg) {
  22674. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22675. }
  22676. if (s.gzindex === s.gzhead.extra.length) {
  22677. s.gzindex = 0;
  22678. s.status = NAME_STATE;
  22679. }
  22680. }
  22681. else {
  22682. s.status = NAME_STATE;
  22683. }
  22684. }
  22685. if (s.status === NAME_STATE) {
  22686. if (s.gzhead.name/* != Z_NULL*/) {
  22687. beg = s.pending; /* start of bytes to update crc */
  22688. //int val;
  22689. do {
  22690. if (s.pending === s.pending_buf_size) {
  22691. if (s.gzhead.hcrc && s.pending > beg) {
  22692. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22693. }
  22694. flush_pending(strm);
  22695. beg = s.pending;
  22696. if (s.pending === s.pending_buf_size) {
  22697. val = 1;
  22698. break;
  22699. }
  22700. }
  22701. // JS specific: little magic to add zero terminator to end of string
  22702. if (s.gzindex < s.gzhead.name.length) {
  22703. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  22704. } else {
  22705. val = 0;
  22706. }
  22707. put_byte(s, val);
  22708. } while (val !== 0);
  22709. if (s.gzhead.hcrc && s.pending > beg) {
  22710. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22711. }
  22712. if (val === 0) {
  22713. s.gzindex = 0;
  22714. s.status = COMMENT_STATE;
  22715. }
  22716. }
  22717. else {
  22718. s.status = COMMENT_STATE;
  22719. }
  22720. }
  22721. if (s.status === COMMENT_STATE) {
  22722. if (s.gzhead.comment/* != Z_NULL*/) {
  22723. beg = s.pending; /* start of bytes to update crc */
  22724. //int val;
  22725. do {
  22726. if (s.pending === s.pending_buf_size) {
  22727. if (s.gzhead.hcrc && s.pending > beg) {
  22728. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22729. }
  22730. flush_pending(strm);
  22731. beg = s.pending;
  22732. if (s.pending === s.pending_buf_size) {
  22733. val = 1;
  22734. break;
  22735. }
  22736. }
  22737. // JS specific: little magic to add zero terminator to end of string
  22738. if (s.gzindex < s.gzhead.comment.length) {
  22739. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  22740. } else {
  22741. val = 0;
  22742. }
  22743. put_byte(s, val);
  22744. } while (val !== 0);
  22745. if (s.gzhead.hcrc && s.pending > beg) {
  22746. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22747. }
  22748. if (val === 0) {
  22749. s.status = HCRC_STATE;
  22750. }
  22751. }
  22752. else {
  22753. s.status = HCRC_STATE;
  22754. }
  22755. }
  22756. if (s.status === HCRC_STATE) {
  22757. if (s.gzhead.hcrc) {
  22758. if (s.pending + 2 > s.pending_buf_size) {
  22759. flush_pending(strm);
  22760. }
  22761. if (s.pending + 2 <= s.pending_buf_size) {
  22762. put_byte(s, strm.adler & 0xff);
  22763. put_byte(s, (strm.adler >> 8) & 0xff);
  22764. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22765. s.status = BUSY_STATE;
  22766. }
  22767. }
  22768. else {
  22769. s.status = BUSY_STATE;
  22770. }
  22771. }
  22772. //#endif
  22773. /* Flush as much pending output as possible */
  22774. if (s.pending !== 0) {
  22775. flush_pending(strm);
  22776. if (strm.avail_out === 0) {
  22777. /* Since avail_out is 0, deflate will be called again with
  22778. * more output space, but possibly with both pending and
  22779. * avail_in equal to zero. There won't be anything to do,
  22780. * but this is not an error situation so make sure we
  22781. * return OK instead of BUF_ERROR at next call of deflate:
  22782. */
  22783. s.last_flush = -1;
  22784. return Z_OK;
  22785. }
  22786. /* Make sure there is something to do and avoid duplicate consecutive
  22787. * flushes. For repeated and useless calls with Z_FINISH, we keep
  22788. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  22789. */
  22790. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  22791. flush !== Z_FINISH) {
  22792. return err(strm, Z_BUF_ERROR);
  22793. }
  22794. /* User must not provide more input after the first FINISH: */
  22795. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  22796. return err(strm, Z_BUF_ERROR);
  22797. }
  22798. /* Start a new block or continue the current one.
  22799. */
  22800. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  22801. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  22802. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  22803. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  22804. configuration_table[s.level].func(s, flush));
  22805. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  22806. s.status = FINISH_STATE;
  22807. }
  22808. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  22809. if (strm.avail_out === 0) {
  22810. s.last_flush = -1;
  22811. /* avoid BUF_ERROR next call, see above */
  22812. }
  22813. return Z_OK;
  22814. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  22815. * of deflate should use the same flush parameter to make sure
  22816. * that the flush is complete. So we don't have to output an
  22817. * empty block here, this will be done at next call. This also
  22818. * ensures that for a very small output buffer, we emit at most
  22819. * one empty block.
  22820. */
  22821. }
  22822. if (bstate === BS_BLOCK_DONE) {
  22823. if (flush === Z_PARTIAL_FLUSH) {
  22824. trees._tr_align(s);
  22825. }
  22826. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  22827. trees._tr_stored_block(s, 0, 0, false);
  22828. /* For a full flush, this empty block will be recognized
  22829. * as a special marker by inflate_sync().
  22830. */
  22831. if (flush === Z_FULL_FLUSH) {
  22832. /*** CLEAR_HASH(s); ***/ /* forget history */
  22833. zero(s.head); // Fill with NIL (= 0);
  22834. if (s.lookahead === 0) {
  22835. s.strstart = 0;
  22836. s.block_start = 0;
  22837. s.insert = 0;
  22838. }
  22839. }
  22840. }
  22841. flush_pending(strm);
  22842. if (strm.avail_out === 0) {
  22843. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  22844. return Z_OK;
  22845. }
  22846. }
  22847. }
  22848. //Assert(strm->avail_out > 0, "bug2");
  22849. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  22850. if (flush !== Z_FINISH) { return Z_OK; }
  22851. if (s.wrap <= 0) { return Z_STREAM_END; }
  22852. /* Write the trailer */
  22853. if (s.wrap === 2) {
  22854. put_byte(s, strm.adler & 0xff);
  22855. put_byte(s, (strm.adler >> 8) & 0xff);
  22856. put_byte(s, (strm.adler >> 16) & 0xff);
  22857. put_byte(s, (strm.adler >> 24) & 0xff);
  22858. put_byte(s, strm.total_in & 0xff);
  22859. put_byte(s, (strm.total_in >> 8) & 0xff);
  22860. put_byte(s, (strm.total_in >> 16) & 0xff);
  22861. put_byte(s, (strm.total_in >> 24) & 0xff);
  22862. }
  22863. else
  22864. {
  22865. putShortMSB(s, strm.adler >>> 16);
  22866. putShortMSB(s, strm.adler & 0xffff);
  22867. }
  22868. flush_pending(strm);
  22869. /* If avail_out is zero, the application will call deflate again
  22870. * to flush the rest.
  22871. */
  22872. if (s.wrap > 0) { s.wrap = -s.wrap; }
  22873. /* write the trailer only once! */
  22874. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  22875. }
  22876. function deflateEnd(strm) {
  22877. var status;
  22878. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  22879. return Z_STREAM_ERROR;
  22880. }
  22881. status = strm.state.status;
  22882. if (status !== INIT_STATE &&
  22883. status !== EXTRA_STATE &&
  22884. status !== NAME_STATE &&
  22885. status !== COMMENT_STATE &&
  22886. status !== HCRC_STATE &&
  22887. status !== BUSY_STATE &&
  22888. status !== FINISH_STATE
  22889. ) {
  22890. return err(strm, Z_STREAM_ERROR);
  22891. }
  22892. strm.state = null;
  22893. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  22894. }
  22895. /* =========================================================================
  22896. * Copy the source state to the destination state
  22897. */
  22898. //function deflateCopy(dest, source) {
  22899. //
  22900. //}
  22901. exports.deflateInit = deflateInit;
  22902. exports.deflateInit2 = deflateInit2;
  22903. exports.deflateReset = deflateReset;
  22904. exports.deflateResetKeep = deflateResetKeep;
  22905. exports.deflateSetHeader = deflateSetHeader;
  22906. exports.deflate = deflate;
  22907. exports.deflateEnd = deflateEnd;
  22908. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  22909. /* Not implemented
  22910. exports.deflateBound = deflateBound;
  22911. exports.deflateCopy = deflateCopy;
  22912. exports.deflateSetDictionary = deflateSetDictionary;
  22913. exports.deflateParams = deflateParams;
  22914. exports.deflatePending = deflatePending;
  22915. exports.deflatePrime = deflatePrime;
  22916. exports.deflateTune = deflateTune;
  22917. */
  22918. },{"../utils/common":80,"./adler32":82,"./crc32":84,"./messages":90,"./trees":91}],86:[function(require,module,exports){
  22919. 'use strict';
  22920. function GZheader() {
  22921. /* true if compressed data believed to be text */
  22922. this.text = 0;
  22923. /* modification time */
  22924. this.time = 0;
  22925. /* extra flags (not used when writing a gzip file) */
  22926. this.xflags = 0;
  22927. /* operating system */
  22928. this.os = 0;
  22929. /* pointer to extra field or Z_NULL if none */
  22930. this.extra = null;
  22931. /* extra field length (valid if extra != Z_NULL) */
  22932. this.extra_len = 0; // Actually, we don't need it in JS,
  22933. // but leave for few code modifications
  22934. //
  22935. // Setup limits is not necessary because in js we should not preallocate memory
  22936. // for inflate use constant limit in 65536 bytes
  22937. //
  22938. /* space at extra (only when reading header) */
  22939. // this.extra_max = 0;
  22940. /* pointer to zero-terminated file name or Z_NULL */
  22941. this.name = '';
  22942. /* space at name (only when reading header) */
  22943. // this.name_max = 0;
  22944. /* pointer to zero-terminated comment or Z_NULL */
  22945. this.comment = '';
  22946. /* space at comment (only when reading header) */
  22947. // this.comm_max = 0;
  22948. /* true if there was or will be a header crc */
  22949. this.hcrc = 0;
  22950. /* true when done reading gzip header (not used when writing a gzip file) */
  22951. this.done = false;
  22952. }
  22953. module.exports = GZheader;
  22954. },{}],87:[function(require,module,exports){
  22955. 'use strict';
  22956. // See state defs from inflate.js
  22957. var BAD = 30; /* got a data error -- remain here until reset */
  22958. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22959. /*
  22960. Decode literal, length, and distance codes and write out the resulting
  22961. literal and match bytes until either not enough input or output is
  22962. available, an end-of-block is encountered, or a data error is encountered.
  22963. When large enough input and output buffers are supplied to inflate(), for
  22964. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22965. inflate execution time is spent in this routine.
  22966. Entry assumptions:
  22967. state.mode === LEN
  22968. strm.avail_in >= 6
  22969. strm.avail_out >= 258
  22970. start >= strm.avail_out
  22971. state.bits < 8
  22972. On return, state.mode is one of:
  22973. LEN -- ran out of enough output space or enough available input
  22974. TYPE -- reached end of block code, inflate() to interpret next block
  22975. BAD -- error in block data
  22976. Notes:
  22977. - The maximum input bits used by a length/distance pair is 15 bits for the
  22978. length code, 5 bits for the length extra, 15 bits for the distance code,
  22979. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22980. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22981. checking for available input while decoding.
  22982. - The maximum bytes that a single length/distance pair can output is 258
  22983. bytes, which is the maximum length that can be coded. inflate_fast()
  22984. requires strm.avail_out >= 258 for each loop to avoid checking for
  22985. output space.
  22986. */
  22987. module.exports = function inflate_fast(strm, start) {
  22988. var state;
  22989. var _in; /* local strm.input */
  22990. var last; /* have enough input while in < last */
  22991. var _out; /* local strm.output */
  22992. var beg; /* inflate()'s initial strm.output */
  22993. var end; /* while out < end, enough space available */
  22994. //#ifdef INFLATE_STRICT
  22995. var dmax; /* maximum distance from zlib header */
  22996. //#endif
  22997. var wsize; /* window size or zero if not using window */
  22998. var whave; /* valid bytes in the window */
  22999. var wnext; /* window write index */
  23000. var window; /* allocated sliding window, if wsize != 0 */
  23001. var hold; /* local strm.hold */
  23002. var bits; /* local strm.bits */
  23003. var lcode; /* local strm.lencode */
  23004. var dcode; /* local strm.distcode */
  23005. var lmask; /* mask for first level of length codes */
  23006. var dmask; /* mask for first level of distance codes */
  23007. var here; /* retrieved table entry */
  23008. var op; /* code bits, operation, extra bits, or */
  23009. /* window position, window bytes to copy */
  23010. var len; /* match length, unused bytes */
  23011. var dist; /* match distance */
  23012. var from; /* where to copy match from */
  23013. var from_source;
  23014. var input, output; // JS specific, because we have no pointers
  23015. /* copy state to local variables */
  23016. state = strm.state;
  23017. //here = state.here;
  23018. _in = strm.next_in;
  23019. input = strm.input;
  23020. last = _in + (strm.avail_in - 5);
  23021. _out = strm.next_out;
  23022. output = strm.output;
  23023. beg = _out - (start - strm.avail_out);
  23024. end = _out + (strm.avail_out - 257);
  23025. //#ifdef INFLATE_STRICT
  23026. dmax = state.dmax;
  23027. //#endif
  23028. wsize = state.wsize;
  23029. whave = state.whave;
  23030. wnext = state.wnext;
  23031. window = state.window;
  23032. hold = state.hold;
  23033. bits = state.bits;
  23034. lcode = state.lencode;
  23035. dcode = state.distcode;
  23036. lmask = (1 << state.lenbits) - 1;
  23037. dmask = (1 << state.distbits) - 1;
  23038. /* decode literals and length/distances until end-of-block or not enough
  23039. input data or output space */
  23040. top:
  23041. do {
  23042. if (bits < 15) {
  23043. hold += input[_in++] << bits;
  23044. bits += 8;
  23045. hold += input[_in++] << bits;
  23046. bits += 8;
  23047. }
  23048. here = lcode[hold & lmask];
  23049. dolen:
  23050. for (;;) { // Goto emulation
  23051. op = here >>> 24/*here.bits*/;
  23052. hold >>>= op;
  23053. bits -= op;
  23054. op = (here >>> 16) & 0xff/*here.op*/;
  23055. if (op === 0) { /* literal */
  23056. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23057. // "inflate: literal '%c'\n" :
  23058. // "inflate: literal 0x%02x\n", here.val));
  23059. output[_out++] = here & 0xffff/*here.val*/;
  23060. }
  23061. else if (op & 16) { /* length base */
  23062. len = here & 0xffff/*here.val*/;
  23063. op &= 15; /* number of extra bits */
  23064. if (op) {
  23065. if (bits < op) {
  23066. hold += input[_in++] << bits;
  23067. bits += 8;
  23068. }
  23069. len += hold & ((1 << op) - 1);
  23070. hold >>>= op;
  23071. bits -= op;
  23072. }
  23073. //Tracevv((stderr, "inflate: length %u\n", len));
  23074. if (bits < 15) {
  23075. hold += input[_in++] << bits;
  23076. bits += 8;
  23077. hold += input[_in++] << bits;
  23078. bits += 8;
  23079. }
  23080. here = dcode[hold & dmask];
  23081. dodist:
  23082. for (;;) { // goto emulation
  23083. op = here >>> 24/*here.bits*/;
  23084. hold >>>= op;
  23085. bits -= op;
  23086. op = (here >>> 16) & 0xff/*here.op*/;
  23087. if (op & 16) { /* distance base */
  23088. dist = here & 0xffff/*here.val*/;
  23089. op &= 15; /* number of extra bits */
  23090. if (bits < op) {
  23091. hold += input[_in++] << bits;
  23092. bits += 8;
  23093. if (bits < op) {
  23094. hold += input[_in++] << bits;
  23095. bits += 8;
  23096. }
  23097. }
  23098. dist += hold & ((1 << op) - 1);
  23099. //#ifdef INFLATE_STRICT
  23100. if (dist > dmax) {
  23101. strm.msg = 'invalid distance too far back';
  23102. state.mode = BAD;
  23103. break top;
  23104. }
  23105. //#endif
  23106. hold >>>= op;
  23107. bits -= op;
  23108. //Tracevv((stderr, "inflate: distance %u\n", dist));
  23109. op = _out - beg; /* max distance in output */
  23110. if (dist > op) { /* see if copy from window */
  23111. op = dist - op; /* distance back in window */
  23112. if (op > whave) {
  23113. if (state.sane) {
  23114. strm.msg = 'invalid distance too far back';
  23115. state.mode = BAD;
  23116. break top;
  23117. }
  23118. // (!) This block is disabled in zlib defailts,
  23119. // don't enable it for binary compatibility
  23120. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23121. // if (len <= op - whave) {
  23122. // do {
  23123. // output[_out++] = 0;
  23124. // } while (--len);
  23125. // continue top;
  23126. // }
  23127. // len -= op - whave;
  23128. // do {
  23129. // output[_out++] = 0;
  23130. // } while (--op > whave);
  23131. // if (op === 0) {
  23132. // from = _out - dist;
  23133. // do {
  23134. // output[_out++] = output[from++];
  23135. // } while (--len);
  23136. // continue top;
  23137. // }
  23138. //#endif
  23139. }
  23140. from = 0; // window index
  23141. from_source = window;
  23142. if (wnext === 0) { /* very common case */
  23143. from += wsize - op;
  23144. if (op < len) { /* some from window */
  23145. len -= op;
  23146. do {
  23147. output[_out++] = window[from++];
  23148. } while (--op);
  23149. from = _out - dist; /* rest from output */
  23150. from_source = output;
  23151. }
  23152. }
  23153. else if (wnext < op) { /* wrap around window */
  23154. from += wsize + wnext - op;
  23155. op -= wnext;
  23156. if (op < len) { /* some from end of window */
  23157. len -= op;
  23158. do {
  23159. output[_out++] = window[from++];
  23160. } while (--op);
  23161. from = 0;
  23162. if (wnext < len) { /* some from start of window */
  23163. op = wnext;
  23164. len -= op;
  23165. do {
  23166. output[_out++] = window[from++];
  23167. } while (--op);
  23168. from = _out - dist; /* rest from output */
  23169. from_source = output;
  23170. }
  23171. }
  23172. }
  23173. else { /* contiguous in window */
  23174. from += wnext - op;
  23175. if (op < len) { /* some from window */
  23176. len -= op;
  23177. do {
  23178. output[_out++] = window[from++];
  23179. } while (--op);
  23180. from = _out - dist; /* rest from output */
  23181. from_source = output;
  23182. }
  23183. }
  23184. while (len > 2) {
  23185. output[_out++] = from_source[from++];
  23186. output[_out++] = from_source[from++];
  23187. output[_out++] = from_source[from++];
  23188. len -= 3;
  23189. }
  23190. if (len) {
  23191. output[_out++] = from_source[from++];
  23192. if (len > 1) {
  23193. output[_out++] = from_source[from++];
  23194. }
  23195. }
  23196. }
  23197. else {
  23198. from = _out - dist; /* copy direct from output */
  23199. do { /* minimum length is three */
  23200. output[_out++] = output[from++];
  23201. output[_out++] = output[from++];
  23202. output[_out++] = output[from++];
  23203. len -= 3;
  23204. } while (len > 2);
  23205. if (len) {
  23206. output[_out++] = output[from++];
  23207. if (len > 1) {
  23208. output[_out++] = output[from++];
  23209. }
  23210. }
  23211. }
  23212. }
  23213. else if ((op & 64) === 0) { /* 2nd level distance code */
  23214. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  23215. continue dodist;
  23216. }
  23217. else {
  23218. strm.msg = 'invalid distance code';
  23219. state.mode = BAD;
  23220. break top;
  23221. }
  23222. break; // need to emulate goto via "continue"
  23223. }
  23224. }
  23225. else if ((op & 64) === 0) { /* 2nd level length code */
  23226. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  23227. continue dolen;
  23228. }
  23229. else if (op & 32) { /* end-of-block */
  23230. //Tracevv((stderr, "inflate: end of block\n"));
  23231. state.mode = TYPE;
  23232. break top;
  23233. }
  23234. else {
  23235. strm.msg = 'invalid literal/length code';
  23236. state.mode = BAD;
  23237. break top;
  23238. }
  23239. break; // need to emulate goto via "continue"
  23240. }
  23241. } while (_in < last && _out < end);
  23242. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  23243. len = bits >> 3;
  23244. _in -= len;
  23245. bits -= len << 3;
  23246. hold &= (1 << bits) - 1;
  23247. /* update state and return */
  23248. strm.next_in = _in;
  23249. strm.next_out = _out;
  23250. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  23251. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  23252. state.hold = hold;
  23253. state.bits = bits;
  23254. return;
  23255. };
  23256. },{}],88:[function(require,module,exports){
  23257. 'use strict';
  23258. var utils = require('../utils/common');
  23259. var adler32 = require('./adler32');
  23260. var crc32 = require('./crc32');
  23261. var inflate_fast = require('./inffast');
  23262. var inflate_table = require('./inftrees');
  23263. var CODES = 0;
  23264. var LENS = 1;
  23265. var DISTS = 2;
  23266. /* Public constants ==========================================================*/
  23267. /* ===========================================================================*/
  23268. /* Allowed flush values; see deflate() and inflate() below for details */
  23269. //var Z_NO_FLUSH = 0;
  23270. //var Z_PARTIAL_FLUSH = 1;
  23271. //var Z_SYNC_FLUSH = 2;
  23272. //var Z_FULL_FLUSH = 3;
  23273. var Z_FINISH = 4;
  23274. var Z_BLOCK = 5;
  23275. var Z_TREES = 6;
  23276. /* Return codes for the compression/decompression functions. Negative values
  23277. * are errors, positive values are used for special but normal events.
  23278. */
  23279. var Z_OK = 0;
  23280. var Z_STREAM_END = 1;
  23281. var Z_NEED_DICT = 2;
  23282. //var Z_ERRNO = -1;
  23283. var Z_STREAM_ERROR = -2;
  23284. var Z_DATA_ERROR = -3;
  23285. var Z_MEM_ERROR = -4;
  23286. var Z_BUF_ERROR = -5;
  23287. //var Z_VERSION_ERROR = -6;
  23288. /* The deflate compression method */
  23289. var Z_DEFLATED = 8;
  23290. /* STATES ====================================================================*/
  23291. /* ===========================================================================*/
  23292. var HEAD = 1; /* i: waiting for magic header */
  23293. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  23294. var TIME = 3; /* i: waiting for modification time (gzip) */
  23295. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  23296. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  23297. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  23298. var NAME = 7; /* i: waiting for end of file name (gzip) */
  23299. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  23300. var HCRC = 9; /* i: waiting for header crc (gzip) */
  23301. var DICTID = 10; /* i: waiting for dictionary check value */
  23302. var DICT = 11; /* waiting for inflateSetDictionary() call */
  23303. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  23304. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  23305. var STORED = 14; /* i: waiting for stored size (length and complement) */
  23306. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  23307. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  23308. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  23309. var LENLENS = 18; /* i: waiting for code length code lengths */
  23310. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  23311. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  23312. var LEN = 21; /* i: waiting for length/lit/eob code */
  23313. var LENEXT = 22; /* i: waiting for length extra bits */
  23314. var DIST = 23; /* i: waiting for distance code */
  23315. var DISTEXT = 24; /* i: waiting for distance extra bits */
  23316. var MATCH = 25; /* o: waiting for output space to copy string */
  23317. var LIT = 26; /* o: waiting for output space to write literal */
  23318. var CHECK = 27; /* i: waiting for 32-bit check value */
  23319. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  23320. var DONE = 29; /* finished check, done -- remain here until reset */
  23321. var BAD = 30; /* got a data error -- remain here until reset */
  23322. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  23323. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  23324. /* ===========================================================================*/
  23325. var ENOUGH_LENS = 852;
  23326. var ENOUGH_DISTS = 592;
  23327. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23328. var MAX_WBITS = 15;
  23329. /* 32K LZ77 window */
  23330. var DEF_WBITS = MAX_WBITS;
  23331. function ZSWAP32(q) {
  23332. return (((q >>> 24) & 0xff) +
  23333. ((q >>> 8) & 0xff00) +
  23334. ((q & 0xff00) << 8) +
  23335. ((q & 0xff) << 24));
  23336. }
  23337. function InflateState() {
  23338. this.mode = 0; /* current inflate mode */
  23339. this.last = false; /* true if processing last block */
  23340. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  23341. this.havedict = false; /* true if dictionary provided */
  23342. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  23343. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  23344. this.check = 0; /* protected copy of check value */
  23345. this.total = 0; /* protected copy of output count */
  23346. // TODO: may be {}
  23347. this.head = null; /* where to save gzip header information */
  23348. /* sliding window */
  23349. this.wbits = 0; /* log base 2 of requested window size */
  23350. this.wsize = 0; /* window size or zero if not using window */
  23351. this.whave = 0; /* valid bytes in the window */
  23352. this.wnext = 0; /* window write index */
  23353. this.window = null; /* allocated sliding window, if needed */
  23354. /* bit accumulator */
  23355. this.hold = 0; /* input bit accumulator */
  23356. this.bits = 0; /* number of bits in "in" */
  23357. /* for string and stored block copying */
  23358. this.length = 0; /* literal or length of data to copy */
  23359. this.offset = 0; /* distance back to copy string from */
  23360. /* for table and code decoding */
  23361. this.extra = 0; /* extra bits needed */
  23362. /* fixed and dynamic code tables */
  23363. this.lencode = null; /* starting table for length/literal codes */
  23364. this.distcode = null; /* starting table for distance codes */
  23365. this.lenbits = 0; /* index bits for lencode */
  23366. this.distbits = 0; /* index bits for distcode */
  23367. /* dynamic table building */
  23368. this.ncode = 0; /* number of code length code lengths */
  23369. this.nlen = 0; /* number of length code lengths */
  23370. this.ndist = 0; /* number of distance code lengths */
  23371. this.have = 0; /* number of code lengths in lens[] */
  23372. this.next = null; /* next available space in codes[] */
  23373. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  23374. this.work = new utils.Buf16(288); /* work area for code table building */
  23375. /*
  23376. because we don't have pointers in js, we use lencode and distcode directly
  23377. as buffers so we don't need codes
  23378. */
  23379. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  23380. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  23381. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  23382. this.sane = 0; /* if false, allow invalid distance too far */
  23383. this.back = 0; /* bits back of last unprocessed length/lit */
  23384. this.was = 0; /* initial length of match */
  23385. }
  23386. function inflateResetKeep(strm) {
  23387. var state;
  23388. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23389. state = strm.state;
  23390. strm.total_in = strm.total_out = state.total = 0;
  23391. strm.msg = ''; /*Z_NULL*/
  23392. if (state.wrap) { /* to support ill-conceived Java test suite */
  23393. strm.adler = state.wrap & 1;
  23394. }
  23395. state.mode = HEAD;
  23396. state.last = 0;
  23397. state.havedict = 0;
  23398. state.dmax = 32768;
  23399. state.head = null/*Z_NULL*/;
  23400. state.hold = 0;
  23401. state.bits = 0;
  23402. //state.lencode = state.distcode = state.next = state.codes;
  23403. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  23404. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  23405. state.sane = 1;
  23406. state.back = -1;
  23407. //Tracev((stderr, "inflate: reset\n"));
  23408. return Z_OK;
  23409. }
  23410. function inflateReset(strm) {
  23411. var state;
  23412. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23413. state = strm.state;
  23414. state.wsize = 0;
  23415. state.whave = 0;
  23416. state.wnext = 0;
  23417. return inflateResetKeep(strm);
  23418. }
  23419. function inflateReset2(strm, windowBits) {
  23420. var wrap;
  23421. var state;
  23422. /* get the state */
  23423. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23424. state = strm.state;
  23425. /* extract wrap request from windowBits parameter */
  23426. if (windowBits < 0) {
  23427. wrap = 0;
  23428. windowBits = -windowBits;
  23429. }
  23430. else {
  23431. wrap = (windowBits >> 4) + 1;
  23432. if (windowBits < 48) {
  23433. windowBits &= 15;
  23434. }
  23435. }
  23436. /* set number of window bits, free window if different */
  23437. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  23438. return Z_STREAM_ERROR;
  23439. }
  23440. if (state.window !== null && state.wbits !== windowBits) {
  23441. state.window = null;
  23442. }
  23443. /* update state and reset the rest of it */
  23444. state.wrap = wrap;
  23445. state.wbits = windowBits;
  23446. return inflateReset(strm);
  23447. }
  23448. function inflateInit2(strm, windowBits) {
  23449. var ret;
  23450. var state;
  23451. if (!strm) { return Z_STREAM_ERROR; }
  23452. //strm.msg = Z_NULL; /* in case we return an error */
  23453. state = new InflateState();
  23454. //if (state === Z_NULL) return Z_MEM_ERROR;
  23455. //Tracev((stderr, "inflate: allocated\n"));
  23456. strm.state = state;
  23457. state.window = null/*Z_NULL*/;
  23458. ret = inflateReset2(strm, windowBits);
  23459. if (ret !== Z_OK) {
  23460. strm.state = null/*Z_NULL*/;
  23461. }
  23462. return ret;
  23463. }
  23464. function inflateInit(strm) {
  23465. return inflateInit2(strm, DEF_WBITS);
  23466. }
  23467. /*
  23468. Return state with length and distance decoding tables and index sizes set to
  23469. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  23470. If BUILDFIXED is defined, then instead this routine builds the tables the
  23471. first time it's called, and returns those tables the first time and
  23472. thereafter. This reduces the size of the code by about 2K bytes, in
  23473. exchange for a little execution time. However, BUILDFIXED should not be
  23474. used for threaded applications, since the rewriting of the tables and virgin
  23475. may not be thread-safe.
  23476. */
  23477. var virgin = true;
  23478. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  23479. function fixedtables(state) {
  23480. /* build fixed huffman tables if first call (may not be thread safe) */
  23481. if (virgin) {
  23482. var sym;
  23483. lenfix = new utils.Buf32(512);
  23484. distfix = new utils.Buf32(32);
  23485. /* literal/length table */
  23486. sym = 0;
  23487. while (sym < 144) { state.lens[sym++] = 8; }
  23488. while (sym < 256) { state.lens[sym++] = 9; }
  23489. while (sym < 280) { state.lens[sym++] = 7; }
  23490. while (sym < 288) { state.lens[sym++] = 8; }
  23491. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  23492. /* distance table */
  23493. sym = 0;
  23494. while (sym < 32) { state.lens[sym++] = 5; }
  23495. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  23496. /* do this just once */
  23497. virgin = false;
  23498. }
  23499. state.lencode = lenfix;
  23500. state.lenbits = 9;
  23501. state.distcode = distfix;
  23502. state.distbits = 5;
  23503. }
  23504. /*
  23505. Update the window with the last wsize (normally 32K) bytes written before
  23506. returning. If window does not exist yet, create it. This is only called
  23507. when a window is already in use, or when output has been written during this
  23508. inflate call, but the end of the deflate stream has not been reached yet.
  23509. It is also called to create a window for dictionary data when a dictionary
  23510. is loaded.
  23511. Providing output buffers larger than 32K to inflate() should provide a speed
  23512. advantage, since only the last 32K of output is copied to the sliding window
  23513. upon return from inflate(), and since all distances after the first 32K of
  23514. output will fall in the output data, making match copies simpler and faster.
  23515. The advantage may be dependent on the size of the processor's data caches.
  23516. */
  23517. function updatewindow(strm, src, end, copy) {
  23518. var dist;
  23519. var state = strm.state;
  23520. /* if it hasn't been done already, allocate space for the window */
  23521. if (state.window === null) {
  23522. state.wsize = 1 << state.wbits;
  23523. state.wnext = 0;
  23524. state.whave = 0;
  23525. state.window = new utils.Buf8(state.wsize);
  23526. }
  23527. /* copy state->wsize or less output bytes into the circular window */
  23528. if (copy >= state.wsize) {
  23529. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  23530. state.wnext = 0;
  23531. state.whave = state.wsize;
  23532. }
  23533. else {
  23534. dist = state.wsize - state.wnext;
  23535. if (dist > copy) {
  23536. dist = copy;
  23537. }
  23538. //zmemcpy(state->window + state->wnext, end - copy, dist);
  23539. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  23540. copy -= dist;
  23541. if (copy) {
  23542. //zmemcpy(state->window, end - copy, copy);
  23543. utils.arraySet(state.window,src, end - copy, copy, 0);
  23544. state.wnext = copy;
  23545. state.whave = state.wsize;
  23546. }
  23547. else {
  23548. state.wnext += dist;
  23549. if (state.wnext === state.wsize) { state.wnext = 0; }
  23550. if (state.whave < state.wsize) { state.whave += dist; }
  23551. }
  23552. }
  23553. return 0;
  23554. }
  23555. function inflate(strm, flush) {
  23556. var state;
  23557. var input, output; // input/output buffers
  23558. var next; /* next input INDEX */
  23559. var put; /* next output INDEX */
  23560. var have, left; /* available input and output */
  23561. var hold; /* bit buffer */
  23562. var bits; /* bits in bit buffer */
  23563. var _in, _out; /* save starting available input and output */
  23564. var copy; /* number of stored or match bytes to copy */
  23565. var from; /* where to copy match bytes from */
  23566. var from_source;
  23567. var here = 0; /* current decoding table entry */
  23568. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  23569. //var last; /* parent table entry */
  23570. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  23571. var len; /* length to copy for repeats, bits to drop */
  23572. var ret; /* return code */
  23573. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  23574. var opts;
  23575. var n; // temporary var for NEED_BITS
  23576. var order = /* permutation of code lengths */
  23577. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  23578. if (!strm || !strm.state || !strm.output ||
  23579. (!strm.input && strm.avail_in !== 0)) {
  23580. return Z_STREAM_ERROR;
  23581. }
  23582. state = strm.state;
  23583. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  23584. //--- LOAD() ---
  23585. put = strm.next_out;
  23586. output = strm.output;
  23587. left = strm.avail_out;
  23588. next = strm.next_in;
  23589. input = strm.input;
  23590. have = strm.avail_in;
  23591. hold = state.hold;
  23592. bits = state.bits;
  23593. //---
  23594. _in = have;
  23595. _out = left;
  23596. ret = Z_OK;
  23597. inf_leave: // goto emulation
  23598. for (;;) {
  23599. switch (state.mode) {
  23600. case HEAD:
  23601. if (state.wrap === 0) {
  23602. state.mode = TYPEDO;
  23603. break;
  23604. }
  23605. //=== NEEDBITS(16);
  23606. while (bits < 16) {
  23607. if (have === 0) { break inf_leave; }
  23608. have--;
  23609. hold += input[next++] << bits;
  23610. bits += 8;
  23611. }
  23612. //===//
  23613. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  23614. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  23615. //=== CRC2(state.check, hold);
  23616. hbuf[0] = hold & 0xff;
  23617. hbuf[1] = (hold >>> 8) & 0xff;
  23618. state.check = crc32(state.check, hbuf, 2, 0);
  23619. //===//
  23620. //=== INITBITS();
  23621. hold = 0;
  23622. bits = 0;
  23623. //===//
  23624. state.mode = FLAGS;
  23625. break;
  23626. }
  23627. state.flags = 0; /* expect zlib header */
  23628. if (state.head) {
  23629. state.head.done = false;
  23630. }
  23631. if (!(state.wrap & 1) || /* check if zlib header allowed */
  23632. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  23633. strm.msg = 'incorrect header check';
  23634. state.mode = BAD;
  23635. break;
  23636. }
  23637. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  23638. strm.msg = 'unknown compression method';
  23639. state.mode = BAD;
  23640. break;
  23641. }
  23642. //--- DROPBITS(4) ---//
  23643. hold >>>= 4;
  23644. bits -= 4;
  23645. //---//
  23646. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  23647. if (state.wbits === 0) {
  23648. state.wbits = len;
  23649. }
  23650. else if (len > state.wbits) {
  23651. strm.msg = 'invalid window size';
  23652. state.mode = BAD;
  23653. break;
  23654. }
  23655. state.dmax = 1 << len;
  23656. //Tracev((stderr, "inflate: zlib header ok\n"));
  23657. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23658. state.mode = hold & 0x200 ? DICTID : TYPE;
  23659. //=== INITBITS();
  23660. hold = 0;
  23661. bits = 0;
  23662. //===//
  23663. break;
  23664. case FLAGS:
  23665. //=== NEEDBITS(16); */
  23666. while (bits < 16) {
  23667. if (have === 0) { break inf_leave; }
  23668. have--;
  23669. hold += input[next++] << bits;
  23670. bits += 8;
  23671. }
  23672. //===//
  23673. state.flags = hold;
  23674. if ((state.flags & 0xff) !== Z_DEFLATED) {
  23675. strm.msg = 'unknown compression method';
  23676. state.mode = BAD;
  23677. break;
  23678. }
  23679. if (state.flags & 0xe000) {
  23680. strm.msg = 'unknown header flags set';
  23681. state.mode = BAD;
  23682. break;
  23683. }
  23684. if (state.head) {
  23685. state.head.text = ((hold >> 8) & 1);
  23686. }
  23687. if (state.flags & 0x0200) {
  23688. //=== CRC2(state.check, hold);
  23689. hbuf[0] = hold & 0xff;
  23690. hbuf[1] = (hold >>> 8) & 0xff;
  23691. state.check = crc32(state.check, hbuf, 2, 0);
  23692. //===//
  23693. }
  23694. //=== INITBITS();
  23695. hold = 0;
  23696. bits = 0;
  23697. //===//
  23698. state.mode = TIME;
  23699. /* falls through */
  23700. case TIME:
  23701. //=== NEEDBITS(32); */
  23702. while (bits < 32) {
  23703. if (have === 0) { break inf_leave; }
  23704. have--;
  23705. hold += input[next++] << bits;
  23706. bits += 8;
  23707. }
  23708. //===//
  23709. if (state.head) {
  23710. state.head.time = hold;
  23711. }
  23712. if (state.flags & 0x0200) {
  23713. //=== CRC4(state.check, hold)
  23714. hbuf[0] = hold & 0xff;
  23715. hbuf[1] = (hold >>> 8) & 0xff;
  23716. hbuf[2] = (hold >>> 16) & 0xff;
  23717. hbuf[3] = (hold >>> 24) & 0xff;
  23718. state.check = crc32(state.check, hbuf, 4, 0);
  23719. //===
  23720. }
  23721. //=== INITBITS();
  23722. hold = 0;
  23723. bits = 0;
  23724. //===//
  23725. state.mode = OS;
  23726. /* falls through */
  23727. case OS:
  23728. //=== NEEDBITS(16); */
  23729. while (bits < 16) {
  23730. if (have === 0) { break inf_leave; }
  23731. have--;
  23732. hold += input[next++] << bits;
  23733. bits += 8;
  23734. }
  23735. //===//
  23736. if (state.head) {
  23737. state.head.xflags = (hold & 0xff);
  23738. state.head.os = (hold >> 8);
  23739. }
  23740. if (state.flags & 0x0200) {
  23741. //=== CRC2(state.check, hold);
  23742. hbuf[0] = hold & 0xff;
  23743. hbuf[1] = (hold >>> 8) & 0xff;
  23744. state.check = crc32(state.check, hbuf, 2, 0);
  23745. //===//
  23746. }
  23747. //=== INITBITS();
  23748. hold = 0;
  23749. bits = 0;
  23750. //===//
  23751. state.mode = EXLEN;
  23752. /* falls through */
  23753. case EXLEN:
  23754. if (state.flags & 0x0400) {
  23755. //=== NEEDBITS(16); */
  23756. while (bits < 16) {
  23757. if (have === 0) { break inf_leave; }
  23758. have--;
  23759. hold += input[next++] << bits;
  23760. bits += 8;
  23761. }
  23762. //===//
  23763. state.length = hold;
  23764. if (state.head) {
  23765. state.head.extra_len = hold;
  23766. }
  23767. if (state.flags & 0x0200) {
  23768. //=== CRC2(state.check, hold);
  23769. hbuf[0] = hold & 0xff;
  23770. hbuf[1] = (hold >>> 8) & 0xff;
  23771. state.check = crc32(state.check, hbuf, 2, 0);
  23772. //===//
  23773. }
  23774. //=== INITBITS();
  23775. hold = 0;
  23776. bits = 0;
  23777. //===//
  23778. }
  23779. else if (state.head) {
  23780. state.head.extra = null/*Z_NULL*/;
  23781. }
  23782. state.mode = EXTRA;
  23783. /* falls through */
  23784. case EXTRA:
  23785. if (state.flags & 0x0400) {
  23786. copy = state.length;
  23787. if (copy > have) { copy = have; }
  23788. if (copy) {
  23789. if (state.head) {
  23790. len = state.head.extra_len - state.length;
  23791. if (!state.head.extra) {
  23792. // Use untyped array for more conveniend processing later
  23793. state.head.extra = new Array(state.head.extra_len);
  23794. }
  23795. utils.arraySet(
  23796. state.head.extra,
  23797. input,
  23798. next,
  23799. // extra field is limited to 65536 bytes
  23800. // - no need for additional size check
  23801. copy,
  23802. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  23803. len
  23804. );
  23805. //zmemcpy(state.head.extra + len, next,
  23806. // len + copy > state.head.extra_max ?
  23807. // state.head.extra_max - len : copy);
  23808. }
  23809. if (state.flags & 0x0200) {
  23810. state.check = crc32(state.check, input, copy, next);
  23811. }
  23812. have -= copy;
  23813. next += copy;
  23814. state.length -= copy;
  23815. }
  23816. if (state.length) { break inf_leave; }
  23817. }
  23818. state.length = 0;
  23819. state.mode = NAME;
  23820. /* falls through */
  23821. case NAME:
  23822. if (state.flags & 0x0800) {
  23823. if (have === 0) { break inf_leave; }
  23824. copy = 0;
  23825. do {
  23826. // TODO: 2 or 1 bytes?
  23827. len = input[next + copy++];
  23828. /* use constant limit because in js we should not preallocate memory */
  23829. if (state.head && len &&
  23830. (state.length < 65536 /*state.head.name_max*/)) {
  23831. state.head.name += String.fromCharCode(len);
  23832. }
  23833. } while (len && copy < have);
  23834. if (state.flags & 0x0200) {
  23835. state.check = crc32(state.check, input, copy, next);
  23836. }
  23837. have -= copy;
  23838. next += copy;
  23839. if (len) { break inf_leave; }
  23840. }
  23841. else if (state.head) {
  23842. state.head.name = null;
  23843. }
  23844. state.length = 0;
  23845. state.mode = COMMENT;
  23846. /* falls through */
  23847. case COMMENT:
  23848. if (state.flags & 0x1000) {
  23849. if (have === 0) { break inf_leave; }
  23850. copy = 0;
  23851. do {
  23852. len = input[next + copy++];
  23853. /* use constant limit because in js we should not preallocate memory */
  23854. if (state.head && len &&
  23855. (state.length < 65536 /*state.head.comm_max*/)) {
  23856. state.head.comment += String.fromCharCode(len);
  23857. }
  23858. } while (len && copy < have);
  23859. if (state.flags & 0x0200) {
  23860. state.check = crc32(state.check, input, copy, next);
  23861. }
  23862. have -= copy;
  23863. next += copy;
  23864. if (len) { break inf_leave; }
  23865. }
  23866. else if (state.head) {
  23867. state.head.comment = null;
  23868. }
  23869. state.mode = HCRC;
  23870. /* falls through */
  23871. case HCRC:
  23872. if (state.flags & 0x0200) {
  23873. //=== NEEDBITS(16); */
  23874. while (bits < 16) {
  23875. if (have === 0) { break inf_leave; }
  23876. have--;
  23877. hold += input[next++] << bits;
  23878. bits += 8;
  23879. }
  23880. //===//
  23881. if (hold !== (state.check & 0xffff)) {
  23882. strm.msg = 'header crc mismatch';
  23883. state.mode = BAD;
  23884. break;
  23885. }
  23886. //=== INITBITS();
  23887. hold = 0;
  23888. bits = 0;
  23889. //===//
  23890. }
  23891. if (state.head) {
  23892. state.head.hcrc = ((state.flags >> 9) & 1);
  23893. state.head.done = true;
  23894. }
  23895. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  23896. state.mode = TYPE;
  23897. break;
  23898. case DICTID:
  23899. //=== NEEDBITS(32); */
  23900. while (bits < 32) {
  23901. if (have === 0) { break inf_leave; }
  23902. have--;
  23903. hold += input[next++] << bits;
  23904. bits += 8;
  23905. }
  23906. //===//
  23907. strm.adler = state.check = ZSWAP32(hold);
  23908. //=== INITBITS();
  23909. hold = 0;
  23910. bits = 0;
  23911. //===//
  23912. state.mode = DICT;
  23913. /* falls through */
  23914. case DICT:
  23915. if (state.havedict === 0) {
  23916. //--- RESTORE() ---
  23917. strm.next_out = put;
  23918. strm.avail_out = left;
  23919. strm.next_in = next;
  23920. strm.avail_in = have;
  23921. state.hold = hold;
  23922. state.bits = bits;
  23923. //---
  23924. return Z_NEED_DICT;
  23925. }
  23926. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23927. state.mode = TYPE;
  23928. /* falls through */
  23929. case TYPE:
  23930. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  23931. /* falls through */
  23932. case TYPEDO:
  23933. if (state.last) {
  23934. //--- BYTEBITS() ---//
  23935. hold >>>= bits & 7;
  23936. bits -= bits & 7;
  23937. //---//
  23938. state.mode = CHECK;
  23939. break;
  23940. }
  23941. //=== NEEDBITS(3); */
  23942. while (bits < 3) {
  23943. if (have === 0) { break inf_leave; }
  23944. have--;
  23945. hold += input[next++] << bits;
  23946. bits += 8;
  23947. }
  23948. //===//
  23949. state.last = (hold & 0x01)/*BITS(1)*/;
  23950. //--- DROPBITS(1) ---//
  23951. hold >>>= 1;
  23952. bits -= 1;
  23953. //---//
  23954. switch ((hold & 0x03)/*BITS(2)*/) {
  23955. case 0: /* stored block */
  23956. //Tracev((stderr, "inflate: stored block%s\n",
  23957. // state.last ? " (last)" : ""));
  23958. state.mode = STORED;
  23959. break;
  23960. case 1: /* fixed block */
  23961. fixedtables(state);
  23962. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23963. // state.last ? " (last)" : ""));
  23964. state.mode = LEN_; /* decode codes */
  23965. if (flush === Z_TREES) {
  23966. //--- DROPBITS(2) ---//
  23967. hold >>>= 2;
  23968. bits -= 2;
  23969. //---//
  23970. break inf_leave;
  23971. }
  23972. break;
  23973. case 2: /* dynamic block */
  23974. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23975. // state.last ? " (last)" : ""));
  23976. state.mode = TABLE;
  23977. break;
  23978. case 3:
  23979. strm.msg = 'invalid block type';
  23980. state.mode = BAD;
  23981. }
  23982. //--- DROPBITS(2) ---//
  23983. hold >>>= 2;
  23984. bits -= 2;
  23985. //---//
  23986. break;
  23987. case STORED:
  23988. //--- BYTEBITS() ---// /* go to byte boundary */
  23989. hold >>>= bits & 7;
  23990. bits -= bits & 7;
  23991. //---//
  23992. //=== NEEDBITS(32); */
  23993. while (bits < 32) {
  23994. if (have === 0) { break inf_leave; }
  23995. have--;
  23996. hold += input[next++] << bits;
  23997. bits += 8;
  23998. }
  23999. //===//
  24000. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  24001. strm.msg = 'invalid stored block lengths';
  24002. state.mode = BAD;
  24003. break;
  24004. }
  24005. state.length = hold & 0xffff;
  24006. //Tracev((stderr, "inflate: stored length %u\n",
  24007. // state.length));
  24008. //=== INITBITS();
  24009. hold = 0;
  24010. bits = 0;
  24011. //===//
  24012. state.mode = COPY_;
  24013. if (flush === Z_TREES) { break inf_leave; }
  24014. /* falls through */
  24015. case COPY_:
  24016. state.mode = COPY;
  24017. /* falls through */
  24018. case COPY:
  24019. copy = state.length;
  24020. if (copy) {
  24021. if (copy > have) { copy = have; }
  24022. if (copy > left) { copy = left; }
  24023. if (copy === 0) { break inf_leave; }
  24024. //--- zmemcpy(put, next, copy); ---
  24025. utils.arraySet(output, input, next, copy, put);
  24026. //---//
  24027. have -= copy;
  24028. next += copy;
  24029. left -= copy;
  24030. put += copy;
  24031. state.length -= copy;
  24032. break;
  24033. }
  24034. //Tracev((stderr, "inflate: stored end\n"));
  24035. state.mode = TYPE;
  24036. break;
  24037. case TABLE:
  24038. //=== NEEDBITS(14); */
  24039. while (bits < 14) {
  24040. if (have === 0) { break inf_leave; }
  24041. have--;
  24042. hold += input[next++] << bits;
  24043. bits += 8;
  24044. }
  24045. //===//
  24046. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  24047. //--- DROPBITS(5) ---//
  24048. hold >>>= 5;
  24049. bits -= 5;
  24050. //---//
  24051. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  24052. //--- DROPBITS(5) ---//
  24053. hold >>>= 5;
  24054. bits -= 5;
  24055. //---//
  24056. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  24057. //--- DROPBITS(4) ---//
  24058. hold >>>= 4;
  24059. bits -= 4;
  24060. //---//
  24061. //#ifndef PKZIP_BUG_WORKAROUND
  24062. if (state.nlen > 286 || state.ndist > 30) {
  24063. strm.msg = 'too many length or distance symbols';
  24064. state.mode = BAD;
  24065. break;
  24066. }
  24067. //#endif
  24068. //Tracev((stderr, "inflate: table sizes ok\n"));
  24069. state.have = 0;
  24070. state.mode = LENLENS;
  24071. /* falls through */
  24072. case LENLENS:
  24073. while (state.have < state.ncode) {
  24074. //=== NEEDBITS(3);
  24075. while (bits < 3) {
  24076. if (have === 0) { break inf_leave; }
  24077. have--;
  24078. hold += input[next++] << bits;
  24079. bits += 8;
  24080. }
  24081. //===//
  24082. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  24083. //--- DROPBITS(3) ---//
  24084. hold >>>= 3;
  24085. bits -= 3;
  24086. //---//
  24087. }
  24088. while (state.have < 19) {
  24089. state.lens[order[state.have++]] = 0;
  24090. }
  24091. // We have separate tables & no pointers. 2 commented lines below not needed.
  24092. //state.next = state.codes;
  24093. //state.lencode = state.next;
  24094. // Switch to use dynamic table
  24095. state.lencode = state.lendyn;
  24096. state.lenbits = 7;
  24097. opts = {bits: state.lenbits};
  24098. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  24099. state.lenbits = opts.bits;
  24100. if (ret) {
  24101. strm.msg = 'invalid code lengths set';
  24102. state.mode = BAD;
  24103. break;
  24104. }
  24105. //Tracev((stderr, "inflate: code lengths ok\n"));
  24106. state.have = 0;
  24107. state.mode = CODELENS;
  24108. /* falls through */
  24109. case CODELENS:
  24110. while (state.have < state.nlen + state.ndist) {
  24111. for (;;) {
  24112. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  24113. here_bits = here >>> 24;
  24114. here_op = (here >>> 16) & 0xff;
  24115. here_val = here & 0xffff;
  24116. if ((here_bits) <= bits) { break; }
  24117. //--- PULLBYTE() ---//
  24118. if (have === 0) { break inf_leave; }
  24119. have--;
  24120. hold += input[next++] << bits;
  24121. bits += 8;
  24122. //---//
  24123. }
  24124. if (here_val < 16) {
  24125. //--- DROPBITS(here.bits) ---//
  24126. hold >>>= here_bits;
  24127. bits -= here_bits;
  24128. //---//
  24129. state.lens[state.have++] = here_val;
  24130. }
  24131. else {
  24132. if (here_val === 16) {
  24133. //=== NEEDBITS(here.bits + 2);
  24134. n = here_bits + 2;
  24135. while (bits < n) {
  24136. if (have === 0) { break inf_leave; }
  24137. have--;
  24138. hold += input[next++] << bits;
  24139. bits += 8;
  24140. }
  24141. //===//
  24142. //--- DROPBITS(here.bits) ---//
  24143. hold >>>= here_bits;
  24144. bits -= here_bits;
  24145. //---//
  24146. if (state.have === 0) {
  24147. strm.msg = 'invalid bit length repeat';
  24148. state.mode = BAD;
  24149. break;
  24150. }
  24151. len = state.lens[state.have - 1];
  24152. copy = 3 + (hold & 0x03);//BITS(2);
  24153. //--- DROPBITS(2) ---//
  24154. hold >>>= 2;
  24155. bits -= 2;
  24156. //---//
  24157. }
  24158. else if (here_val === 17) {
  24159. //=== NEEDBITS(here.bits + 3);
  24160. n = here_bits + 3;
  24161. while (bits < n) {
  24162. if (have === 0) { break inf_leave; }
  24163. have--;
  24164. hold += input[next++] << bits;
  24165. bits += 8;
  24166. }
  24167. //===//
  24168. //--- DROPBITS(here.bits) ---//
  24169. hold >>>= here_bits;
  24170. bits -= here_bits;
  24171. //---//
  24172. len = 0;
  24173. copy = 3 + (hold & 0x07);//BITS(3);
  24174. //--- DROPBITS(3) ---//
  24175. hold >>>= 3;
  24176. bits -= 3;
  24177. //---//
  24178. }
  24179. else {
  24180. //=== NEEDBITS(here.bits + 7);
  24181. n = here_bits + 7;
  24182. while (bits < n) {
  24183. if (have === 0) { break inf_leave; }
  24184. have--;
  24185. hold += input[next++] << bits;
  24186. bits += 8;
  24187. }
  24188. //===//
  24189. //--- DROPBITS(here.bits) ---//
  24190. hold >>>= here_bits;
  24191. bits -= here_bits;
  24192. //---//
  24193. len = 0;
  24194. copy = 11 + (hold & 0x7f);//BITS(7);
  24195. //--- DROPBITS(7) ---//
  24196. hold >>>= 7;
  24197. bits -= 7;
  24198. //---//
  24199. }
  24200. if (state.have + copy > state.nlen + state.ndist) {
  24201. strm.msg = 'invalid bit length repeat';
  24202. state.mode = BAD;
  24203. break;
  24204. }
  24205. while (copy--) {
  24206. state.lens[state.have++] = len;
  24207. }
  24208. }
  24209. }
  24210. /* handle error breaks in while */
  24211. if (state.mode === BAD) { break; }
  24212. /* check for end-of-block code (better have one) */
  24213. if (state.lens[256] === 0) {
  24214. strm.msg = 'invalid code -- missing end-of-block';
  24215. state.mode = BAD;
  24216. break;
  24217. }
  24218. /* build code tables -- note: do not change the lenbits or distbits
  24219. values here (9 and 6) without reading the comments in inftrees.h
  24220. concerning the ENOUGH constants, which depend on those values */
  24221. state.lenbits = 9;
  24222. opts = {bits: state.lenbits};
  24223. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  24224. // We have separate tables & no pointers. 2 commented lines below not needed.
  24225. // state.next_index = opts.table_index;
  24226. state.lenbits = opts.bits;
  24227. // state.lencode = state.next;
  24228. if (ret) {
  24229. strm.msg = 'invalid literal/lengths set';
  24230. state.mode = BAD;
  24231. break;
  24232. }
  24233. state.distbits = 6;
  24234. //state.distcode.copy(state.codes);
  24235. // Switch to use dynamic table
  24236. state.distcode = state.distdyn;
  24237. opts = {bits: state.distbits};
  24238. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  24239. // We have separate tables & no pointers. 2 commented lines below not needed.
  24240. // state.next_index = opts.table_index;
  24241. state.distbits = opts.bits;
  24242. // state.distcode = state.next;
  24243. if (ret) {
  24244. strm.msg = 'invalid distances set';
  24245. state.mode = BAD;
  24246. break;
  24247. }
  24248. //Tracev((stderr, 'inflate: codes ok\n'));
  24249. state.mode = LEN_;
  24250. if (flush === Z_TREES) { break inf_leave; }
  24251. /* falls through */
  24252. case LEN_:
  24253. state.mode = LEN;
  24254. /* falls through */
  24255. case LEN:
  24256. if (have >= 6 && left >= 258) {
  24257. //--- RESTORE() ---
  24258. strm.next_out = put;
  24259. strm.avail_out = left;
  24260. strm.next_in = next;
  24261. strm.avail_in = have;
  24262. state.hold = hold;
  24263. state.bits = bits;
  24264. //---
  24265. inflate_fast(strm, _out);
  24266. //--- LOAD() ---
  24267. put = strm.next_out;
  24268. output = strm.output;
  24269. left = strm.avail_out;
  24270. next = strm.next_in;
  24271. input = strm.input;
  24272. have = strm.avail_in;
  24273. hold = state.hold;
  24274. bits = state.bits;
  24275. //---
  24276. if (state.mode === TYPE) {
  24277. state.back = -1;
  24278. }
  24279. break;
  24280. }
  24281. state.back = 0;
  24282. for (;;) {
  24283. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  24284. here_bits = here >>> 24;
  24285. here_op = (here >>> 16) & 0xff;
  24286. here_val = here & 0xffff;
  24287. if (here_bits <= bits) { break; }
  24288. //--- PULLBYTE() ---//
  24289. if (have === 0) { break inf_leave; }
  24290. have--;
  24291. hold += input[next++] << bits;
  24292. bits += 8;
  24293. //---//
  24294. }
  24295. if (here_op && (here_op & 0xf0) === 0) {
  24296. last_bits = here_bits;
  24297. last_op = here_op;
  24298. last_val = here_val;
  24299. for (;;) {
  24300. here = state.lencode[last_val +
  24301. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  24302. here_bits = here >>> 24;
  24303. here_op = (here >>> 16) & 0xff;
  24304. here_val = here & 0xffff;
  24305. if ((last_bits + here_bits) <= bits) { break; }
  24306. //--- PULLBYTE() ---//
  24307. if (have === 0) { break inf_leave; }
  24308. have--;
  24309. hold += input[next++] << bits;
  24310. bits += 8;
  24311. //---//
  24312. }
  24313. //--- DROPBITS(last.bits) ---//
  24314. hold >>>= last_bits;
  24315. bits -= last_bits;
  24316. //---//
  24317. state.back += last_bits;
  24318. }
  24319. //--- DROPBITS(here.bits) ---//
  24320. hold >>>= here_bits;
  24321. bits -= here_bits;
  24322. //---//
  24323. state.back += here_bits;
  24324. state.length = here_val;
  24325. if (here_op === 0) {
  24326. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  24327. // "inflate: literal '%c'\n" :
  24328. // "inflate: literal 0x%02x\n", here.val));
  24329. state.mode = LIT;
  24330. break;
  24331. }
  24332. if (here_op & 32) {
  24333. //Tracevv((stderr, "inflate: end of block\n"));
  24334. state.back = -1;
  24335. state.mode = TYPE;
  24336. break;
  24337. }
  24338. if (here_op & 64) {
  24339. strm.msg = 'invalid literal/length code';
  24340. state.mode = BAD;
  24341. break;
  24342. }
  24343. state.extra = here_op & 15;
  24344. state.mode = LENEXT;
  24345. /* falls through */
  24346. case LENEXT:
  24347. if (state.extra) {
  24348. //=== NEEDBITS(state.extra);
  24349. n = state.extra;
  24350. while (bits < n) {
  24351. if (have === 0) { break inf_leave; }
  24352. have--;
  24353. hold += input[next++] << bits;
  24354. bits += 8;
  24355. }
  24356. //===//
  24357. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  24358. //--- DROPBITS(state.extra) ---//
  24359. hold >>>= state.extra;
  24360. bits -= state.extra;
  24361. //---//
  24362. state.back += state.extra;
  24363. }
  24364. //Tracevv((stderr, "inflate: length %u\n", state.length));
  24365. state.was = state.length;
  24366. state.mode = DIST;
  24367. /* falls through */
  24368. case DIST:
  24369. for (;;) {
  24370. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  24371. here_bits = here >>> 24;
  24372. here_op = (here >>> 16) & 0xff;
  24373. here_val = here & 0xffff;
  24374. if ((here_bits) <= bits) { break; }
  24375. //--- PULLBYTE() ---//
  24376. if (have === 0) { break inf_leave; }
  24377. have--;
  24378. hold += input[next++] << bits;
  24379. bits += 8;
  24380. //---//
  24381. }
  24382. if ((here_op & 0xf0) === 0) {
  24383. last_bits = here_bits;
  24384. last_op = here_op;
  24385. last_val = here_val;
  24386. for (;;) {
  24387. here = state.distcode[last_val +
  24388. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  24389. here_bits = here >>> 24;
  24390. here_op = (here >>> 16) & 0xff;
  24391. here_val = here & 0xffff;
  24392. if ((last_bits + here_bits) <= bits) { break; }
  24393. //--- PULLBYTE() ---//
  24394. if (have === 0) { break inf_leave; }
  24395. have--;
  24396. hold += input[next++] << bits;
  24397. bits += 8;
  24398. //---//
  24399. }
  24400. //--- DROPBITS(last.bits) ---//
  24401. hold >>>= last_bits;
  24402. bits -= last_bits;
  24403. //---//
  24404. state.back += last_bits;
  24405. }
  24406. //--- DROPBITS(here.bits) ---//
  24407. hold >>>= here_bits;
  24408. bits -= here_bits;
  24409. //---//
  24410. state.back += here_bits;
  24411. if (here_op & 64) {
  24412. strm.msg = 'invalid distance code';
  24413. state.mode = BAD;
  24414. break;
  24415. }
  24416. state.offset = here_val;
  24417. state.extra = (here_op) & 15;
  24418. state.mode = DISTEXT;
  24419. /* falls through */
  24420. case DISTEXT:
  24421. if (state.extra) {
  24422. //=== NEEDBITS(state.extra);
  24423. n = state.extra;
  24424. while (bits < n) {
  24425. if (have === 0) { break inf_leave; }
  24426. have--;
  24427. hold += input[next++] << bits;
  24428. bits += 8;
  24429. }
  24430. //===//
  24431. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  24432. //--- DROPBITS(state.extra) ---//
  24433. hold >>>= state.extra;
  24434. bits -= state.extra;
  24435. //---//
  24436. state.back += state.extra;
  24437. }
  24438. //#ifdef INFLATE_STRICT
  24439. if (state.offset > state.dmax) {
  24440. strm.msg = 'invalid distance too far back';
  24441. state.mode = BAD;
  24442. break;
  24443. }
  24444. //#endif
  24445. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  24446. state.mode = MATCH;
  24447. /* falls through */
  24448. case MATCH:
  24449. if (left === 0) { break inf_leave; }
  24450. copy = _out - left;
  24451. if (state.offset > copy) { /* copy from window */
  24452. copy = state.offset - copy;
  24453. if (copy > state.whave) {
  24454. if (state.sane) {
  24455. strm.msg = 'invalid distance too far back';
  24456. state.mode = BAD;
  24457. break;
  24458. }
  24459. // (!) This block is disabled in zlib defailts,
  24460. // don't enable it for binary compatibility
  24461. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  24462. // Trace((stderr, "inflate.c too far\n"));
  24463. // copy -= state.whave;
  24464. // if (copy > state.length) { copy = state.length; }
  24465. // if (copy > left) { copy = left; }
  24466. // left -= copy;
  24467. // state.length -= copy;
  24468. // do {
  24469. // output[put++] = 0;
  24470. // } while (--copy);
  24471. // if (state.length === 0) { state.mode = LEN; }
  24472. // break;
  24473. //#endif
  24474. }
  24475. if (copy > state.wnext) {
  24476. copy -= state.wnext;
  24477. from = state.wsize - copy;
  24478. }
  24479. else {
  24480. from = state.wnext - copy;
  24481. }
  24482. if (copy > state.length) { copy = state.length; }
  24483. from_source = state.window;
  24484. }
  24485. else { /* copy from output */
  24486. from_source = output;
  24487. from = put - state.offset;
  24488. copy = state.length;
  24489. }
  24490. if (copy > left) { copy = left; }
  24491. left -= copy;
  24492. state.length -= copy;
  24493. do {
  24494. output[put++] = from_source[from++];
  24495. } while (--copy);
  24496. if (state.length === 0) { state.mode = LEN; }
  24497. break;
  24498. case LIT:
  24499. if (left === 0) { break inf_leave; }
  24500. output[put++] = state.length;
  24501. left--;
  24502. state.mode = LEN;
  24503. break;
  24504. case CHECK:
  24505. if (state.wrap) {
  24506. //=== NEEDBITS(32);
  24507. while (bits < 32) {
  24508. if (have === 0) { break inf_leave; }
  24509. have--;
  24510. // Use '|' insdead of '+' to make sure that result is signed
  24511. hold |= input[next++] << bits;
  24512. bits += 8;
  24513. }
  24514. //===//
  24515. _out -= left;
  24516. strm.total_out += _out;
  24517. state.total += _out;
  24518. if (_out) {
  24519. strm.adler = state.check =
  24520. /*UPDATE(state.check, put - _out, _out);*/
  24521. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  24522. }
  24523. _out = left;
  24524. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  24525. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  24526. strm.msg = 'incorrect data check';
  24527. state.mode = BAD;
  24528. break;
  24529. }
  24530. //=== INITBITS();
  24531. hold = 0;
  24532. bits = 0;
  24533. //===//
  24534. //Tracev((stderr, "inflate: check matches trailer\n"));
  24535. }
  24536. state.mode = LENGTH;
  24537. /* falls through */
  24538. case LENGTH:
  24539. if (state.wrap && state.flags) {
  24540. //=== NEEDBITS(32);
  24541. while (bits < 32) {
  24542. if (have === 0) { break inf_leave; }
  24543. have--;
  24544. hold += input[next++] << bits;
  24545. bits += 8;
  24546. }
  24547. //===//
  24548. if (hold !== (state.total & 0xffffffff)) {
  24549. strm.msg = 'incorrect length check';
  24550. state.mode = BAD;
  24551. break;
  24552. }
  24553. //=== INITBITS();
  24554. hold = 0;
  24555. bits = 0;
  24556. //===//
  24557. //Tracev((stderr, "inflate: length matches trailer\n"));
  24558. }
  24559. state.mode = DONE;
  24560. /* falls through */
  24561. case DONE:
  24562. ret = Z_STREAM_END;
  24563. break inf_leave;
  24564. case BAD:
  24565. ret = Z_DATA_ERROR;
  24566. break inf_leave;
  24567. case MEM:
  24568. return Z_MEM_ERROR;
  24569. case SYNC:
  24570. /* falls through */
  24571. default:
  24572. return Z_STREAM_ERROR;
  24573. }
  24574. }
  24575. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  24576. /*
  24577. Return from inflate(), updating the total counts and the check value.
  24578. If there was no progress during the inflate() call, return a buffer
  24579. error. Call updatewindow() to create and/or update the window state.
  24580. Note: a memory error from inflate() is non-recoverable.
  24581. */
  24582. //--- RESTORE() ---
  24583. strm.next_out = put;
  24584. strm.avail_out = left;
  24585. strm.next_in = next;
  24586. strm.avail_in = have;
  24587. state.hold = hold;
  24588. state.bits = bits;
  24589. //---
  24590. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  24591. (state.mode < CHECK || flush !== Z_FINISH))) {
  24592. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  24593. state.mode = MEM;
  24594. return Z_MEM_ERROR;
  24595. }
  24596. }
  24597. _in -= strm.avail_in;
  24598. _out -= strm.avail_out;
  24599. strm.total_in += _in;
  24600. strm.total_out += _out;
  24601. state.total += _out;
  24602. if (state.wrap && _out) {
  24603. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  24604. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  24605. }
  24606. strm.data_type = state.bits + (state.last ? 64 : 0) +
  24607. (state.mode === TYPE ? 128 : 0) +
  24608. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  24609. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  24610. ret = Z_BUF_ERROR;
  24611. }
  24612. return ret;
  24613. }
  24614. function inflateEnd(strm) {
  24615. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  24616. return Z_STREAM_ERROR;
  24617. }
  24618. var state = strm.state;
  24619. if (state.window) {
  24620. state.window = null;
  24621. }
  24622. strm.state = null;
  24623. return Z_OK;
  24624. }
  24625. function inflateGetHeader(strm, head) {
  24626. var state;
  24627. /* check state */
  24628. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  24629. state = strm.state;
  24630. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  24631. /* save header structure */
  24632. state.head = head;
  24633. head.done = false;
  24634. return Z_OK;
  24635. }
  24636. exports.inflateReset = inflateReset;
  24637. exports.inflateReset2 = inflateReset2;
  24638. exports.inflateResetKeep = inflateResetKeep;
  24639. exports.inflateInit = inflateInit;
  24640. exports.inflateInit2 = inflateInit2;
  24641. exports.inflate = inflate;
  24642. exports.inflateEnd = inflateEnd;
  24643. exports.inflateGetHeader = inflateGetHeader;
  24644. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  24645. /* Not implemented
  24646. exports.inflateCopy = inflateCopy;
  24647. exports.inflateGetDictionary = inflateGetDictionary;
  24648. exports.inflateMark = inflateMark;
  24649. exports.inflatePrime = inflatePrime;
  24650. exports.inflateSetDictionary = inflateSetDictionary;
  24651. exports.inflateSync = inflateSync;
  24652. exports.inflateSyncPoint = inflateSyncPoint;
  24653. exports.inflateUndermine = inflateUndermine;
  24654. */
  24655. },{"../utils/common":80,"./adler32":82,"./crc32":84,"./inffast":87,"./inftrees":89}],89:[function(require,module,exports){
  24656. 'use strict';
  24657. var utils = require('../utils/common');
  24658. var MAXBITS = 15;
  24659. var ENOUGH_LENS = 852;
  24660. var ENOUGH_DISTS = 592;
  24661. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  24662. var CODES = 0;
  24663. var LENS = 1;
  24664. var DISTS = 2;
  24665. var lbase = [ /* Length codes 257..285 base */
  24666. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  24667. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  24668. ];
  24669. var lext = [ /* Length codes 257..285 extra */
  24670. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  24671. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  24672. ];
  24673. var dbase = [ /* Distance codes 0..29 base */
  24674. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  24675. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  24676. 8193, 12289, 16385, 24577, 0, 0
  24677. ];
  24678. var dext = [ /* Distance codes 0..29 extra */
  24679. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  24680. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  24681. 28, 28, 29, 29, 64, 64
  24682. ];
  24683. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  24684. {
  24685. var bits = opts.bits;
  24686. //here = opts.here; /* table entry for duplication */
  24687. var len = 0; /* a code's length in bits */
  24688. var sym = 0; /* index of code symbols */
  24689. var min = 0, max = 0; /* minimum and maximum code lengths */
  24690. var root = 0; /* number of index bits for root table */
  24691. var curr = 0; /* number of index bits for current table */
  24692. var drop = 0; /* code bits to drop for sub-table */
  24693. var left = 0; /* number of prefix codes available */
  24694. var used = 0; /* code entries in table used */
  24695. var huff = 0; /* Huffman code */
  24696. var incr; /* for incrementing code, index */
  24697. var fill; /* index for replicating entries */
  24698. var low; /* low bits for current root entry */
  24699. var mask; /* mask for low root bits */
  24700. var next; /* next available space in table */
  24701. var base = null; /* base value table to use */
  24702. var base_index = 0;
  24703. // var shoextra; /* extra bits table to use */
  24704. var end; /* use base and extra for symbol > end */
  24705. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  24706. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  24707. var extra = null;
  24708. var extra_index = 0;
  24709. var here_bits, here_op, here_val;
  24710. /*
  24711. Process a set of code lengths to create a canonical Huffman code. The
  24712. code lengths are lens[0..codes-1]. Each length corresponds to the
  24713. symbols 0..codes-1. The Huffman code is generated by first sorting the
  24714. symbols by length from short to long, and retaining the symbol order
  24715. for codes with equal lengths. Then the code starts with all zero bits
  24716. for the first code of the shortest length, and the codes are integer
  24717. increments for the same length, and zeros are appended as the length
  24718. increases. For the deflate format, these bits are stored backwards
  24719. from their more natural integer increment ordering, and so when the
  24720. decoding tables are built in the large loop below, the integer codes
  24721. are incremented backwards.
  24722. This routine assumes, but does not check, that all of the entries in
  24723. lens[] are in the range 0..MAXBITS. The caller must assure this.
  24724. 1..MAXBITS is interpreted as that code length. zero means that that
  24725. symbol does not occur in this code.
  24726. The codes are sorted by computing a count of codes for each length,
  24727. creating from that a table of starting indices for each length in the
  24728. sorted table, and then entering the symbols in order in the sorted
  24729. table. The sorted table is work[], with that space being provided by
  24730. the caller.
  24731. The length counts are used for other purposes as well, i.e. finding
  24732. the minimum and maximum length codes, determining if there are any
  24733. codes at all, checking for a valid set of lengths, and looking ahead
  24734. at length counts to determine sub-table sizes when building the
  24735. decoding tables.
  24736. */
  24737. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  24738. for (len = 0; len <= MAXBITS; len++) {
  24739. count[len] = 0;
  24740. }
  24741. for (sym = 0; sym < codes; sym++) {
  24742. count[lens[lens_index + sym]]++;
  24743. }
  24744. /* bound code lengths, force root to be within code lengths */
  24745. root = bits;
  24746. for (max = MAXBITS; max >= 1; max--) {
  24747. if (count[max] !== 0) { break; }
  24748. }
  24749. if (root > max) {
  24750. root = max;
  24751. }
  24752. if (max === 0) { /* no symbols to code at all */
  24753. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  24754. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  24755. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  24756. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24757. //table.op[opts.table_index] = 64;
  24758. //table.bits[opts.table_index] = 1;
  24759. //table.val[opts.table_index++] = 0;
  24760. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24761. opts.bits = 1;
  24762. return 0; /* no symbols, but wait for decoding to report error */
  24763. }
  24764. for (min = 1; min < max; min++) {
  24765. if (count[min] !== 0) { break; }
  24766. }
  24767. if (root < min) {
  24768. root = min;
  24769. }
  24770. /* check for an over-subscribed or incomplete set of lengths */
  24771. left = 1;
  24772. for (len = 1; len <= MAXBITS; len++) {
  24773. left <<= 1;
  24774. left -= count[len];
  24775. if (left < 0) {
  24776. return -1;
  24777. } /* over-subscribed */
  24778. }
  24779. if (left > 0 && (type === CODES || max !== 1)) {
  24780. return -1; /* incomplete set */
  24781. }
  24782. /* generate offsets into symbol table for each length for sorting */
  24783. offs[1] = 0;
  24784. for (len = 1; len < MAXBITS; len++) {
  24785. offs[len + 1] = offs[len] + count[len];
  24786. }
  24787. /* sort symbols by length, by symbol order within each length */
  24788. for (sym = 0; sym < codes; sym++) {
  24789. if (lens[lens_index + sym] !== 0) {
  24790. work[offs[lens[lens_index + sym]]++] = sym;
  24791. }
  24792. }
  24793. /*
  24794. Create and fill in decoding tables. In this loop, the table being
  24795. filled is at next and has curr index bits. The code being used is huff
  24796. with length len. That code is converted to an index by dropping drop
  24797. bits off of the bottom. For codes where len is less than drop + curr,
  24798. those top drop + curr - len bits are incremented through all values to
  24799. fill the table with replicated entries.
  24800. root is the number of index bits for the root table. When len exceeds
  24801. root, sub-tables are created pointed to by the root entry with an index
  24802. of the low root bits of huff. This is saved in low to check for when a
  24803. new sub-table should be started. drop is zero when the root table is
  24804. being filled, and drop is root when sub-tables are being filled.
  24805. When a new sub-table is needed, it is necessary to look ahead in the
  24806. code lengths to determine what size sub-table is needed. The length
  24807. counts are used for this, and so count[] is decremented as codes are
  24808. entered in the tables.
  24809. used keeps track of how many table entries have been allocated from the
  24810. provided *table space. It is checked for LENS and DIST tables against
  24811. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  24812. the initial root table size constants. See the comments in inftrees.h
  24813. for more information.
  24814. sym increments through all symbols, and the loop terminates when
  24815. all codes of length max, i.e. all codes, have been processed. This
  24816. routine permits incomplete codes, so another loop after this one fills
  24817. in the rest of the decoding tables with invalid code markers.
  24818. */
  24819. /* set up for code type */
  24820. // poor man optimization - use if-else instead of switch,
  24821. // to avoid deopts in old v8
  24822. if (type === CODES) {
  24823. base = extra = work; /* dummy value--not used */
  24824. end = 19;
  24825. } else if (type === LENS) {
  24826. base = lbase;
  24827. base_index -= 257;
  24828. extra = lext;
  24829. extra_index -= 257;
  24830. end = 256;
  24831. } else { /* DISTS */
  24832. base = dbase;
  24833. extra = dext;
  24834. end = -1;
  24835. }
  24836. /* initialize opts for loop */
  24837. huff = 0; /* starting code */
  24838. sym = 0; /* starting code symbol */
  24839. len = min; /* starting code length */
  24840. next = table_index; /* current table to fill in */
  24841. curr = root; /* current table index bits */
  24842. drop = 0; /* current bits to drop from code for index */
  24843. low = -1; /* trigger new sub-table when len > root */
  24844. used = 1 << root; /* use root table entries */
  24845. mask = used - 1; /* mask for comparing low */
  24846. /* check available table space */
  24847. if ((type === LENS && used > ENOUGH_LENS) ||
  24848. (type === DISTS && used > ENOUGH_DISTS)) {
  24849. return 1;
  24850. }
  24851. var i=0;
  24852. /* process all codes and make table entries */
  24853. for (;;) {
  24854. i++;
  24855. /* create table entry */
  24856. here_bits = len - drop;
  24857. if (work[sym] < end) {
  24858. here_op = 0;
  24859. here_val = work[sym];
  24860. }
  24861. else if (work[sym] > end) {
  24862. here_op = extra[extra_index + work[sym]];
  24863. here_val = base[base_index + work[sym]];
  24864. }
  24865. else {
  24866. here_op = 32 + 64; /* end of block */
  24867. here_val = 0;
  24868. }
  24869. /* replicate for those indices with low len bits equal to huff */
  24870. incr = 1 << (len - drop);
  24871. fill = 1 << curr;
  24872. min = fill; /* save offset to next table */
  24873. do {
  24874. fill -= incr;
  24875. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  24876. } while (fill !== 0);
  24877. /* backwards increment the len-bit code huff */
  24878. incr = 1 << (len - 1);
  24879. while (huff & incr) {
  24880. incr >>= 1;
  24881. }
  24882. if (incr !== 0) {
  24883. huff &= incr - 1;
  24884. huff += incr;
  24885. } else {
  24886. huff = 0;
  24887. }
  24888. /* go to next symbol, update count, len */
  24889. sym++;
  24890. if (--count[len] === 0) {
  24891. if (len === max) { break; }
  24892. len = lens[lens_index + work[sym]];
  24893. }
  24894. /* create new sub-table if needed */
  24895. if (len > root && (huff & mask) !== low) {
  24896. /* if first time, transition to sub-tables */
  24897. if (drop === 0) {
  24898. drop = root;
  24899. }
  24900. /* increment past last table */
  24901. next += min; /* here min is 1 << curr */
  24902. /* determine length of next table */
  24903. curr = len - drop;
  24904. left = 1 << curr;
  24905. while (curr + drop < max) {
  24906. left -= count[curr + drop];
  24907. if (left <= 0) { break; }
  24908. curr++;
  24909. left <<= 1;
  24910. }
  24911. /* check for enough space */
  24912. used += 1 << curr;
  24913. if ((type === LENS && used > ENOUGH_LENS) ||
  24914. (type === DISTS && used > ENOUGH_DISTS)) {
  24915. return 1;
  24916. }
  24917. /* point entry in root table to sub-table */
  24918. low = huff & mask;
  24919. /*table.op[low] = curr;
  24920. table.bits[low] = root;
  24921. table.val[low] = next - opts.table_index;*/
  24922. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  24923. }
  24924. }
  24925. /* fill in remaining table entry if code is incomplete (guaranteed to have
  24926. at most one remaining entry, since if the code is incomplete, the
  24927. maximum code length that was allowed to get this far is one bit) */
  24928. if (huff !== 0) {
  24929. //table.op[next + huff] = 64; /* invalid code marker */
  24930. //table.bits[next + huff] = len - drop;
  24931. //table.val[next + huff] = 0;
  24932. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24933. }
  24934. /* set return parameters */
  24935. //opts.table_index += used;
  24936. opts.bits = root;
  24937. return 0;
  24938. };
  24939. },{"../utils/common":80}],90:[function(require,module,exports){
  24940. 'use strict';
  24941. module.exports = {
  24942. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24943. '1': 'stream end', /* Z_STREAM_END 1 */
  24944. '0': '', /* Z_OK 0 */
  24945. '-1': 'file error', /* Z_ERRNO (-1) */
  24946. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24947. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24948. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24949. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24950. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24951. };
  24952. },{}],91:[function(require,module,exports){
  24953. 'use strict';
  24954. var utils = require('../utils/common');
  24955. /* Public constants ==========================================================*/
  24956. /* ===========================================================================*/
  24957. //var Z_FILTERED = 1;
  24958. //var Z_HUFFMAN_ONLY = 2;
  24959. //var Z_RLE = 3;
  24960. var Z_FIXED = 4;
  24961. //var Z_DEFAULT_STRATEGY = 0;
  24962. /* Possible values of the data_type field (though see inflate()) */
  24963. var Z_BINARY = 0;
  24964. var Z_TEXT = 1;
  24965. //var Z_ASCII = 1; // = Z_TEXT
  24966. var Z_UNKNOWN = 2;
  24967. /*============================================================================*/
  24968. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24969. // From zutil.h
  24970. var STORED_BLOCK = 0;
  24971. var STATIC_TREES = 1;
  24972. var DYN_TREES = 2;
  24973. /* The three kinds of block type */
  24974. var MIN_MATCH = 3;
  24975. var MAX_MATCH = 258;
  24976. /* The minimum and maximum match lengths */
  24977. // From deflate.h
  24978. /* ===========================================================================
  24979. * Internal compression state.
  24980. */
  24981. var LENGTH_CODES = 29;
  24982. /* number of length codes, not counting the special END_BLOCK code */
  24983. var LITERALS = 256;
  24984. /* number of literal bytes 0..255 */
  24985. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24986. /* number of Literal or Length codes, including the END_BLOCK code */
  24987. var D_CODES = 30;
  24988. /* number of distance codes */
  24989. var BL_CODES = 19;
  24990. /* number of codes used to transfer the bit lengths */
  24991. var HEAP_SIZE = 2*L_CODES + 1;
  24992. /* maximum heap size */
  24993. var MAX_BITS = 15;
  24994. /* All codes must not exceed MAX_BITS bits */
  24995. var Buf_size = 16;
  24996. /* size of bit buffer in bi_buf */
  24997. /* ===========================================================================
  24998. * Constants
  24999. */
  25000. var MAX_BL_BITS = 7;
  25001. /* Bit length codes must not exceed MAX_BL_BITS bits */
  25002. var END_BLOCK = 256;
  25003. /* end of block literal code */
  25004. var REP_3_6 = 16;
  25005. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  25006. var REPZ_3_10 = 17;
  25007. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  25008. var REPZ_11_138 = 18;
  25009. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  25010. var extra_lbits = /* extra bits for each length code */
  25011. [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];
  25012. var extra_dbits = /* extra bits for each distance code */
  25013. [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];
  25014. var extra_blbits = /* extra bits for each bit length code */
  25015. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  25016. var bl_order =
  25017. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  25018. /* The lengths of the bit length codes are sent in order of decreasing
  25019. * probability, to avoid transmitting the lengths for unused bit length codes.
  25020. */
  25021. /* ===========================================================================
  25022. * Local data. These are initialized only once.
  25023. */
  25024. // We pre-fill arrays with 0 to avoid uninitialized gaps
  25025. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  25026. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  25027. var static_ltree = new Array((L_CODES+2) * 2);
  25028. zero(static_ltree);
  25029. /* The static literal tree. Since the bit lengths are imposed, there is no
  25030. * need for the L_CODES extra codes used during heap construction. However
  25031. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  25032. * below).
  25033. */
  25034. var static_dtree = new Array(D_CODES * 2);
  25035. zero(static_dtree);
  25036. /* The static distance tree. (Actually a trivial tree since all codes use
  25037. * 5 bits.)
  25038. */
  25039. var _dist_code = new Array(DIST_CODE_LEN);
  25040. zero(_dist_code);
  25041. /* Distance codes. The first 256 values correspond to the distances
  25042. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  25043. * the 15 bit distances.
  25044. */
  25045. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  25046. zero(_length_code);
  25047. /* length code for each normalized match length (0 == MIN_MATCH) */
  25048. var base_length = new Array(LENGTH_CODES);
  25049. zero(base_length);
  25050. /* First normalized length for each code (0 = MIN_MATCH) */
  25051. var base_dist = new Array(D_CODES);
  25052. zero(base_dist);
  25053. /* First normalized distance for each code (0 = distance of 1) */
  25054. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  25055. this.static_tree = static_tree; /* static tree or NULL */
  25056. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  25057. this.extra_base = extra_base; /* base index for extra_bits */
  25058. this.elems = elems; /* max number of elements in the tree */
  25059. this.max_length = max_length; /* max bit length for the codes */
  25060. // show if `static_tree` has data or dummy - needed for monomorphic objects
  25061. this.has_stree = static_tree && static_tree.length;
  25062. };
  25063. var static_l_desc;
  25064. var static_d_desc;
  25065. var static_bl_desc;
  25066. var TreeDesc = function(dyn_tree, stat_desc) {
  25067. this.dyn_tree = dyn_tree; /* the dynamic tree */
  25068. this.max_code = 0; /* largest code with non zero frequency */
  25069. this.stat_desc = stat_desc; /* the corresponding static tree */
  25070. };
  25071. function d_code(dist) {
  25072. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  25073. }
  25074. /* ===========================================================================
  25075. * Output a short LSB first on the stream.
  25076. * IN assertion: there is enough room in pendingBuf.
  25077. */
  25078. function put_short (s, w) {
  25079. // put_byte(s, (uch)((w) & 0xff));
  25080. // put_byte(s, (uch)((ush)(w) >> 8));
  25081. s.pending_buf[s.pending++] = (w) & 0xff;
  25082. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  25083. }
  25084. /* ===========================================================================
  25085. * Send a value on a given number of bits.
  25086. * IN assertion: length <= 16 and value fits in length bits.
  25087. */
  25088. function send_bits(s, value, length) {
  25089. if (s.bi_valid > (Buf_size - length)) {
  25090. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  25091. put_short(s, s.bi_buf);
  25092. s.bi_buf = value >> (Buf_size - s.bi_valid);
  25093. s.bi_valid += length - Buf_size;
  25094. } else {
  25095. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  25096. s.bi_valid += length;
  25097. }
  25098. }
  25099. function send_code(s, c, tree) {
  25100. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  25101. }
  25102. /* ===========================================================================
  25103. * Reverse the first len bits of a code, using straightforward code (a faster
  25104. * method would use a table)
  25105. * IN assertion: 1 <= len <= 15
  25106. */
  25107. function bi_reverse(code, len) {
  25108. var res = 0;
  25109. do {
  25110. res |= code & 1;
  25111. code >>>= 1;
  25112. res <<= 1;
  25113. } while (--len > 0);
  25114. return res >>> 1;
  25115. }
  25116. /* ===========================================================================
  25117. * Flush the bit buffer, keeping at most 7 bits in it.
  25118. */
  25119. function bi_flush(s) {
  25120. if (s.bi_valid === 16) {
  25121. put_short(s, s.bi_buf);
  25122. s.bi_buf = 0;
  25123. s.bi_valid = 0;
  25124. } else if (s.bi_valid >= 8) {
  25125. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  25126. s.bi_buf >>= 8;
  25127. s.bi_valid -= 8;
  25128. }
  25129. }
  25130. /* ===========================================================================
  25131. * Compute the optimal bit lengths for a tree and update the total bit length
  25132. * for the current block.
  25133. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  25134. * above are the tree nodes sorted by increasing frequency.
  25135. * OUT assertions: the field len is set to the optimal bit length, the
  25136. * array bl_count contains the frequencies for each bit length.
  25137. * The length opt_len is updated; static_len is also updated if stree is
  25138. * not null.
  25139. */
  25140. function gen_bitlen(s, desc)
  25141. // deflate_state *s;
  25142. // tree_desc *desc; /* the tree descriptor */
  25143. {
  25144. var tree = desc.dyn_tree;
  25145. var max_code = desc.max_code;
  25146. var stree = desc.stat_desc.static_tree;
  25147. var has_stree = desc.stat_desc.has_stree;
  25148. var extra = desc.stat_desc.extra_bits;
  25149. var base = desc.stat_desc.extra_base;
  25150. var max_length = desc.stat_desc.max_length;
  25151. var h; /* heap index */
  25152. var n, m; /* iterate over the tree elements */
  25153. var bits; /* bit length */
  25154. var xbits; /* extra bits */
  25155. var f; /* frequency */
  25156. var overflow = 0; /* number of elements with bit length too large */
  25157. for (bits = 0; bits <= MAX_BITS; bits++) {
  25158. s.bl_count[bits] = 0;
  25159. }
  25160. /* In a first pass, compute the optimal bit lengths (which may
  25161. * overflow in the case of the bit length tree).
  25162. */
  25163. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  25164. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  25165. n = s.heap[h];
  25166. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  25167. if (bits > max_length) {
  25168. bits = max_length;
  25169. overflow++;
  25170. }
  25171. tree[n*2 + 1]/*.Len*/ = bits;
  25172. /* We overwrite tree[n].Dad which is no longer needed */
  25173. if (n > max_code) { continue; } /* not a leaf node */
  25174. s.bl_count[bits]++;
  25175. xbits = 0;
  25176. if (n >= base) {
  25177. xbits = extra[n-base];
  25178. }
  25179. f = tree[n * 2]/*.Freq*/;
  25180. s.opt_len += f * (bits + xbits);
  25181. if (has_stree) {
  25182. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  25183. }
  25184. }
  25185. if (overflow === 0) { return; }
  25186. // Trace((stderr,"\nbit length overflow\n"));
  25187. /* This happens for example on obj2 and pic of the Calgary corpus */
  25188. /* Find the first bit length which could increase: */
  25189. do {
  25190. bits = max_length-1;
  25191. while (s.bl_count[bits] === 0) { bits--; }
  25192. s.bl_count[bits]--; /* move one leaf down the tree */
  25193. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  25194. s.bl_count[max_length]--;
  25195. /* The brother of the overflow item also moves one step up,
  25196. * but this does not affect bl_count[max_length]
  25197. */
  25198. overflow -= 2;
  25199. } while (overflow > 0);
  25200. /* Now recompute all bit lengths, scanning in increasing frequency.
  25201. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  25202. * lengths instead of fixing only the wrong ones. This idea is taken
  25203. * from 'ar' written by Haruhiko Okumura.)
  25204. */
  25205. for (bits = max_length; bits !== 0; bits--) {
  25206. n = s.bl_count[bits];
  25207. while (n !== 0) {
  25208. m = s.heap[--h];
  25209. if (m > max_code) { continue; }
  25210. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  25211. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  25212. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  25213. tree[m*2 + 1]/*.Len*/ = bits;
  25214. }
  25215. n--;
  25216. }
  25217. }
  25218. }
  25219. /* ===========================================================================
  25220. * Generate the codes for a given tree and bit counts (which need not be
  25221. * optimal).
  25222. * IN assertion: the array bl_count contains the bit length statistics for
  25223. * the given tree and the field len is set for all tree elements.
  25224. * OUT assertion: the field code is set for all tree elements of non
  25225. * zero code length.
  25226. */
  25227. function gen_codes(tree, max_code, bl_count)
  25228. // ct_data *tree; /* the tree to decorate */
  25229. // int max_code; /* largest code with non zero frequency */
  25230. // ushf *bl_count; /* number of codes at each bit length */
  25231. {
  25232. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  25233. var code = 0; /* running code value */
  25234. var bits; /* bit index */
  25235. var n; /* code index */
  25236. /* The distribution counts are first used to generate the code values
  25237. * without bit reversal.
  25238. */
  25239. for (bits = 1; bits <= MAX_BITS; bits++) {
  25240. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  25241. }
  25242. /* Check that the bit counts in bl_count are consistent. The last code
  25243. * must be all ones.
  25244. */
  25245. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  25246. // "inconsistent bit counts");
  25247. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  25248. for (n = 0; n <= max_code; n++) {
  25249. var len = tree[n*2 + 1]/*.Len*/;
  25250. if (len === 0) { continue; }
  25251. /* Now reverse the bits */
  25252. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  25253. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  25254. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  25255. }
  25256. }
  25257. /* ===========================================================================
  25258. * Initialize the various 'constant' tables.
  25259. */
  25260. function tr_static_init() {
  25261. var n; /* iterates over tree elements */
  25262. var bits; /* bit counter */
  25263. var length; /* length value */
  25264. var code; /* code value */
  25265. var dist; /* distance index */
  25266. var bl_count = new Array(MAX_BITS+1);
  25267. /* number of codes at each bit length for an optimal tree */
  25268. // do check in _tr_init()
  25269. //if (static_init_done) return;
  25270. /* For some embedded targets, global variables are not initialized: */
  25271. /*#ifdef NO_INIT_GLOBAL_POINTERS
  25272. static_l_desc.static_tree = static_ltree;
  25273. static_l_desc.extra_bits = extra_lbits;
  25274. static_d_desc.static_tree = static_dtree;
  25275. static_d_desc.extra_bits = extra_dbits;
  25276. static_bl_desc.extra_bits = extra_blbits;
  25277. #endif*/
  25278. /* Initialize the mapping length (0..255) -> length code (0..28) */
  25279. length = 0;
  25280. for (code = 0; code < LENGTH_CODES-1; code++) {
  25281. base_length[code] = length;
  25282. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  25283. _length_code[length++] = code;
  25284. }
  25285. }
  25286. //Assert (length == 256, "tr_static_init: length != 256");
  25287. /* Note that the length 255 (match length 258) can be represented
  25288. * in two different ways: code 284 + 5 bits or code 285, so we
  25289. * overwrite length_code[255] to use the best encoding:
  25290. */
  25291. _length_code[length-1] = code;
  25292. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  25293. dist = 0;
  25294. for (code = 0 ; code < 16; code++) {
  25295. base_dist[code] = dist;
  25296. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  25297. _dist_code[dist++] = code;
  25298. }
  25299. }
  25300. //Assert (dist == 256, "tr_static_init: dist != 256");
  25301. dist >>= 7; /* from now on, all distances are divided by 128 */
  25302. for (; code < D_CODES; code++) {
  25303. base_dist[code] = dist << 7;
  25304. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  25305. _dist_code[256 + dist++] = code;
  25306. }
  25307. }
  25308. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  25309. /* Construct the codes of the static literal tree */
  25310. for (bits = 0; bits <= MAX_BITS; bits++) {
  25311. bl_count[bits] = 0;
  25312. }
  25313. n = 0;
  25314. while (n <= 143) {
  25315. static_ltree[n*2 + 1]/*.Len*/ = 8;
  25316. n++;
  25317. bl_count[8]++;
  25318. }
  25319. while (n <= 255) {
  25320. static_ltree[n*2 + 1]/*.Len*/ = 9;
  25321. n++;
  25322. bl_count[9]++;
  25323. }
  25324. while (n <= 279) {
  25325. static_ltree[n*2 + 1]/*.Len*/ = 7;
  25326. n++;
  25327. bl_count[7]++;
  25328. }
  25329. while (n <= 287) {
  25330. static_ltree[n*2 + 1]/*.Len*/ = 8;
  25331. n++;
  25332. bl_count[8]++;
  25333. }
  25334. /* Codes 286 and 287 do not exist, but we must include them in the
  25335. * tree construction to get a canonical Huffman tree (longest code
  25336. * all ones)
  25337. */
  25338. gen_codes(static_ltree, L_CODES+1, bl_count);
  25339. /* The static distance tree is trivial: */
  25340. for (n = 0; n < D_CODES; n++) {
  25341. static_dtree[n*2 + 1]/*.Len*/ = 5;
  25342. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  25343. }
  25344. // Now data ready and we can init static trees
  25345. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  25346. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  25347. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  25348. //static_init_done = true;
  25349. }
  25350. /* ===========================================================================
  25351. * Initialize a new block.
  25352. */
  25353. function init_block(s) {
  25354. var n; /* iterates over tree elements */
  25355. /* Initialize the trees. */
  25356. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  25357. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  25358. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  25359. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  25360. s.opt_len = s.static_len = 0;
  25361. s.last_lit = s.matches = 0;
  25362. }
  25363. /* ===========================================================================
  25364. * Flush the bit buffer and align the output on a byte boundary
  25365. */
  25366. function bi_windup(s)
  25367. {
  25368. if (s.bi_valid > 8) {
  25369. put_short(s, s.bi_buf);
  25370. } else if (s.bi_valid > 0) {
  25371. //put_byte(s, (Byte)s->bi_buf);
  25372. s.pending_buf[s.pending++] = s.bi_buf;
  25373. }
  25374. s.bi_buf = 0;
  25375. s.bi_valid = 0;
  25376. }
  25377. /* ===========================================================================
  25378. * Copy a stored block, storing first the length and its
  25379. * one's complement if requested.
  25380. */
  25381. function copy_block(s, buf, len, header)
  25382. //DeflateState *s;
  25383. //charf *buf; /* the input data */
  25384. //unsigned len; /* its length */
  25385. //int header; /* true if block header must be written */
  25386. {
  25387. bi_windup(s); /* align on byte boundary */
  25388. if (header) {
  25389. put_short(s, len);
  25390. put_short(s, ~len);
  25391. }
  25392. // while (len--) {
  25393. // put_byte(s, *buf++);
  25394. // }
  25395. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  25396. s.pending += len;
  25397. }
  25398. /* ===========================================================================
  25399. * Compares to subtrees, using the tree depth as tie breaker when
  25400. * the subtrees have equal frequency. This minimizes the worst case length.
  25401. */
  25402. function smaller(tree, n, m, depth) {
  25403. var _n2 = n*2;
  25404. var _m2 = m*2;
  25405. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  25406. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  25407. }
  25408. /* ===========================================================================
  25409. * Restore the heap property by moving down the tree starting at node k,
  25410. * exchanging a node with the smallest of its two sons if necessary, stopping
  25411. * when the heap property is re-established (each father smaller than its
  25412. * two sons).
  25413. */
  25414. function pqdownheap(s, tree, k)
  25415. // deflate_state *s;
  25416. // ct_data *tree; /* the tree to restore */
  25417. // int k; /* node to move down */
  25418. {
  25419. var v = s.heap[k];
  25420. var j = k << 1; /* left son of k */
  25421. while (j <= s.heap_len) {
  25422. /* Set j to the smallest of the two sons: */
  25423. if (j < s.heap_len &&
  25424. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  25425. j++;
  25426. }
  25427. /* Exit if v is smaller than both sons */
  25428. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  25429. /* Exchange v with the smallest son */
  25430. s.heap[k] = s.heap[j];
  25431. k = j;
  25432. /* And continue down the tree, setting j to the left son of k */
  25433. j <<= 1;
  25434. }
  25435. s.heap[k] = v;
  25436. }
  25437. // inlined manually
  25438. // var SMALLEST = 1;
  25439. /* ===========================================================================
  25440. * Send the block data compressed using the given Huffman trees
  25441. */
  25442. function compress_block(s, ltree, dtree)
  25443. // deflate_state *s;
  25444. // const ct_data *ltree; /* literal tree */
  25445. // const ct_data *dtree; /* distance tree */
  25446. {
  25447. var dist; /* distance of matched string */
  25448. var lc; /* match length or unmatched char (if dist == 0) */
  25449. var lx = 0; /* running index in l_buf */
  25450. var code; /* the code to send */
  25451. var extra; /* number of extra bits to send */
  25452. if (s.last_lit !== 0) {
  25453. do {
  25454. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  25455. lc = s.pending_buf[s.l_buf + lx];
  25456. lx++;
  25457. if (dist === 0) {
  25458. send_code(s, lc, ltree); /* send a literal byte */
  25459. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  25460. } else {
  25461. /* Here, lc is the match length - MIN_MATCH */
  25462. code = _length_code[lc];
  25463. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  25464. extra = extra_lbits[code];
  25465. if (extra !== 0) {
  25466. lc -= base_length[code];
  25467. send_bits(s, lc, extra); /* send the extra length bits */
  25468. }
  25469. dist--; /* dist is now the match distance - 1 */
  25470. code = d_code(dist);
  25471. //Assert (code < D_CODES, "bad d_code");
  25472. send_code(s, code, dtree); /* send the distance code */
  25473. extra = extra_dbits[code];
  25474. if (extra !== 0) {
  25475. dist -= base_dist[code];
  25476. send_bits(s, dist, extra); /* send the extra distance bits */
  25477. }
  25478. } /* literal or match pair ? */
  25479. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  25480. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  25481. // "pendingBuf overflow");
  25482. } while (lx < s.last_lit);
  25483. }
  25484. send_code(s, END_BLOCK, ltree);
  25485. }
  25486. /* ===========================================================================
  25487. * Construct one Huffman tree and assigns the code bit strings and lengths.
  25488. * Update the total bit length for the current block.
  25489. * IN assertion: the field freq is set for all tree elements.
  25490. * OUT assertions: the fields len and code are set to the optimal bit length
  25491. * and corresponding code. The length opt_len is updated; static_len is
  25492. * also updated if stree is not null. The field max_code is set.
  25493. */
  25494. function build_tree(s, desc)
  25495. // deflate_state *s;
  25496. // tree_desc *desc; /* the tree descriptor */
  25497. {
  25498. var tree = desc.dyn_tree;
  25499. var stree = desc.stat_desc.static_tree;
  25500. var has_stree = desc.stat_desc.has_stree;
  25501. var elems = desc.stat_desc.elems;
  25502. var n, m; /* iterate over heap elements */
  25503. var max_code = -1; /* largest code with non zero frequency */
  25504. var node; /* new node being created */
  25505. /* Construct the initial heap, with least frequent element in
  25506. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  25507. * heap[0] is not used.
  25508. */
  25509. s.heap_len = 0;
  25510. s.heap_max = HEAP_SIZE;
  25511. for (n = 0; n < elems; n++) {
  25512. if (tree[n * 2]/*.Freq*/ !== 0) {
  25513. s.heap[++s.heap_len] = max_code = n;
  25514. s.depth[n] = 0;
  25515. } else {
  25516. tree[n*2 + 1]/*.Len*/ = 0;
  25517. }
  25518. }
  25519. /* The pkzip format requires that at least one distance code exists,
  25520. * and that at least one bit should be sent even if there is only one
  25521. * possible code. So to avoid special checks later on we force at least
  25522. * two codes of non zero frequency.
  25523. */
  25524. while (s.heap_len < 2) {
  25525. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  25526. tree[node * 2]/*.Freq*/ = 1;
  25527. s.depth[node] = 0;
  25528. s.opt_len--;
  25529. if (has_stree) {
  25530. s.static_len -= stree[node*2 + 1]/*.Len*/;
  25531. }
  25532. /* node is 0 or 1 so it does not have extra bits */
  25533. }
  25534. desc.max_code = max_code;
  25535. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  25536. * establish sub-heaps of increasing lengths:
  25537. */
  25538. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  25539. /* Construct the Huffman tree by repeatedly combining the least two
  25540. * frequent nodes.
  25541. */
  25542. node = elems; /* next internal node of the tree */
  25543. do {
  25544. //pqremove(s, tree, n); /* n = node of least frequency */
  25545. /*** pqremove ***/
  25546. n = s.heap[1/*SMALLEST*/];
  25547. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  25548. pqdownheap(s, tree, 1/*SMALLEST*/);
  25549. /***/
  25550. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  25551. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  25552. s.heap[--s.heap_max] = m;
  25553. /* Create a new node father of n and m */
  25554. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  25555. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  25556. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  25557. /* and insert the new node in the heap */
  25558. s.heap[1/*SMALLEST*/] = node++;
  25559. pqdownheap(s, tree, 1/*SMALLEST*/);
  25560. } while (s.heap_len >= 2);
  25561. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  25562. /* At this point, the fields freq and dad are set. We can now
  25563. * generate the bit lengths.
  25564. */
  25565. gen_bitlen(s, desc);
  25566. /* The field len is now set, we can generate the bit codes */
  25567. gen_codes(tree, max_code, s.bl_count);
  25568. }
  25569. /* ===========================================================================
  25570. * Scan a literal or distance tree to determine the frequencies of the codes
  25571. * in the bit length tree.
  25572. */
  25573. function scan_tree(s, tree, max_code)
  25574. // deflate_state *s;
  25575. // ct_data *tree; /* the tree to be scanned */
  25576. // int max_code; /* and its largest code of non zero frequency */
  25577. {
  25578. var n; /* iterates over all tree elements */
  25579. var prevlen = -1; /* last emitted length */
  25580. var curlen; /* length of current code */
  25581. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25582. var count = 0; /* repeat count of the current code */
  25583. var max_count = 7; /* max repeat count */
  25584. var min_count = 4; /* min repeat count */
  25585. if (nextlen === 0) {
  25586. max_count = 138;
  25587. min_count = 3;
  25588. }
  25589. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  25590. for (n = 0; n <= max_code; n++) {
  25591. curlen = nextlen;
  25592. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25593. if (++count < max_count && curlen === nextlen) {
  25594. continue;
  25595. } else if (count < min_count) {
  25596. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  25597. } else if (curlen !== 0) {
  25598. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  25599. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  25600. } else if (count <= 10) {
  25601. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  25602. } else {
  25603. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  25604. }
  25605. count = 0;
  25606. prevlen = curlen;
  25607. if (nextlen === 0) {
  25608. max_count = 138;
  25609. min_count = 3;
  25610. } else if (curlen === nextlen) {
  25611. max_count = 6;
  25612. min_count = 3;
  25613. } else {
  25614. max_count = 7;
  25615. min_count = 4;
  25616. }
  25617. }
  25618. }
  25619. /* ===========================================================================
  25620. * Send a literal or distance tree in compressed form, using the codes in
  25621. * bl_tree.
  25622. */
  25623. function send_tree(s, tree, max_code)
  25624. // deflate_state *s;
  25625. // ct_data *tree; /* the tree to be scanned */
  25626. // int max_code; /* and its largest code of non zero frequency */
  25627. {
  25628. var n; /* iterates over all tree elements */
  25629. var prevlen = -1; /* last emitted length */
  25630. var curlen; /* length of current code */
  25631. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25632. var count = 0; /* repeat count of the current code */
  25633. var max_count = 7; /* max repeat count */
  25634. var min_count = 4; /* min repeat count */
  25635. /* tree[max_code+1].Len = -1; */ /* guard already set */
  25636. if (nextlen === 0) {
  25637. max_count = 138;
  25638. min_count = 3;
  25639. }
  25640. for (n = 0; n <= max_code; n++) {
  25641. curlen = nextlen;
  25642. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25643. if (++count < max_count && curlen === nextlen) {
  25644. continue;
  25645. } else if (count < min_count) {
  25646. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  25647. } else if (curlen !== 0) {
  25648. if (curlen !== prevlen) {
  25649. send_code(s, curlen, s.bl_tree);
  25650. count--;
  25651. }
  25652. //Assert(count >= 3 && count <= 6, " 3_6?");
  25653. send_code(s, REP_3_6, s.bl_tree);
  25654. send_bits(s, count-3, 2);
  25655. } else if (count <= 10) {
  25656. send_code(s, REPZ_3_10, s.bl_tree);
  25657. send_bits(s, count-3, 3);
  25658. } else {
  25659. send_code(s, REPZ_11_138, s.bl_tree);
  25660. send_bits(s, count-11, 7);
  25661. }
  25662. count = 0;
  25663. prevlen = curlen;
  25664. if (nextlen === 0) {
  25665. max_count = 138;
  25666. min_count = 3;
  25667. } else if (curlen === nextlen) {
  25668. max_count = 6;
  25669. min_count = 3;
  25670. } else {
  25671. max_count = 7;
  25672. min_count = 4;
  25673. }
  25674. }
  25675. }
  25676. /* ===========================================================================
  25677. * Construct the Huffman tree for the bit lengths and return the index in
  25678. * bl_order of the last bit length code to send.
  25679. */
  25680. function build_bl_tree(s) {
  25681. var max_blindex; /* index of last bit length code of non zero freq */
  25682. /* Determine the bit length frequencies for literal and distance trees */
  25683. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  25684. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  25685. /* Build the bit length tree: */
  25686. build_tree(s, s.bl_desc);
  25687. /* opt_len now includes the length of the tree representations, except
  25688. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  25689. */
  25690. /* Determine the number of bit length codes to send. The pkzip format
  25691. * requires that at least 4 bit length codes be sent. (appnote.txt says
  25692. * 3 but the actual value used is 4.)
  25693. */
  25694. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  25695. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  25696. break;
  25697. }
  25698. }
  25699. /* Update opt_len to include the bit length tree and counts */
  25700. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  25701. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  25702. // s->opt_len, s->static_len));
  25703. return max_blindex;
  25704. }
  25705. /* ===========================================================================
  25706. * Send the header for a block using dynamic Huffman trees: the counts, the
  25707. * lengths of the bit length codes, the literal tree and the distance tree.
  25708. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  25709. */
  25710. function send_all_trees(s, lcodes, dcodes, blcodes)
  25711. // deflate_state *s;
  25712. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  25713. {
  25714. var rank; /* index in bl_order */
  25715. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  25716. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  25717. // "too many codes");
  25718. //Tracev((stderr, "\nbl counts: "));
  25719. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  25720. send_bits(s, dcodes-1, 5);
  25721. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  25722. for (rank = 0; rank < blcodes; rank++) {
  25723. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  25724. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  25725. }
  25726. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  25727. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  25728. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  25729. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  25730. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  25731. }
  25732. /* ===========================================================================
  25733. * Check if the data type is TEXT or BINARY, using the following algorithm:
  25734. * - TEXT if the two conditions below are satisfied:
  25735. * a) There are no non-portable control characters belonging to the
  25736. * "black list" (0..6, 14..25, 28..31).
  25737. * b) There is at least one printable character belonging to the
  25738. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  25739. * - BINARY otherwise.
  25740. * - The following partially-portable control characters form a
  25741. * "gray list" that is ignored in this detection algorithm:
  25742. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  25743. * IN assertion: the fields Freq of dyn_ltree are set.
  25744. */
  25745. function detect_data_type(s) {
  25746. /* black_mask is the bit mask of black-listed bytes
  25747. * set bits 0..6, 14..25, and 28..31
  25748. * 0xf3ffc07f = binary 11110011111111111100000001111111
  25749. */
  25750. var black_mask = 0xf3ffc07f;
  25751. var n;
  25752. /* Check for non-textual ("black-listed") bytes. */
  25753. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  25754. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  25755. return Z_BINARY;
  25756. }
  25757. }
  25758. /* Check for textual ("white-listed") bytes. */
  25759. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  25760. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  25761. return Z_TEXT;
  25762. }
  25763. for (n = 32; n < LITERALS; n++) {
  25764. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  25765. return Z_TEXT;
  25766. }
  25767. }
  25768. /* There are no "black-listed" or "white-listed" bytes:
  25769. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  25770. */
  25771. return Z_BINARY;
  25772. }
  25773. var static_init_done = false;
  25774. /* ===========================================================================
  25775. * Initialize the tree data structures for a new zlib stream.
  25776. */
  25777. function _tr_init(s)
  25778. {
  25779. if (!static_init_done) {
  25780. tr_static_init();
  25781. static_init_done = true;
  25782. }
  25783. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  25784. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  25785. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  25786. s.bi_buf = 0;
  25787. s.bi_valid = 0;
  25788. /* Initialize the first block of the first file: */
  25789. init_block(s);
  25790. }
  25791. /* ===========================================================================
  25792. * Send a stored block
  25793. */
  25794. function _tr_stored_block(s, buf, stored_len, last)
  25795. //DeflateState *s;
  25796. //charf *buf; /* input block */
  25797. //ulg stored_len; /* length of input block */
  25798. //int last; /* one if this is the last block for a file */
  25799. {
  25800. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  25801. copy_block(s, buf, stored_len, true); /* with header */
  25802. }
  25803. /* ===========================================================================
  25804. * Send one empty static block to give enough lookahead for inflate.
  25805. * This takes 10 bits, of which 7 may remain in the bit buffer.
  25806. */
  25807. function _tr_align(s) {
  25808. send_bits(s, STATIC_TREES<<1, 3);
  25809. send_code(s, END_BLOCK, static_ltree);
  25810. bi_flush(s);
  25811. }
  25812. /* ===========================================================================
  25813. * Determine the best encoding for the current block: dynamic trees, static
  25814. * trees or store, and output the encoded block to the zip file.
  25815. */
  25816. function _tr_flush_block(s, buf, stored_len, last)
  25817. //DeflateState *s;
  25818. //charf *buf; /* input block, or NULL if too old */
  25819. //ulg stored_len; /* length of input block */
  25820. //int last; /* one if this is the last block for a file */
  25821. {
  25822. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  25823. var max_blindex = 0; /* index of last bit length code of non zero freq */
  25824. /* Build the Huffman trees unless a stored block is forced */
  25825. if (s.level > 0) {
  25826. /* Check if the file is binary or text */
  25827. if (s.strm.data_type === Z_UNKNOWN) {
  25828. s.strm.data_type = detect_data_type(s);
  25829. }
  25830. /* Construct the literal and distance trees */
  25831. build_tree(s, s.l_desc);
  25832. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  25833. // s->static_len));
  25834. build_tree(s, s.d_desc);
  25835. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  25836. // s->static_len));
  25837. /* At this point, opt_len and static_len are the total bit lengths of
  25838. * the compressed block data, excluding the tree representations.
  25839. */
  25840. /* Build the bit length tree for the above two trees, and get the index
  25841. * in bl_order of the last bit length code to send.
  25842. */
  25843. max_blindex = build_bl_tree(s);
  25844. /* Determine the best encoding. Compute the block lengths in bytes. */
  25845. opt_lenb = (s.opt_len+3+7) >>> 3;
  25846. static_lenb = (s.static_len+3+7) >>> 3;
  25847. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  25848. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  25849. // s->last_lit));
  25850. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  25851. } else {
  25852. // Assert(buf != (char*)0, "lost buf");
  25853. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  25854. }
  25855. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  25856. /* 4: two words for the lengths */
  25857. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  25858. * Otherwise we can't have processed more than WSIZE input bytes since
  25859. * the last block flush, because compression would have been
  25860. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  25861. * transform a block into a stored block.
  25862. */
  25863. _tr_stored_block(s, buf, stored_len, last);
  25864. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  25865. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  25866. compress_block(s, static_ltree, static_dtree);
  25867. } else {
  25868. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  25869. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  25870. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  25871. }
  25872. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  25873. /* The above check is made mod 2^32, for files larger than 512 MB
  25874. * and uLong implemented on 32 bits.
  25875. */
  25876. init_block(s);
  25877. if (last) {
  25878. bi_windup(s);
  25879. }
  25880. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  25881. // s->compressed_len-7*last));
  25882. }
  25883. /* ===========================================================================
  25884. * Save the match info and tally the frequency counts. Return true if
  25885. * the current block must be flushed.
  25886. */
  25887. function _tr_tally(s, dist, lc)
  25888. // deflate_state *s;
  25889. // unsigned dist; /* distance of matched string */
  25890. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  25891. {
  25892. //var out_length, in_length, dcode;
  25893. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  25894. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  25895. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  25896. s.last_lit++;
  25897. if (dist === 0) {
  25898. /* lc is the unmatched char */
  25899. s.dyn_ltree[lc*2]/*.Freq*/++;
  25900. } else {
  25901. s.matches++;
  25902. /* Here, lc is the match length - MIN_MATCH */
  25903. dist--; /* dist = match distance - 1 */
  25904. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  25905. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  25906. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  25907. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  25908. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  25909. }
  25910. // (!) This block is disabled in zlib defailts,
  25911. // don't enable it for binary compatibility
  25912. //#ifdef TRUNCATE_BLOCK
  25913. // /* Try to guess if it is profitable to stop the current block here */
  25914. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  25915. // /* Compute an upper bound for the compressed length */
  25916. // out_length = s.last_lit*8;
  25917. // in_length = s.strstart - s.block_start;
  25918. //
  25919. // for (dcode = 0; dcode < D_CODES; dcode++) {
  25920. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  25921. // }
  25922. // out_length >>>= 3;
  25923. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  25924. // // s->last_lit, in_length, out_length,
  25925. // // 100L - out_length*100L/in_length));
  25926. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  25927. // return true;
  25928. // }
  25929. // }
  25930. //#endif
  25931. return (s.last_lit === s.lit_bufsize-1);
  25932. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25933. * on 16 bit machines and because stored blocks are restricted to
  25934. * 64K-1 bytes.
  25935. */
  25936. }
  25937. exports._tr_init = _tr_init;
  25938. exports._tr_stored_block = _tr_stored_block;
  25939. exports._tr_flush_block = _tr_flush_block;
  25940. exports._tr_tally = _tr_tally;
  25941. exports._tr_align = _tr_align;
  25942. },{"../utils/common":80}],92:[function(require,module,exports){
  25943. 'use strict';
  25944. function ZStream() {
  25945. /* next input byte */
  25946. this.input = null; // JS specific, because we have no pointers
  25947. this.next_in = 0;
  25948. /* number of bytes available at input */
  25949. this.avail_in = 0;
  25950. /* total number of input bytes read so far */
  25951. this.total_in = 0;
  25952. /* next output byte should be put there */
  25953. this.output = null; // JS specific, because we have no pointers
  25954. this.next_out = 0;
  25955. /* remaining free space at output */
  25956. this.avail_out = 0;
  25957. /* total number of bytes output so far */
  25958. this.total_out = 0;
  25959. /* last error message, NULL if no error */
  25960. this.msg = ''/*Z_NULL*/;
  25961. /* not visible by applications */
  25962. this.state = null;
  25963. /* best guess about the data type: binary or text */
  25964. this.data_type = 2/*Z_UNKNOWN*/;
  25965. /* adler32 value of the uncompressed data */
  25966. this.adler = 0;
  25967. }
  25968. module.exports = ZStream;
  25969. },{}],93:[function(require,module,exports){
  25970. module.exports = require('./lib/retry');
  25971. },{"./lib/retry":94}],94:[function(require,module,exports){
  25972. var RetryOperation = require('./retry_operation');
  25973. exports.operation = function(options) {
  25974. var timeouts = exports.timeouts(options);
  25975. return new RetryOperation(timeouts);
  25976. };
  25977. exports.timeouts = function(options) {
  25978. if (options instanceof Array) {
  25979. return [].concat(options);
  25980. }
  25981. var opts = {
  25982. retries: 10,
  25983. factor: 2,
  25984. minTimeout: 1 * 1000,
  25985. maxTimeout: Infinity,
  25986. randomize: false
  25987. };
  25988. for (var key in options) {
  25989. opts[key] = options[key];
  25990. }
  25991. if (opts.minTimeout > opts.maxTimeout) {
  25992. throw new Error('minTimeout is greater than maxTimeout');
  25993. }
  25994. var timeouts = [];
  25995. for (var i = 0; i < opts.retries; i++) {
  25996. timeouts.push(this._createTimeout(i, opts));
  25997. }
  25998. // sort the array numerically ascending
  25999. timeouts.sort(function(a,b) {
  26000. return a - b;
  26001. });
  26002. return timeouts;
  26003. };
  26004. exports._createTimeout = function(attempt, opts) {
  26005. var random = (opts.randomize)
  26006. ? (Math.random() + 1)
  26007. : 1;
  26008. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  26009. timeout = Math.min(timeout, opts.maxTimeout);
  26010. return timeout;
  26011. };
  26012. },{"./retry_operation":95}],95:[function(require,module,exports){
  26013. function RetryOperation(timeouts) {
  26014. this._timeouts = timeouts;
  26015. this._fn = null;
  26016. this._errors = [];
  26017. this._attempts = 1;
  26018. this._operationTimeout = null;
  26019. this._operationTimeoutCb = null;
  26020. this._timeout = null;
  26021. }
  26022. module.exports = RetryOperation;
  26023. RetryOperation.prototype.retry = function(err) {
  26024. if (this._timeout) {
  26025. clearTimeout(this._timeout);
  26026. }
  26027. if (!err) {
  26028. return false;
  26029. }
  26030. this._errors.push(err);
  26031. var timeout = this._timeouts.shift();
  26032. if (timeout === undefined) {
  26033. return false;
  26034. }
  26035. this._attempts++;
  26036. var self = this;
  26037. setTimeout(function() {
  26038. self._fn(self._attempts);
  26039. if (self._operationTimeoutCb) {
  26040. self._timeout = setTimeout(function() {
  26041. self._operationTimeoutCb(self._attempts);
  26042. }, self._operationTimeout);
  26043. }
  26044. }, timeout);
  26045. return true;
  26046. };
  26047. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  26048. this._fn = fn;
  26049. if (timeoutOps) {
  26050. if (timeoutOps.timeout) {
  26051. this._operationTimeout = timeoutOps.timeout;
  26052. }
  26053. if (timeoutOps.cb) {
  26054. this._operationTimeoutCb = timeoutOps.cb;
  26055. }
  26056. }
  26057. this._fn(this._attempts);
  26058. var self = this;
  26059. if (this._operationTimeoutCb) {
  26060. this._timeout = setTimeout(function() {
  26061. self._operationTimeoutCb();
  26062. }, self._operationTimeout);
  26063. }
  26064. };
  26065. RetryOperation.prototype.try = function(fn) {
  26066. console.log('Using RetryOperation.try() is deprecated');
  26067. this.attempt(fn);
  26068. };
  26069. RetryOperation.prototype.start = function(fn) {
  26070. console.log('Using RetryOperation.start() is deprecated');
  26071. this.attempt(fn);
  26072. };
  26073. RetryOperation.prototype.start = RetryOperation.prototype.try;
  26074. RetryOperation.prototype.errors = function() {
  26075. return this._errors;
  26076. };
  26077. RetryOperation.prototype.attempts = function() {
  26078. return this._attempts;
  26079. };
  26080. RetryOperation.prototype.mainError = function() {
  26081. if (this._errors.length === 0) {
  26082. return null;
  26083. }
  26084. var counts = {};
  26085. var mainError = null;
  26086. var mainErrorCount = 0;
  26087. for (var i = 0; i < this._errors.length; i++) {
  26088. var error = this._errors[i];
  26089. var message = error.message;
  26090. var count = (counts[message] || 0) + 1;
  26091. counts[message] = count;
  26092. if (count >= mainErrorCount) {
  26093. mainError = error;
  26094. mainErrorCount = count;
  26095. }
  26096. }
  26097. return mainError;
  26098. };
  26099. },{}],96:[function(require,module,exports){
  26100. module.exports = function arrayEquals(array) {
  26101. // if the other array is a falsy value, return
  26102. if (!array)
  26103. return false;
  26104. // compare lengths - can save a lot of time
  26105. if (this.length != array.length)
  26106. return false;
  26107. for (var i = 0, l = this.length; i < l; i++) {
  26108. // Check if we have nested arrays
  26109. if (this[i] instanceof Array && array[i] instanceof Array) {
  26110. // recurse into the nested arrays
  26111. if (!arrayEquals.apply(this[i], [array[i]]))
  26112. return false;
  26113. } else if (this[i] != array[i]) {
  26114. // Warning - two different object instances will never be equal:
  26115. // {x:20} != {x:20}
  26116. return false;
  26117. }
  26118. }
  26119. return true;
  26120. }
  26121. },{}],97:[function(require,module,exports){
  26122. exports.Interop = require('./interop');
  26123. },{"./interop":98}],98:[function(require,module,exports){
  26124. "use strict";
  26125. var transform = require('./transform');
  26126. var arrayEquals = require('./array-equals');
  26127. function Interop() {
  26128. /**
  26129. * This map holds the most recent Unified Plan offer/answer SDP that was
  26130. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  26131. * the SDP string as values.
  26132. *
  26133. * @type {{}}
  26134. */
  26135. this.cache = {};
  26136. }
  26137. module.exports = Interop;
  26138. /**
  26139. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  26140. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  26141. * application.
  26142. *
  26143. * @param desc
  26144. * @returns {*}
  26145. */
  26146. Interop.prototype.toPlanB = function(desc) {
  26147. //#region Preliminary input validation.
  26148. if (typeof desc !== 'object' || desc === null ||
  26149. typeof desc.sdp !== 'string') {
  26150. console.warn('An empty description was passed as an argument.');
  26151. return desc;
  26152. }
  26153. // Objectify the SDP for easier manipulation.
  26154. var session = transform.parse(desc.sdp);
  26155. // If the SDP contains no media, there's nothing to transform.
  26156. if (typeof session.media === 'undefined' ||
  26157. !Array.isArray(session.media) || session.media.length === 0) {
  26158. console.warn('The description has no media.');
  26159. return desc;
  26160. }
  26161. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  26162. // SDP has a video, an audio and a data "channel" at most.
  26163. if (session.media.length <= 3 && session.media.every(function(m) {
  26164. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  26165. })) {
  26166. console.warn('This description does not look like Unified Plan.');
  26167. return desc;
  26168. }
  26169. //#endregion
  26170. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  26171. // -> Unified Plan transformation.
  26172. this.cache[desc.type] = desc.sdp;
  26173. //#region Convert from Unified Plan to Plan B.
  26174. // We rebuild the session.media array.
  26175. var media = session.media;
  26176. session.media = [];
  26177. // Associative array that maps channel types to channel objects for fast
  26178. // access to channel objects by their type, e.g. type2bl['audio']->channel
  26179. // obj.
  26180. var type2bl = {};
  26181. // Used to build the group:BUNDLE value after the channels construction
  26182. // loop.
  26183. var types = [];
  26184. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  26185. media.forEach(function(unifiedLine) {
  26186. // rtcp-mux is required in the Plan B SDP.
  26187. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  26188. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  26189. unifiedLine.direction !== 'inactive') {
  26190. throw new Error('Cannot convert to Plan B because m-lines ' +
  26191. 'without the rtcp-mux attribute were found.');
  26192. }
  26193. if (unifiedLine.type === 'application') {
  26194. session.media.push(unifiedLine);
  26195. types.push(unifiedLine.mid);
  26196. return;
  26197. }
  26198. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  26199. // as the channel basis.
  26200. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  26201. type2bl[unifiedLine.type] = unifiedLine;
  26202. }
  26203. // Add sources to the channel and handle a=msid.
  26204. if (typeof unifiedLine.sources === 'object') {
  26205. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  26206. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  26207. type2bl[unifiedLine.type].sources = {};
  26208. // Assign the sources to the channel.
  26209. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  26210. if (typeof unifiedLine.msid !== 'undefined') {
  26211. // In Plan B the msid is an SSRC attribute. Also, we don't
  26212. // care about the obsolete label and mslabel attributes.
  26213. //
  26214. // Note that it is not guaranteed that the unifiedLine will have
  26215. // an msid. recvonly channels in particular don't have one.
  26216. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  26217. }
  26218. // NOTE ssrcs in ssrc groups will share msids, as
  26219. // draft-uberti-rtcweb-plan-00 mandates.
  26220. });
  26221. }
  26222. // Add ssrc groups to the channel.
  26223. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  26224. Array.isArray(unifiedLine.ssrcGroups)) {
  26225. // Create the ssrcGroups array, if it's not defined.
  26226. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  26227. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  26228. type2bl[unifiedLine.type].ssrcGroups = [];
  26229. }
  26230. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  26231. }
  26232. if (type2bl[unifiedLine.type] === unifiedLine) {
  26233. // Copy ICE related stuff from the principal media line.
  26234. unifiedLine.candidates = media[0].candidates;
  26235. unifiedLine.iceUfrag = media[0].iceUfrag;
  26236. unifiedLine.icePwd = media[0].icePwd;
  26237. unifiedLine.fingerprint = media[0].fingerprint;
  26238. // Plan B mids are in ['audio', 'video', 'data']
  26239. unifiedLine.mid = unifiedLine.type;
  26240. // Plan B doesn't support/need the bundle-only attribute.
  26241. delete unifiedLine.bundleOnly;
  26242. // In Plan B the msid is an SSRC attribute.
  26243. delete unifiedLine.msid;
  26244. // Used to build the group:BUNDLE value after this loop.
  26245. types.push(unifiedLine.type);
  26246. // Add the channel to the new media array.
  26247. session.media.push(unifiedLine);
  26248. }
  26249. });
  26250. // We regenerate the BUNDLE group with the new mids.
  26251. session.groups.some(function(group) {
  26252. if (group.type === 'BUNDLE') {
  26253. group.mids = types.join(' ');
  26254. return true;
  26255. }
  26256. });
  26257. // msid semantic
  26258. session.msidSemantic = {
  26259. semantic: 'WMS',
  26260. token: '*'
  26261. };
  26262. var resStr = transform.write(session);
  26263. return new RTCSessionDescription({
  26264. type: desc.type,
  26265. sdp: resStr
  26266. });
  26267. //#endregion
  26268. };
  26269. /**
  26270. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  26271. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  26272. * to FF.
  26273. *
  26274. * @param desc
  26275. * @returns {*}
  26276. */
  26277. Interop.prototype.toUnifiedPlan = function(desc) {
  26278. //#region Preliminary input validation.
  26279. if (typeof desc !== 'object' || desc === null ||
  26280. typeof desc.sdp !== 'string') {
  26281. console.warn('An empty description was passed as an argument.');
  26282. return desc;
  26283. }
  26284. var session = transform.parse(desc.sdp);
  26285. // If the SDP contains no media, there's nothing to transform.
  26286. if (typeof session.media === 'undefined' ||
  26287. !Array.isArray(session.media) || session.media.length === 0) {
  26288. console.warn('The description has no media.');
  26289. return desc;
  26290. }
  26291. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  26292. // a video, an audio and a data "channel" at most.
  26293. if (session.media.length > 3 || !session.media.every(function(m) {
  26294. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  26295. })) {
  26296. console.warn('This description does not look like Plan B.');
  26297. return desc;
  26298. }
  26299. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  26300. var mids = [];
  26301. session.media.forEach(function(m) {
  26302. mids.push(m.mid);
  26303. });
  26304. var hasBundle = false;
  26305. if (typeof session.groups !== 'undefined' &&
  26306. Array.isArray(session.groups)) {
  26307. hasBundle = session.groups.every(function(g) {
  26308. return g.type !== 'BUNDLE' ||
  26309. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  26310. });
  26311. }
  26312. if (!hasBundle) {
  26313. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  26314. " are not bundled were found.");
  26315. }
  26316. //#endregion
  26317. //#region Convert from Plan B to Unified Plan.
  26318. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  26319. // rebuild an equivalent Unified Plan offer/answer.
  26320. //
  26321. // For example, if this is a local answer (in Unified Plan style) that we
  26322. // convert to Plan B prior to handing it over to the application (the
  26323. // PeerConnection wrapper called us, for instance, after a successful
  26324. // createAnswer), we want to remember the m-line at which we've seen the
  26325. // (local) SSRC. That's because when the application wants to do call the
  26326. // SLD method, forcing us to do the inverse transformation (from Plan B to
  26327. // Unified Plan), we need to know to which m-line to assign the (local)
  26328. // SSRC. We also need to know all the other m-lines that the original
  26329. // answer had and include them in the transformed answer as well.
  26330. //
  26331. // Another example is if this is a remote offer that we convert to Plan B
  26332. // prior to giving it to the application, we want to remember the mid at
  26333. // which we've seen the (remote) SSRC.
  26334. //
  26335. // In the iteration that follows, we use the cached Unified Plan (if it
  26336. // exists) to assign mids to ssrcs.
  26337. var cached;
  26338. if (typeof this.cache[desc.type] !== 'undefined') {
  26339. cached = transform.parse(this.cache[desc.type]);
  26340. }
  26341. // A helper map that sends mids to m-line objects. We use it later to
  26342. // rebuild the Unified Plan style session.media array.
  26343. var mid2ul = {};
  26344. session.media.forEach(function(bLine) {
  26345. if ((typeof bLine.rtcpMux !== 'string' ||
  26346. bLine.rtcpMux !== 'rtcp-mux') &&
  26347. bLine.direction !== 'inactive') {
  26348. throw new Error("Cannot convert to Unified Plan because m-lines " +
  26349. "without the rtcp-mux attribute were found.");
  26350. }
  26351. if (bLine.type === 'application') {
  26352. mid2ul[bLine.mid] = bLine;
  26353. return;
  26354. }
  26355. // With rtcp-mux and bundle all the channels should have the same ICE
  26356. // stuff.
  26357. var sources = bLine.sources;
  26358. var ssrcGroups = bLine.ssrcGroups;
  26359. var candidates = bLine.candidates;
  26360. var iceUfrag = bLine.iceUfrag;
  26361. var icePwd = bLine.icePwd;
  26362. var fingerprint = bLine.fingerprint;
  26363. var port = bLine.port;
  26364. // We'll use the "bLine" object as a prototype for each new "mLine"
  26365. // that we create, but first we need to clean it up a bit.
  26366. delete bLine.sources;
  26367. delete bLine.ssrcGroups;
  26368. delete bLine.candidates;
  26369. delete bLine.iceUfrag;
  26370. delete bLine.icePwd;
  26371. delete bLine.fingerprint;
  26372. delete bLine.port;
  26373. delete bLine.mid;
  26374. // inverted ssrc group map
  26375. var ssrc2group = {};
  26376. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  26377. ssrcGroups.forEach(function (ssrcGroup) {
  26378. // TODO(gp) find out how to receive simulcast with FF. For the
  26379. // time being, hide it.
  26380. if (ssrcGroup.semantics === 'SIM') {
  26381. return;
  26382. }
  26383. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  26384. Array.isArray(ssrcGroup.ssrcs)) {
  26385. ssrcGroup.ssrcs.forEach(function (ssrc) {
  26386. if (typeof ssrc2group[ssrc] === 'undefined') {
  26387. ssrc2group[ssrc] = [];
  26388. }
  26389. ssrc2group[ssrc].push(ssrcGroup);
  26390. });
  26391. }
  26392. });
  26393. }
  26394. // ssrc to m-line index.
  26395. var ssrc2ml = {};
  26396. if (typeof sources === 'object') {
  26397. // Explode the Plan B channel sources with one m-line per source.
  26398. Object.keys(sources).forEach(function(ssrc) {
  26399. // The (unified) m-line for this SSRC. We either create it from
  26400. // scratch or, if it's a grouped SSRC, we re-use a related
  26401. // mline. In other words, if the source is grouped with another
  26402. // source, put the two together in the same m-line.
  26403. var unifiedLine;
  26404. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  26405. Array.isArray(ssrc2group[ssrc])) {
  26406. ssrc2group[ssrc].some(function (ssrcGroup) {
  26407. // ssrcGroup.ssrcs *is* an Array, no need to check
  26408. // again here.
  26409. return ssrcGroup.ssrcs.some(function (related) {
  26410. if (typeof ssrc2ml[related] === 'object') {
  26411. unifiedLine = ssrc2ml[related];
  26412. return true;
  26413. }
  26414. });
  26415. });
  26416. }
  26417. if (typeof unifiedLine === 'object') {
  26418. // the m-line already exists. Just add the source.
  26419. unifiedLine.sources[ssrc] = sources[ssrc];
  26420. delete sources[ssrc].msid;
  26421. } else {
  26422. // Use the "bLine" as a prototype for the "unifiedLine".
  26423. unifiedLine = Object.create(bLine);
  26424. ssrc2ml[ssrc] = unifiedLine;
  26425. if (typeof sources[ssrc].msid !== 'undefined') {
  26426. // Assign the msid of the source to the m-line. Note
  26427. // that it is not guaranteed that the source will have
  26428. // msid. In particular "recvonly" sources don't have an
  26429. // msid. Note that "recvonly" is a term only defined
  26430. // for m-lines.
  26431. unifiedLine.msid = sources[ssrc].msid;
  26432. delete sources[ssrc].msid;
  26433. }
  26434. // We assign one SSRC per media line.
  26435. unifiedLine.sources = {};
  26436. unifiedLine.sources[ssrc] = sources[ssrc];
  26437. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  26438. // Use the cached Unified Plan SDP (if it exists) to assign
  26439. // SSRCs to mids.
  26440. if (typeof cached !== 'undefined' &&
  26441. typeof cached.media !== 'undefined' &&
  26442. Array.isArray(cached.media)) {
  26443. cached.media.forEach(function (m) {
  26444. if (typeof m.sources === 'object') {
  26445. Object.keys(m.sources).forEach(function (s) {
  26446. if (s === ssrc) {
  26447. unifiedLine.mid = m.mid;
  26448. }
  26449. });
  26450. }
  26451. });
  26452. }
  26453. if (typeof unifiedLine.mid === 'undefined') {
  26454. // If this is an SSRC that we see for the first time
  26455. // assign it a new mid. This is typically the case when
  26456. // this method is called to transform a remote
  26457. // description for the first time or when there is a
  26458. // new SSRC in the remote description because a new
  26459. // peer has joined the conference. Local SSRCs should
  26460. // have already been added to the map in the toPlanB
  26461. // method.
  26462. //
  26463. // Because FF generates answers in Unified Plan style,
  26464. // we MUST already have a cached answer with all the
  26465. // local SSRCs mapped to some m-line/mid.
  26466. if (desc.type === 'answer') {
  26467. throw new Error("An unmapped SSRC was found.");
  26468. }
  26469. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  26470. }
  26471. // Include the candidates in the 1st media line.
  26472. unifiedLine.candidates = candidates;
  26473. unifiedLine.iceUfrag = iceUfrag;
  26474. unifiedLine.icePwd = icePwd;
  26475. unifiedLine.fingerprint = fingerprint;
  26476. unifiedLine.port = port;
  26477. mid2ul[unifiedLine.mid] = unifiedLine;
  26478. }
  26479. });
  26480. }
  26481. });
  26482. // Rebuild the media array in the right order and add the missing mLines
  26483. // (missing from the Plan B SDP).
  26484. session.media = [];
  26485. mids = []; // reuse
  26486. if (desc.type === 'answer') {
  26487. // The media lines in the answer must match the media lines in the
  26488. // offer. The order is important too. Here we assume that Firefox is the
  26489. // answerer, so we merely have to use the reconstructed (unified) answer
  26490. // to update the cached (unified) answer accordingly.
  26491. //
  26492. // In the general case, one would have to use the cached (unified) offer
  26493. // to find the m-lines that are missing from the reconstructed answer,
  26494. // potentially grabbing them from the cached (unified) answer. One has
  26495. // to be carefull with this approach because inactive m-lines do not
  26496. // always have an mid, making it tricky (impossible?) to find where
  26497. // exactly and which m-lines are missing from the reconstructed answer.
  26498. for (var i = 0; i < cached.media.length; i++) {
  26499. var unifiedLine = cached.media[i];
  26500. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  26501. // The mid isn't in the reconstructed (unified) answer.
  26502. // This is either a (unified) m-line containing a remote
  26503. // track only, or a (unified) m-line containing a remote
  26504. // track and a local track that has been removed.
  26505. // In either case, it MUST exist in the cached
  26506. // (unified) answer.
  26507. //
  26508. // In case this is a removed local track, clean-up
  26509. // the (unified) m-line and make sure it's 'recvonly' or
  26510. // 'inactive'.
  26511. delete unifiedLine.msid;
  26512. delete unifiedLine.sources;
  26513. delete unifiedLine.ssrcGroups;
  26514. if (!unifiedLine.direction
  26515. || unifiedLine.direction === 'sendrecv')
  26516. unifiedLine.direction = 'recvonly';
  26517. if (!unifiedLine.direction
  26518. || unifiedLine.direction === 'sendonly')
  26519. unifiedLine.direction = 'inactive';
  26520. } else {
  26521. // This is an (unified) m-line/channel that contains a local
  26522. // track (sendrecv or sendonly channel) or it's a unified
  26523. // recvonly m-line/channel. In either case, since we're
  26524. // going from PlanB -> Unified Plan this m-line MUST
  26525. // exist in the cached answer.
  26526. }
  26527. session.media.push(unifiedLine);
  26528. if (typeof unifiedLine.mid === 'string') {
  26529. // inactive lines don't/may not have an mid.
  26530. mids.push(unifiedLine.mid);
  26531. }
  26532. }
  26533. } else {
  26534. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  26535. // under any circumstances. If we are no longer interested in sending a
  26536. // track, we just remove the msid and ssrc attributes and set it to
  26537. // either a=recvonly (as the reofferer, we must use recvonly if the
  26538. // other side was previously sending on the m-section, but we can also
  26539. // leave the possibility open if it wasn't previously in use), or
  26540. // a=inacive.
  26541. if (typeof cached !== 'undefined' &&
  26542. typeof cached.media !== 'undefined' &&
  26543. Array.isArray(cached.media)) {
  26544. cached.media.forEach(function(unifiedLine) {
  26545. mids.push(unifiedLine.mid);
  26546. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  26547. session.media.push(mid2ul[unifiedLine.mid]);
  26548. } else {
  26549. delete unifiedLine.msid;
  26550. delete unifiedLine.sources;
  26551. delete unifiedLine.ssrcGroups;
  26552. if (!unifiedLine.direction
  26553. || unifiedLine.direction === 'sendrecv')
  26554. unifiedLine.direction = 'recvonly';
  26555. if (!unifiedLine.direction
  26556. || unifiedLine.direction === 'sendonly')
  26557. unifiedLine.direction = 'inactive';
  26558. session.media.push(unifiedLine);
  26559. }
  26560. });
  26561. }
  26562. // Add all the remaining (new) m-lines of the transformed SDP.
  26563. Object.keys(mid2ul).forEach(function(mid) {
  26564. if (mids.indexOf(mid) === -1) {
  26565. mids.push(mid);
  26566. if (typeof mid2ul[mid].direction === 'recvonly') {
  26567. // This is a remote recvonly channel. Add its SSRC to the
  26568. // appropriate sendrecv or sendonly channel.
  26569. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  26570. session.media.some(function (unifiedLine) {
  26571. if ((unifiedLine.direction === 'sendrecv' ||
  26572. unifiedLine.direction === 'sendonly') &&
  26573. unifiedLine.type === mid2ul[mid].type) {
  26574. // mid2ul[mid] shouldn't have any ssrc-groups
  26575. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  26576. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  26577. });
  26578. return true;
  26579. }
  26580. });
  26581. } else {
  26582. session.media.push(mid2ul[mid]);
  26583. }
  26584. }
  26585. });
  26586. }
  26587. // We regenerate the BUNDLE group (since we regenerated the mids)
  26588. session.groups.some(function(group) {
  26589. if (group.type === 'BUNDLE') {
  26590. group.mids = mids.join(' ');
  26591. return true;
  26592. }
  26593. });
  26594. // msid semantic
  26595. session.msidSemantic = {
  26596. semantic: 'WMS',
  26597. token: '*'
  26598. };
  26599. var resStr = transform.write(session);
  26600. // Cache the transformed SDP (Unified Plan) for later re-use in this
  26601. // function.
  26602. this.cache[desc.type] = resStr;
  26603. return new RTCSessionDescription({
  26604. type: desc.type,
  26605. sdp: resStr
  26606. });
  26607. //#endregion
  26608. };
  26609. },{"./array-equals":96,"./transform":99}],99:[function(require,module,exports){
  26610. var transform = require('sdp-transform');
  26611. exports.write = function(session, opts) {
  26612. if (typeof session !== 'undefined' &&
  26613. typeof session.media !== 'undefined' &&
  26614. Array.isArray(session.media)) {
  26615. session.media.forEach(function (mLine) {
  26616. // expand sources to ssrcs
  26617. if (typeof mLine.sources !== 'undefined' &&
  26618. Object.keys(mLine.sources).length !== 0) {
  26619. mLine.ssrcs = [];
  26620. Object.keys(mLine.sources).forEach(function (ssrc) {
  26621. var source = mLine.sources[ssrc];
  26622. Object.keys(source).forEach(function (attribute) {
  26623. mLine.ssrcs.push({
  26624. id: ssrc,
  26625. attribute: attribute,
  26626. value: source[attribute]
  26627. });
  26628. });
  26629. });
  26630. delete mLine.sources;
  26631. }
  26632. // join ssrcs in ssrc groups
  26633. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26634. Array.isArray(mLine.ssrcGroups)) {
  26635. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26636. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  26637. Array.isArray(ssrcGroup.ssrcs)) {
  26638. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  26639. }
  26640. });
  26641. }
  26642. });
  26643. }
  26644. // join group mids
  26645. if (typeof session !== 'undefined' &&
  26646. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26647. session.groups.forEach(function (g) {
  26648. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  26649. g.mids = g.mids.join(' ');
  26650. }
  26651. });
  26652. }
  26653. return transform.write(session, opts);
  26654. };
  26655. exports.parse = function(sdp) {
  26656. var session = transform.parse(sdp);
  26657. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  26658. Array.isArray(session.media)) {
  26659. session.media.forEach(function (mLine) {
  26660. // group sources attributes by ssrc
  26661. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26662. mLine.sources = {};
  26663. mLine.ssrcs.forEach(function (ssrc) {
  26664. if (!mLine.sources[ssrc.id])
  26665. mLine.sources[ssrc.id] = {};
  26666. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26667. });
  26668. delete mLine.ssrcs;
  26669. }
  26670. // split ssrcs in ssrc groups
  26671. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26672. Array.isArray(mLine.ssrcGroups)) {
  26673. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26674. if (typeof ssrcGroup.ssrcs === 'string') {
  26675. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  26676. }
  26677. });
  26678. }
  26679. });
  26680. }
  26681. // split group mids
  26682. if (typeof session !== 'undefined' &&
  26683. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26684. session.groups.forEach(function (g) {
  26685. if (typeof g.mids === 'string') {
  26686. g.mids = g.mids.split(' ');
  26687. }
  26688. });
  26689. }
  26690. return session;
  26691. };
  26692. },{"sdp-transform":101}],100:[function(require,module,exports){
  26693. var grammar = module.exports = {
  26694. v: [{
  26695. name: 'version',
  26696. reg: /^(\d*)$/
  26697. }],
  26698. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26699. // NB: sessionId will be a String in most cases because it is huge
  26700. name: 'origin',
  26701. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26702. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26703. format: "%s %s %d %s IP%d %s"
  26704. }],
  26705. // default parsing of these only (though some of these feel outdated)
  26706. s: [{ name: 'name' }],
  26707. i: [{ name: 'description' }],
  26708. u: [{ name: 'uri' }],
  26709. e: [{ name: 'email' }],
  26710. p: [{ name: 'phone' }],
  26711. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26712. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26713. //k: [{}], // outdated thing ignored
  26714. t: [{ //t=0 0
  26715. name: 'timing',
  26716. reg: /^(\d*) (\d*)/,
  26717. names: ['start', 'stop'],
  26718. format: "%d %d"
  26719. }],
  26720. c: [{ //c=IN IP4 10.47.197.26
  26721. name: 'connection',
  26722. reg: /^IN IP(\d) (\S*)/,
  26723. names: ['version', 'ip'],
  26724. format: "IN IP%d %s"
  26725. }],
  26726. b: [{ //b=AS:4000
  26727. push: 'bandwidth',
  26728. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26729. names: ['type', 'limit'],
  26730. format: "%s:%s"
  26731. }],
  26732. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26733. // NB: special - pushes to session
  26734. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26735. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26736. names: ['type', 'port', 'protocol', 'payloads'],
  26737. format: "%s %d %s %s"
  26738. }],
  26739. a: [
  26740. { //a=rtpmap:110 opus/48000/2
  26741. push: 'rtp',
  26742. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26743. names: ['payload', 'codec', 'rate', 'encoding'],
  26744. format: function (o) {
  26745. return (o.encoding) ?
  26746. "rtpmap:%d %s/%s/%s":
  26747. "rtpmap:%d %s/%s";
  26748. }
  26749. },
  26750. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26751. push: 'fmtp',
  26752. reg: /^fmtp:(\d*) (\S*)/,
  26753. names: ['payload', 'config'],
  26754. format: "fmtp:%d %s"
  26755. },
  26756. { //a=control:streamid=0
  26757. name: 'control',
  26758. reg: /^control:(.*)/,
  26759. format: "control:%s"
  26760. },
  26761. { //a=rtcp:65179 IN IP4 193.84.77.194
  26762. name: 'rtcp',
  26763. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26764. names: ['port', 'netType', 'ipVer', 'address'],
  26765. format: function (o) {
  26766. return (o.address != null) ?
  26767. "rtcp:%d %s IP%d %s":
  26768. "rtcp:%d";
  26769. }
  26770. },
  26771. { //a=rtcp-fb:98 trr-int 100
  26772. push: 'rtcpFbTrrInt',
  26773. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26774. names: ['payload', 'value'],
  26775. format: "rtcp-fb:%d trr-int %d"
  26776. },
  26777. { //a=rtcp-fb:98 nack rpsi
  26778. push: 'rtcpFb',
  26779. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26780. names: ['payload', 'type', 'subtype'],
  26781. format: function (o) {
  26782. return (o.subtype != null) ?
  26783. "rtcp-fb:%s %s %s":
  26784. "rtcp-fb:%s %s";
  26785. }
  26786. },
  26787. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26788. //a=extmap:1/recvonly URI-gps-string
  26789. push: 'ext',
  26790. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26791. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26792. format: function (o) {
  26793. return (o.config != null) ?
  26794. "extmap:%s %s %s":
  26795. "extmap:%s %s";
  26796. }
  26797. },
  26798. {
  26799. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26800. push: 'crypto',
  26801. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26802. names: ['id', 'suite', 'config', 'sessionConfig'],
  26803. format: function (o) {
  26804. return (o.sessionConfig != null) ?
  26805. "crypto:%d %s %s %s":
  26806. "crypto:%d %s %s";
  26807. }
  26808. },
  26809. { //a=setup:actpass
  26810. name: 'setup',
  26811. reg: /^setup:(\w*)/,
  26812. format: "setup:%s"
  26813. },
  26814. { //a=mid:1
  26815. name: 'mid',
  26816. reg: /^mid:([^\s]*)/,
  26817. format: "mid:%s"
  26818. },
  26819. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26820. name: 'msid',
  26821. reg: /^msid:(.*)/,
  26822. format: "msid:%s"
  26823. },
  26824. { //a=ptime:20
  26825. name: 'ptime',
  26826. reg: /^ptime:(\d*)/,
  26827. format: "ptime:%d"
  26828. },
  26829. { //a=maxptime:60
  26830. name: 'maxptime',
  26831. reg: /^maxptime:(\d*)/,
  26832. format: "maxptime:%d"
  26833. },
  26834. { //a=sendrecv
  26835. name: 'direction',
  26836. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26837. },
  26838. { //a=ice-lite
  26839. name: 'icelite',
  26840. reg: /^(ice-lite)/
  26841. },
  26842. { //a=ice-ufrag:F7gI
  26843. name: 'iceUfrag',
  26844. reg: /^ice-ufrag:(\S*)/,
  26845. format: "ice-ufrag:%s"
  26846. },
  26847. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26848. name: 'icePwd',
  26849. reg: /^ice-pwd:(\S*)/,
  26850. format: "ice-pwd:%s"
  26851. },
  26852. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26853. name: 'fingerprint',
  26854. reg: /^fingerprint:(\S*) (\S*)/,
  26855. names: ['type', 'hash'],
  26856. format: "fingerprint:%s %s"
  26857. },
  26858. {
  26859. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26860. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26861. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26862. push:'candidates',
  26863. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26864. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26865. format: function (o) {
  26866. var str = "candidate:%s %d %s %d %s %d typ %s";
  26867. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26868. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26869. if (o.generation != null) {
  26870. str += " generation %d";
  26871. }
  26872. return str;
  26873. }
  26874. },
  26875. { //a=end-of-candidates (keep after the candidates line for readability)
  26876. name: 'endOfCandidates',
  26877. reg: /^(end-of-candidates)/
  26878. },
  26879. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26880. name: 'remoteCandidates',
  26881. reg: /^remote-candidates:(.*)/,
  26882. format: "remote-candidates:%s"
  26883. },
  26884. { //a=ice-options:google-ice
  26885. name: 'iceOptions',
  26886. reg: /^ice-options:(\S*)/,
  26887. format: "ice-options:%s"
  26888. },
  26889. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26890. push: "ssrcs",
  26891. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26892. names: ['id', 'attribute', 'value'],
  26893. format: "ssrc:%d %s:%s"
  26894. },
  26895. { //a=ssrc-group:FEC 1 2
  26896. push: "ssrcGroups",
  26897. reg: /^ssrc-group:(\w*) (.*)/,
  26898. names: ['semantics', 'ssrcs'],
  26899. format: "ssrc-group:%s %s"
  26900. },
  26901. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26902. name: "msidSemantic",
  26903. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26904. names: ['semantic', 'token'],
  26905. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26906. },
  26907. { //a=group:BUNDLE audio video
  26908. push: 'groups',
  26909. reg: /^group:(\w*) (.*)/,
  26910. names: ['type', 'mids'],
  26911. format: "group:%s %s"
  26912. },
  26913. { //a=rtcp-mux
  26914. name: 'rtcpMux',
  26915. reg: /^(rtcp-mux)/
  26916. },
  26917. { //a=rtcp-rsize
  26918. name: 'rtcpRsize',
  26919. reg: /^(rtcp-rsize)/
  26920. },
  26921. { // any a= that we don't understand is kepts verbatim on media.invalid
  26922. push: 'invalid',
  26923. names: ["value"]
  26924. }
  26925. ]
  26926. };
  26927. // set sensible defaults to avoid polluting the grammar with boring details
  26928. Object.keys(grammar).forEach(function (key) {
  26929. var objs = grammar[key];
  26930. objs.forEach(function (obj) {
  26931. if (!obj.reg) {
  26932. obj.reg = /(.*)/;
  26933. }
  26934. if (!obj.format) {
  26935. obj.format = "%s";
  26936. }
  26937. });
  26938. });
  26939. },{}],101:[function(require,module,exports){
  26940. var parser = require('./parser');
  26941. var writer = require('./writer');
  26942. exports.write = writer;
  26943. exports.parse = parser.parse;
  26944. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26945. exports.parsePayloads = parser.parsePayloads;
  26946. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26947. },{"./parser":102,"./writer":103}],102:[function(require,module,exports){
  26948. var toIntIfInt = function (v) {
  26949. return String(Number(v)) === v ? Number(v) : v;
  26950. };
  26951. var attachProperties = function (match, location, names, rawName) {
  26952. if (rawName && !names) {
  26953. location[rawName] = toIntIfInt(match[1]);
  26954. }
  26955. else {
  26956. for (var i = 0; i < names.length; i += 1) {
  26957. if (match[i+1] != null) {
  26958. location[names[i]] = toIntIfInt(match[i+1]);
  26959. }
  26960. }
  26961. }
  26962. };
  26963. var parseReg = function (obj, location, content) {
  26964. var needsBlank = obj.name && obj.names;
  26965. if (obj.push && !location[obj.push]) {
  26966. location[obj.push] = [];
  26967. }
  26968. else if (needsBlank && !location[obj.name]) {
  26969. location[obj.name] = {};
  26970. }
  26971. var keyLocation = obj.push ?
  26972. {} : // blank object that will be pushed
  26973. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26974. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26975. if (obj.push) {
  26976. location[obj.push].push(keyLocation);
  26977. }
  26978. };
  26979. var grammar = require('./grammar');
  26980. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26981. exports.parse = function (sdp) {
  26982. var session = {}
  26983. , media = []
  26984. , location = session; // points at where properties go under (one of the above)
  26985. // parse lines we understand
  26986. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26987. var type = l[0];
  26988. var content = l.slice(2);
  26989. if (type === 'm') {
  26990. media.push({rtp: [], fmtp: []});
  26991. location = media[media.length-1]; // point at latest media line
  26992. }
  26993. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26994. var obj = grammar[type][j];
  26995. if (obj.reg.test(content)) {
  26996. return parseReg(obj, location, content);
  26997. }
  26998. }
  26999. });
  27000. session.media = media; // link it up
  27001. return session;
  27002. };
  27003. var fmtpReducer = function (acc, expr) {
  27004. var s = expr.split('=');
  27005. if (s.length === 2) {
  27006. acc[s[0]] = toIntIfInt(s[1]);
  27007. }
  27008. return acc;
  27009. };
  27010. exports.parseFmtpConfig = function (str) {
  27011. return str.split(';').reduce(fmtpReducer, {});
  27012. };
  27013. exports.parsePayloads = function (str) {
  27014. return str.split(' ').map(Number);
  27015. };
  27016. exports.parseRemoteCandidates = function (str) {
  27017. var candidates = [];
  27018. var parts = str.split(' ').map(toIntIfInt);
  27019. for (var i = 0; i < parts.length; i += 3) {
  27020. candidates.push({
  27021. component: parts[i],
  27022. ip: parts[i + 1],
  27023. port: parts[i + 2]
  27024. });
  27025. }
  27026. return candidates;
  27027. };
  27028. },{"./grammar":100}],103:[function(require,module,exports){
  27029. var grammar = require('./grammar');
  27030. // customized util.format - discards excess arguments and can void middle ones
  27031. var formatRegExp = /%[sdv%]/g;
  27032. var format = function (formatStr) {
  27033. var i = 1;
  27034. var args = arguments;
  27035. var len = args.length;
  27036. return formatStr.replace(formatRegExp, function (x) {
  27037. if (i >= len) {
  27038. return x; // missing argument
  27039. }
  27040. var arg = args[i];
  27041. i += 1;
  27042. switch (x) {
  27043. case '%%':
  27044. return '%';
  27045. case '%s':
  27046. return String(arg);
  27047. case '%d':
  27048. return Number(arg);
  27049. case '%v':
  27050. return '';
  27051. }
  27052. });
  27053. // NB: we discard excess arguments - they are typically undefined from makeLine
  27054. };
  27055. var makeLine = function (type, obj, location) {
  27056. var str = obj.format instanceof Function ?
  27057. (obj.format(obj.push ? location : location[obj.name])) :
  27058. obj.format;
  27059. var args = [type + '=' + str];
  27060. if (obj.names) {
  27061. for (var i = 0; i < obj.names.length; i += 1) {
  27062. var n = obj.names[i];
  27063. if (obj.name) {
  27064. args.push(location[obj.name][n]);
  27065. }
  27066. else { // for mLine and push attributes
  27067. args.push(location[obj.names[i]]);
  27068. }
  27069. }
  27070. }
  27071. else {
  27072. args.push(location[obj.name]);
  27073. }
  27074. return format.apply(null, args);
  27075. };
  27076. // RFC specified order
  27077. // TODO: extend this with all the rest
  27078. var defaultOuterOrder = [
  27079. 'v', 'o', 's', 'i',
  27080. 'u', 'e', 'p', 'c',
  27081. 'b', 't', 'r', 'z', 'a'
  27082. ];
  27083. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  27084. module.exports = function (session, opts) {
  27085. opts = opts || {};
  27086. // ensure certain properties exist
  27087. if (session.version == null) {
  27088. session.version = 0; // "v=0" must be there (only defined version atm)
  27089. }
  27090. if (session.name == null) {
  27091. session.name = " "; // "s= " must be there if no meaningful name set
  27092. }
  27093. session.media.forEach(function (mLine) {
  27094. if (mLine.payloads == null) {
  27095. mLine.payloads = "";
  27096. }
  27097. });
  27098. var outerOrder = opts.outerOrder || defaultOuterOrder;
  27099. var innerOrder = opts.innerOrder || defaultInnerOrder;
  27100. var sdp = [];
  27101. // loop through outerOrder for matching properties on session
  27102. outerOrder.forEach(function (type) {
  27103. grammar[type].forEach(function (obj) {
  27104. if (obj.name in session && session[obj.name] != null) {
  27105. sdp.push(makeLine(type, obj, session));
  27106. }
  27107. else if (obj.push in session && session[obj.push] != null) {
  27108. session[obj.push].forEach(function (el) {
  27109. sdp.push(makeLine(type, obj, el));
  27110. });
  27111. }
  27112. });
  27113. });
  27114. // then for each media line, follow the innerOrder
  27115. session.media.forEach(function (mLine) {
  27116. sdp.push(makeLine('m', grammar.m[0], mLine));
  27117. innerOrder.forEach(function (type) {
  27118. grammar[type].forEach(function (obj) {
  27119. if (obj.name in mLine && mLine[obj.name] != null) {
  27120. sdp.push(makeLine(type, obj, mLine));
  27121. }
  27122. else if (obj.push in mLine && mLine[obj.push] != null) {
  27123. mLine[obj.push].forEach(function (el) {
  27124. sdp.push(makeLine(type, obj, el));
  27125. });
  27126. }
  27127. });
  27128. });
  27129. });
  27130. return sdp.join('\r\n') + '\r\n';
  27131. };
  27132. },{"./grammar":100}],104:[function(require,module,exports){
  27133. var transform = require('sdp-transform');
  27134. var transformUtils = require('./transform-utils');
  27135. var parseSsrcs = transformUtils.parseSsrcs;
  27136. var writeSsrcs = transformUtils.writeSsrcs;
  27137. //region Constants
  27138. var DEFAULT_NUM_OF_LAYERS = 3;
  27139. //endregion
  27140. //region Ctor
  27141. function Simulcast(options) {
  27142. this.options = options ? options : {};
  27143. if (!this.options.numOfLayers) {
  27144. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  27145. }
  27146. this.layers = [];
  27147. }
  27148. //endregion
  27149. //region Stateless private utility functions
  27150. /**
  27151. * Returns a random integer between min (included) and max (excluded)
  27152. * Using Math.round() gives a non-uniform distribution!
  27153. * @returns {number}
  27154. */
  27155. function generateSSRC() {
  27156. var min = 0, max = 0xffffffff;
  27157. return Math.floor(Math.random() * (max - min)) + min;
  27158. };
  27159. function processVideo(session, action) {
  27160. if (session == null || !Array.isArray(session.media)) {
  27161. return;
  27162. }
  27163. session.media.forEach(function (mLine) {
  27164. if (mLine.type === 'video') {
  27165. action(mLine);
  27166. }
  27167. });
  27168. }
  27169. function validateDescription(desc)
  27170. {
  27171. return desc && desc != null
  27172. && desc.type && desc.type != ''
  27173. && desc.sdp && desc.sdp != '';
  27174. }
  27175. function explodeRemoteSimulcast(mLine) {
  27176. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  27177. return;
  27178. }
  27179. var sources = parseSsrcs(mLine);
  27180. var order = [];
  27181. // Find the SIM group and explode its sources.
  27182. var j = mLine.ssrcGroups.length;
  27183. while (j--) {
  27184. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  27185. continue;
  27186. }
  27187. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  27188. for (var i = 0; i < simulcastSsrcs.length; i++) {
  27189. var ssrc = simulcastSsrcs[i];
  27190. order.push(ssrc);
  27191. var parts = sources[ssrc].msid.split(' ');
  27192. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  27193. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  27194. // Remove all the groups that this SSRC participates in.
  27195. mLine.ssrcGroups.forEach(function (relatedGroup) {
  27196. if (relatedGroup.semantics === 'SIM') {
  27197. return;
  27198. }
  27199. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  27200. if (relatedSsrcs.indexOf(ssrc) === -1) {
  27201. return;
  27202. }
  27203. // Nuke all the related SSRCs.
  27204. relatedSsrcs.forEach(function (relatedSSRC) {
  27205. sources[relatedSSRC].msid = sources[ssrc].msid;
  27206. sources[relatedSSRC].cname = sources[ssrc].cname;
  27207. if (relatedSSRC !== ssrc) {
  27208. order.push(relatedSSRC);
  27209. }
  27210. });
  27211. // Schedule the related group for nuking.
  27212. })
  27213. }
  27214. mLine.ssrcs = writeSsrcs(sources, order);
  27215. mLine.ssrcGroups.splice(j, 1);
  27216. };
  27217. }
  27218. function squeezeRemoteSimulcast(mLine) {
  27219. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  27220. return;
  27221. }
  27222. var sources = parseSsrcs(mLine);
  27223. // Find the SIM group and nuke it.
  27224. mLine.ssrcGroups.some(function (simulcastGroup) {
  27225. if (simulcastGroup.semantics !== 'SIM') {
  27226. return false;
  27227. }
  27228. // Schedule the SIM group for nuking.
  27229. simulcastGroup.nuke = true;
  27230. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  27231. // Nuke all the higher layer SSRCs.
  27232. for (var i = 1; i < simulcastSsrcs.length; i++) {
  27233. var ssrc = simulcastSsrcs[i];
  27234. delete sources[ssrc];
  27235. // Remove all the groups that this SSRC participates in.
  27236. mLine.ssrcGroups.forEach(function (relatedGroup) {
  27237. if (relatedGroup.semantics === 'SIM') {
  27238. return;
  27239. }
  27240. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  27241. if (relatedSsrcs.indexOf(ssrc) === -1) {
  27242. return;
  27243. }
  27244. // Nuke all the related SSRCs.
  27245. relatedSsrcs.forEach(function (relatedSSRC) {
  27246. delete sources[relatedSSRC];
  27247. });
  27248. // Schedule the related group for nuking.
  27249. relatedGroup.nuke = true;
  27250. })
  27251. }
  27252. return true;
  27253. });
  27254. mLine.ssrcs = writeSsrcs(sources);
  27255. // Nuke all the scheduled groups.
  27256. var i = mLine.ssrcGroups.length;
  27257. while (i--) {
  27258. if (mLine.ssrcGroups[i].nuke) {
  27259. mLine.ssrcGroups.splice(i, 1);
  27260. }
  27261. }
  27262. }
  27263. function removeGoogConference(mLine) {
  27264. if (!mLine || !Array.isArray(mLine.invalid)) {
  27265. return;
  27266. }
  27267. var i = mLine.invalid.length;
  27268. while (i--) {
  27269. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  27270. mLine.invalid.splice(i, 1);
  27271. }
  27272. }
  27273. }
  27274. function assertGoogConference(mLine) {
  27275. if (!mLine) {
  27276. return;
  27277. }
  27278. if (!Array.isArray(mLine.invalid)) {
  27279. mLine.invalid = [];
  27280. }
  27281. if (!mLine.invalid.some(
  27282. function (i) { return i.value === 'x-google-flag:conference' })) {
  27283. mLine.invalid.push({'value': 'x-google-flag:conference'});
  27284. }
  27285. }
  27286. //endregion
  27287. //region "Private" functions
  27288. /**
  27289. *
  27290. * @param mLine
  27291. * @private
  27292. */
  27293. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  27294. if (!mLine || mLine.type !== 'video') {
  27295. return;
  27296. }
  27297. var sources = parseSsrcs(mLine);
  27298. if (Object.keys(sources).length === 0) {
  27299. // no sources, disable simulcast.
  27300. if (this.layers.length !== 0) {
  27301. this.layers = [];
  27302. }
  27303. return;
  27304. }
  27305. // find the base layer (we'll reuse its msid and cname).
  27306. var baseLayerSSRC = Object.keys(sources)[0];
  27307. var baseLayer = sources[baseLayerSSRC];
  27308. // todo(gp) handle screen sharing.
  27309. // check if base CNAME has changed and reinitialise layers.
  27310. if (this.layers.length > 0
  27311. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  27312. this.layers = [];
  27313. }
  27314. // (re)initialise layers
  27315. if (this.layers.length < 1) {
  27316. // first push the base layer.
  27317. this.layers.push({
  27318. ssrc: baseLayerSSRC,
  27319. msid: baseLayer.msid,
  27320. cname: baseLayer.cname
  27321. });
  27322. var rtx = false; // RFC 4588
  27323. if (Array.isArray(mLine.rtp)) {
  27324. rtx = mLine.rtp.some(
  27325. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  27326. }
  27327. if (rtx) {
  27328. this.layers[0].rtx = generateSSRC();
  27329. }
  27330. // now push additional layers.
  27331. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  27332. var layer = { ssrc: generateSSRC() };
  27333. if (rtx) {
  27334. layer.rtx = generateSSRC();
  27335. }
  27336. this.layers.push(layer);
  27337. }
  27338. }
  27339. };
  27340. /**
  27341. *
  27342. * @param mLine
  27343. * @private
  27344. */
  27345. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  27346. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  27347. var sources = {};
  27348. var msid = this.layers[0].msid;
  27349. var cname = this.layers[0].cname;
  27350. var simulcastSsrcs = [];
  27351. var ssrcGroups = [];
  27352. for (var i = 0; i < this.layers.length; i++) {
  27353. var layer = this.layers[i];
  27354. sources[layer.ssrc] = { msid: msid, cname: cname };
  27355. simulcastSsrcs.push(layer.ssrc);
  27356. if (layer.rtx) {
  27357. sources[layer.rtx] = {
  27358. msid: msid,
  27359. cname: cname
  27360. }
  27361. ssrcGroups.push({
  27362. semantics: 'FID',
  27363. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  27364. });
  27365. }
  27366. }
  27367. ssrcGroups.push({
  27368. semantics: 'SIM',
  27369. ssrcs: simulcastSsrcs.join(' ')
  27370. });
  27371. mLine.ssrcGroups = ssrcGroups;
  27372. mLine.ssrcs = writeSsrcs(sources);
  27373. }
  27374. }
  27375. //endregion
  27376. //region "Public" functions
  27377. Simulcast.prototype.isSupported = function () {
  27378. return window.chrome;
  27379. // TODO this needs improvements. For example I doubt that Chrome in Android
  27380. // has simulcast support. Also, only recent versions of Chromium have native
  27381. // simulcast support.
  27382. }
  27383. /**
  27384. *
  27385. * @param desc
  27386. * @returns {RTCSessionDescription}
  27387. */
  27388. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  27389. if (!validateDescription(desc)) {
  27390. return desc;
  27391. }
  27392. var session = transform.parse(desc.sdp);
  27393. var self = this;
  27394. processVideo(session, function (mLine) {
  27395. // Handle simulcast reception.
  27396. if (self.options.explodeRemoteSimulcast) {
  27397. explodeRemoteSimulcast(mLine);
  27398. } else {
  27399. squeezeRemoteSimulcast(mLine);
  27400. }
  27401. // If native simulcast is enabled, we must append the x-goog-conference
  27402. // attribute to the SDP.
  27403. if (self.layers.length < 1) {
  27404. removeGoogConference(mLine);
  27405. } else {
  27406. assertGoogConference(mLine);
  27407. }
  27408. });
  27409. return new RTCSessionDescription({
  27410. type: desc.type,
  27411. sdp: transform.write(session)
  27412. });
  27413. };
  27414. /**
  27415. *
  27416. * @param desc
  27417. * @returns {RTCSessionDescription}
  27418. */
  27419. Simulcast.prototype.mungeLocalDescription = function (desc) {
  27420. if (!validateDescription(desc) || !this.isSupported()) {
  27421. return desc;
  27422. }
  27423. var session = transform.parse(desc.sdp);
  27424. var self = this;
  27425. processVideo(session, function (mLine) {
  27426. // Initialize native simulcast layers, if not already done.
  27427. self._maybeInitializeLayers(mLine);
  27428. // Update the SDP with the simulcast layers.
  27429. self._restoreSimulcastView(mLine);
  27430. });
  27431. return new RTCSessionDescription({
  27432. type: desc.type,
  27433. sdp: transform.write(session)
  27434. });
  27435. };
  27436. //endregion
  27437. module.exports = Simulcast;
  27438. },{"./transform-utils":105,"sdp-transform":107}],105:[function(require,module,exports){
  27439. exports.writeSsrcs = function(sources, order) {
  27440. var ssrcs = [];
  27441. // expand sources to ssrcs
  27442. if (typeof sources !== 'undefined' &&
  27443. Object.keys(sources).length !== 0) {
  27444. if (Array.isArray(order)) {
  27445. for (var i = 0; i < order.length; i++) {
  27446. var ssrc = order[i];
  27447. var source = sources[ssrc];
  27448. Object.keys(source).forEach(function (attribute) {
  27449. ssrcs.push({
  27450. id: ssrc,
  27451. attribute: attribute,
  27452. value: source[attribute]
  27453. });
  27454. });
  27455. }
  27456. } else {
  27457. Object.keys(sources).forEach(function (ssrc) {
  27458. var source = sources[ssrc];
  27459. Object.keys(source).forEach(function (attribute) {
  27460. ssrcs.push({
  27461. id: ssrc,
  27462. attribute: attribute,
  27463. value: source[attribute]
  27464. });
  27465. });
  27466. });
  27467. }
  27468. }
  27469. return ssrcs;
  27470. };
  27471. exports.parseSsrcs = function (mLine) {
  27472. var sources = {};
  27473. // group sources attributes by ssrc.
  27474. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  27475. mLine.ssrcs.forEach(function (ssrc) {
  27476. if (!sources[ssrc.id])
  27477. sources[ssrc.id] = {};
  27478. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  27479. });
  27480. }
  27481. return sources;
  27482. };
  27483. },{}],106:[function(require,module,exports){
  27484. arguments[4][100][0].apply(exports,arguments)
  27485. },{"dup":100}],107:[function(require,module,exports){
  27486. arguments[4][101][0].apply(exports,arguments)
  27487. },{"./parser":108,"./writer":109,"dup":101}],108:[function(require,module,exports){
  27488. arguments[4][102][0].apply(exports,arguments)
  27489. },{"./grammar":106,"dup":102}],109:[function(require,module,exports){
  27490. arguments[4][103][0].apply(exports,arguments)
  27491. },{"./grammar":106,"dup":103}],110:[function(require,module,exports){
  27492. var grammar = module.exports = {
  27493. v: [{
  27494. name: 'version',
  27495. reg: /^(\d*)$/
  27496. }],
  27497. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  27498. // NB: sessionId will be a String in most cases because it is huge
  27499. name: 'origin',
  27500. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  27501. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  27502. format: "%s %s %d %s IP%d %s"
  27503. }],
  27504. // default parsing of these only (though some of these feel outdated)
  27505. s: [{ name: 'name' }],
  27506. i: [{ name: 'description' }],
  27507. u: [{ name: 'uri' }],
  27508. e: [{ name: 'email' }],
  27509. p: [{ name: 'phone' }],
  27510. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  27511. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  27512. //k: [{}], // outdated thing ignored
  27513. t: [{ //t=0 0
  27514. name: 'timing',
  27515. reg: /^(\d*) (\d*)/,
  27516. names: ['start', 'stop'],
  27517. format: "%d %d"
  27518. }],
  27519. c: [{ //c=IN IP4 10.47.197.26
  27520. name: 'connection',
  27521. reg: /^IN IP(\d) (\S*)/,
  27522. names: ['version', 'ip'],
  27523. format: "IN IP%d %s"
  27524. }],
  27525. b: [{ //b=AS:4000
  27526. push: 'bandwidth',
  27527. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  27528. names: ['type', 'limit'],
  27529. format: "%s:%s"
  27530. }],
  27531. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  27532. // NB: special - pushes to session
  27533. // TODO: rtp/fmtp should be filtered by the payloads found here?
  27534. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  27535. names: ['type', 'port', 'protocol', 'payloads'],
  27536. format: "%s %d %s %s"
  27537. }],
  27538. a: [
  27539. { //a=rtpmap:110 opus/48000/2
  27540. push: 'rtp',
  27541. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  27542. names: ['payload', 'codec', 'rate', 'encoding'],
  27543. format: function (o) {
  27544. return (o.encoding) ?
  27545. "rtpmap:%d %s/%s/%s":
  27546. "rtpmap:%d %s/%s";
  27547. }
  27548. },
  27549. {
  27550. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  27551. //a=fmtp:111 minptime=10; useinbandfec=1
  27552. push: 'fmtp',
  27553. reg: /^fmtp:(\d*) ([\S| ]*)/,
  27554. names: ['payload', 'config'],
  27555. format: "fmtp:%d %s"
  27556. },
  27557. { //a=control:streamid=0
  27558. name: 'control',
  27559. reg: /^control:(.*)/,
  27560. format: "control:%s"
  27561. },
  27562. { //a=rtcp:65179 IN IP4 193.84.77.194
  27563. name: 'rtcp',
  27564. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  27565. names: ['port', 'netType', 'ipVer', 'address'],
  27566. format: function (o) {
  27567. return (o.address != null) ?
  27568. "rtcp:%d %s IP%d %s":
  27569. "rtcp:%d";
  27570. }
  27571. },
  27572. { //a=rtcp-fb:98 trr-int 100
  27573. push: 'rtcpFbTrrInt',
  27574. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  27575. names: ['payload', 'value'],
  27576. format: "rtcp-fb:%d trr-int %d"
  27577. },
  27578. { //a=rtcp-fb:98 nack rpsi
  27579. push: 'rtcpFb',
  27580. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  27581. names: ['payload', 'type', 'subtype'],
  27582. format: function (o) {
  27583. return (o.subtype != null) ?
  27584. "rtcp-fb:%s %s %s":
  27585. "rtcp-fb:%s %s";
  27586. }
  27587. },
  27588. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  27589. //a=extmap:1/recvonly URI-gps-string
  27590. push: 'ext',
  27591. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  27592. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  27593. format: function (o) {
  27594. return (o.config != null) ?
  27595. "extmap:%s %s %s":
  27596. "extmap:%s %s";
  27597. }
  27598. },
  27599. {
  27600. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  27601. push: 'crypto',
  27602. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  27603. names: ['id', 'suite', 'config', 'sessionConfig'],
  27604. format: function (o) {
  27605. return (o.sessionConfig != null) ?
  27606. "crypto:%d %s %s %s":
  27607. "crypto:%d %s %s";
  27608. }
  27609. },
  27610. { //a=setup:actpass
  27611. name: 'setup',
  27612. reg: /^setup:(\w*)/,
  27613. format: "setup:%s"
  27614. },
  27615. { //a=mid:1
  27616. name: 'mid',
  27617. reg: /^mid:([^\s]*)/,
  27618. format: "mid:%s"
  27619. },
  27620. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  27621. name: 'msid',
  27622. reg: /^msid:(.*)/,
  27623. format: "msid:%s"
  27624. },
  27625. { //a=ptime:20
  27626. name: 'ptime',
  27627. reg: /^ptime:(\d*)/,
  27628. format: "ptime:%d"
  27629. },
  27630. { //a=maxptime:60
  27631. name: 'maxptime',
  27632. reg: /^maxptime:(\d*)/,
  27633. format: "maxptime:%d"
  27634. },
  27635. { //a=sendrecv
  27636. name: 'direction',
  27637. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  27638. },
  27639. { //a=ice-lite
  27640. name: 'icelite',
  27641. reg: /^(ice-lite)/
  27642. },
  27643. { //a=ice-ufrag:F7gI
  27644. name: 'iceUfrag',
  27645. reg: /^ice-ufrag:(\S*)/,
  27646. format: "ice-ufrag:%s"
  27647. },
  27648. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  27649. name: 'icePwd',
  27650. reg: /^ice-pwd:(\S*)/,
  27651. format: "ice-pwd:%s"
  27652. },
  27653. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  27654. name: 'fingerprint',
  27655. reg: /^fingerprint:(\S*) (\S*)/,
  27656. names: ['type', 'hash'],
  27657. format: "fingerprint:%s %s"
  27658. },
  27659. {
  27660. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  27661. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  27662. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  27663. push:'candidates',
  27664. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  27665. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  27666. format: function (o) {
  27667. var str = "candidate:%s %d %s %d %s %d typ %s";
  27668. // NB: candidate has two optional chunks, so %void middle one if it's missing
  27669. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  27670. if (o.generation != null) {
  27671. str += " generation %d";
  27672. }
  27673. return str;
  27674. }
  27675. },
  27676. { //a=end-of-candidates (keep after the candidates line for readability)
  27677. name: 'endOfCandidates',
  27678. reg: /^(end-of-candidates)/
  27679. },
  27680. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  27681. name: 'remoteCandidates',
  27682. reg: /^remote-candidates:(.*)/,
  27683. format: "remote-candidates:%s"
  27684. },
  27685. { //a=ice-options:google-ice
  27686. name: 'iceOptions',
  27687. reg: /^ice-options:(\S*)/,
  27688. format: "ice-options:%s"
  27689. },
  27690. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  27691. push: "ssrcs",
  27692. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  27693. names: ['id', 'attribute', 'value'],
  27694. format: "ssrc:%d %s:%s"
  27695. },
  27696. { //a=ssrc-group:FEC 1 2
  27697. push: "ssrcGroups",
  27698. reg: /^ssrc-group:(\w*) (.*)/,
  27699. names: ['semantics', 'ssrcs'],
  27700. format: "ssrc-group:%s %s"
  27701. },
  27702. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  27703. name: "msidSemantic",
  27704. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  27705. names: ['semantic', 'token'],
  27706. format: "msid-semantic: %s %s" // space after ":" is not accidental
  27707. },
  27708. { //a=group:BUNDLE audio video
  27709. push: 'groups',
  27710. reg: /^group:(\w*) (.*)/,
  27711. names: ['type', 'mids'],
  27712. format: "group:%s %s"
  27713. },
  27714. { //a=rtcp-mux
  27715. name: 'rtcpMux',
  27716. reg: /^(rtcp-mux)/
  27717. },
  27718. { //a=rtcp-rsize
  27719. name: 'rtcpRsize',
  27720. reg: /^(rtcp-rsize)/
  27721. },
  27722. { // any a= that we don't understand is kepts verbatim on media.invalid
  27723. push: 'invalid',
  27724. names: ["value"]
  27725. }
  27726. ]
  27727. };
  27728. // set sensible defaults to avoid polluting the grammar with boring details
  27729. Object.keys(grammar).forEach(function (key) {
  27730. var objs = grammar[key];
  27731. objs.forEach(function (obj) {
  27732. if (!obj.reg) {
  27733. obj.reg = /(.*)/;
  27734. }
  27735. if (!obj.format) {
  27736. obj.format = "%s";
  27737. }
  27738. });
  27739. });
  27740. },{}],111:[function(require,module,exports){
  27741. arguments[4][101][0].apply(exports,arguments)
  27742. },{"./parser":112,"./writer":113,"dup":101}],112:[function(require,module,exports){
  27743. var toIntIfInt = function (v) {
  27744. return String(Number(v)) === v ? Number(v) : v;
  27745. };
  27746. var attachProperties = function (match, location, names, rawName) {
  27747. if (rawName && !names) {
  27748. location[rawName] = toIntIfInt(match[1]);
  27749. }
  27750. else {
  27751. for (var i = 0; i < names.length; i += 1) {
  27752. if (match[i+1] != null) {
  27753. location[names[i]] = toIntIfInt(match[i+1]);
  27754. }
  27755. }
  27756. }
  27757. };
  27758. var parseReg = function (obj, location, content) {
  27759. var needsBlank = obj.name && obj.names;
  27760. if (obj.push && !location[obj.push]) {
  27761. location[obj.push] = [];
  27762. }
  27763. else if (needsBlank && !location[obj.name]) {
  27764. location[obj.name] = {};
  27765. }
  27766. var keyLocation = obj.push ?
  27767. {} : // blank object that will be pushed
  27768. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  27769. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  27770. if (obj.push) {
  27771. location[obj.push].push(keyLocation);
  27772. }
  27773. };
  27774. var grammar = require('./grammar');
  27775. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  27776. exports.parse = function (sdp) {
  27777. var session = {}
  27778. , media = []
  27779. , location = session; // points at where properties go under (one of the above)
  27780. // parse lines we understand
  27781. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  27782. var type = l[0];
  27783. var content = l.slice(2);
  27784. if (type === 'm') {
  27785. media.push({rtp: [], fmtp: []});
  27786. location = media[media.length-1]; // point at latest media line
  27787. }
  27788. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  27789. var obj = grammar[type][j];
  27790. if (obj.reg.test(content)) {
  27791. return parseReg(obj, location, content);
  27792. }
  27793. }
  27794. });
  27795. session.media = media; // link it up
  27796. return session;
  27797. };
  27798. var fmtpReducer = function (acc, expr) {
  27799. var s = expr.split('=');
  27800. if (s.length === 2) {
  27801. acc[s[0]] = toIntIfInt(s[1]);
  27802. }
  27803. return acc;
  27804. };
  27805. exports.parseFmtpConfig = function (str) {
  27806. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  27807. };
  27808. exports.parsePayloads = function (str) {
  27809. return str.split(' ').map(Number);
  27810. };
  27811. exports.parseRemoteCandidates = function (str) {
  27812. var candidates = [];
  27813. var parts = str.split(' ').map(toIntIfInt);
  27814. for (var i = 0; i < parts.length; i += 3) {
  27815. candidates.push({
  27816. component: parts[i],
  27817. ip: parts[i + 1],
  27818. port: parts[i + 2]
  27819. });
  27820. }
  27821. return candidates;
  27822. };
  27823. },{"./grammar":110}],113:[function(require,module,exports){
  27824. arguments[4][103][0].apply(exports,arguments)
  27825. },{"./grammar":110,"dup":103}],114:[function(require,module,exports){
  27826. module.exports = require('./lib/');
  27827. },{"./lib/":115}],115:[function(require,module,exports){
  27828. /**
  27829. * Module dependencies.
  27830. */
  27831. var url = require('./url');
  27832. var parser = require('socket.io-parser');
  27833. var Manager = require('./manager');
  27834. var debug = require('debug')('socket.io-client');
  27835. /**
  27836. * Module exports.
  27837. */
  27838. module.exports = exports = lookup;
  27839. /**
  27840. * Managers cache.
  27841. */
  27842. var cache = exports.managers = {};
  27843. /**
  27844. * Looks up an existing `Manager` for multiplexing.
  27845. * If the user summons:
  27846. *
  27847. * `io('http://localhost/a');`
  27848. * `io('http://localhost/b');`
  27849. *
  27850. * We reuse the existing instance based on same scheme/port/host,
  27851. * and we initialize sockets for each namespace.
  27852. *
  27853. * @api public
  27854. */
  27855. function lookup(uri, opts) {
  27856. if (typeof uri == 'object') {
  27857. opts = uri;
  27858. uri = undefined;
  27859. }
  27860. opts = opts || {};
  27861. var parsed = url(uri);
  27862. var source = parsed.source;
  27863. var id = parsed.id;
  27864. var io;
  27865. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  27866. debug('ignoring socket cache for %s', source);
  27867. io = Manager(source, opts);
  27868. } else {
  27869. if (!cache[id]) {
  27870. debug('new io instance for %s', source);
  27871. cache[id] = Manager(source, opts);
  27872. }
  27873. io = cache[id];
  27874. }
  27875. return io.socket(parsed.path);
  27876. }
  27877. /**
  27878. * Protocol version.
  27879. *
  27880. * @api public
  27881. */
  27882. exports.protocol = parser.protocol;
  27883. /**
  27884. * `connect`.
  27885. *
  27886. * @param {String} uri
  27887. * @api public
  27888. */
  27889. exports.connect = lookup;
  27890. /**
  27891. * Expose constructors for standalone build.
  27892. *
  27893. * @api public
  27894. */
  27895. exports.Manager = require('./manager');
  27896. exports.Socket = require('./socket');
  27897. },{"./manager":116,"./socket":118,"./url":119,"debug":123,"socket.io-parser":159}],116:[function(require,module,exports){
  27898. /**
  27899. * Module dependencies.
  27900. */
  27901. var url = require('./url');
  27902. var eio = require('engine.io-client');
  27903. var Socket = require('./socket');
  27904. var Emitter = require('component-emitter');
  27905. var parser = require('socket.io-parser');
  27906. var on = require('./on');
  27907. var bind = require('component-bind');
  27908. var object = require('object-component');
  27909. var debug = require('debug')('socket.io-client:manager');
  27910. var indexOf = require('indexof');
  27911. var Backoff = require('backo2');
  27912. /**
  27913. * Module exports
  27914. */
  27915. module.exports = Manager;
  27916. /**
  27917. * `Manager` constructor.
  27918. *
  27919. * @param {String} engine instance or engine uri/opts
  27920. * @param {Object} options
  27921. * @api public
  27922. */
  27923. function Manager(uri, opts){
  27924. if (!(this instanceof Manager)) return new Manager(uri, opts);
  27925. if (uri && ('object' == typeof uri)) {
  27926. opts = uri;
  27927. uri = undefined;
  27928. }
  27929. opts = opts || {};
  27930. opts.path = opts.path || '/socket.io';
  27931. this.nsps = {};
  27932. this.subs = [];
  27933. this.opts = opts;
  27934. this.reconnection(opts.reconnection !== false);
  27935. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  27936. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  27937. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  27938. this.randomizationFactor(opts.randomizationFactor || 0.5);
  27939. this.backoff = new Backoff({
  27940. min: this.reconnectionDelay(),
  27941. max: this.reconnectionDelayMax(),
  27942. jitter: this.randomizationFactor()
  27943. });
  27944. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  27945. this.readyState = 'closed';
  27946. this.uri = uri;
  27947. this.connected = [];
  27948. this.encoding = false;
  27949. this.packetBuffer = [];
  27950. this.encoder = new parser.Encoder();
  27951. this.decoder = new parser.Decoder();
  27952. this.autoConnect = opts.autoConnect !== false;
  27953. if (this.autoConnect) this.open();
  27954. }
  27955. /**
  27956. * Propagate given event to sockets and emit on `this`
  27957. *
  27958. * @api private
  27959. */
  27960. Manager.prototype.emitAll = function() {
  27961. this.emit.apply(this, arguments);
  27962. for (var nsp in this.nsps) {
  27963. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  27964. }
  27965. };
  27966. /**
  27967. * Update `socket.id` of all sockets
  27968. *
  27969. * @api private
  27970. */
  27971. Manager.prototype.updateSocketIds = function(){
  27972. for (var nsp in this.nsps) {
  27973. this.nsps[nsp].id = this.engine.id;
  27974. }
  27975. };
  27976. /**
  27977. * Mix in `Emitter`.
  27978. */
  27979. Emitter(Manager.prototype);
  27980. /**
  27981. * Sets the `reconnection` config.
  27982. *
  27983. * @param {Boolean} true/false if it should automatically reconnect
  27984. * @return {Manager} self or value
  27985. * @api public
  27986. */
  27987. Manager.prototype.reconnection = function(v){
  27988. if (!arguments.length) return this._reconnection;
  27989. this._reconnection = !!v;
  27990. return this;
  27991. };
  27992. /**
  27993. * Sets the reconnection attempts config.
  27994. *
  27995. * @param {Number} max reconnection attempts before giving up
  27996. * @return {Manager} self or value
  27997. * @api public
  27998. */
  27999. Manager.prototype.reconnectionAttempts = function(v){
  28000. if (!arguments.length) return this._reconnectionAttempts;
  28001. this._reconnectionAttempts = v;
  28002. return this;
  28003. };
  28004. /**
  28005. * Sets the delay between reconnections.
  28006. *
  28007. * @param {Number} delay
  28008. * @return {Manager} self or value
  28009. * @api public
  28010. */
  28011. Manager.prototype.reconnectionDelay = function(v){
  28012. if (!arguments.length) return this._reconnectionDelay;
  28013. this._reconnectionDelay = v;
  28014. this.backoff && this.backoff.setMin(v);
  28015. return this;
  28016. };
  28017. Manager.prototype.randomizationFactor = function(v){
  28018. if (!arguments.length) return this._randomizationFactor;
  28019. this._randomizationFactor = v;
  28020. this.backoff && this.backoff.setJitter(v);
  28021. return this;
  28022. };
  28023. /**
  28024. * Sets the maximum delay between reconnections.
  28025. *
  28026. * @param {Number} delay
  28027. * @return {Manager} self or value
  28028. * @api public
  28029. */
  28030. Manager.prototype.reconnectionDelayMax = function(v){
  28031. if (!arguments.length) return this._reconnectionDelayMax;
  28032. this._reconnectionDelayMax = v;
  28033. this.backoff && this.backoff.setMax(v);
  28034. return this;
  28035. };
  28036. /**
  28037. * Sets the connection timeout. `false` to disable
  28038. *
  28039. * @return {Manager} self or value
  28040. * @api public
  28041. */
  28042. Manager.prototype.timeout = function(v){
  28043. if (!arguments.length) return this._timeout;
  28044. this._timeout = v;
  28045. return this;
  28046. };
  28047. /**
  28048. * Starts trying to reconnect if reconnection is enabled and we have not
  28049. * started reconnecting yet
  28050. *
  28051. * @api private
  28052. */
  28053. Manager.prototype.maybeReconnectOnOpen = function() {
  28054. // Only try to reconnect if it's the first time we're connecting
  28055. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  28056. // keeps reconnection from firing twice for the same reconnection loop
  28057. this.reconnect();
  28058. }
  28059. };
  28060. /**
  28061. * Sets the current transport `socket`.
  28062. *
  28063. * @param {Function} optional, callback
  28064. * @return {Manager} self
  28065. * @api public
  28066. */
  28067. Manager.prototype.open =
  28068. Manager.prototype.connect = function(fn){
  28069. debug('readyState %s', this.readyState);
  28070. if (~this.readyState.indexOf('open')) return this;
  28071. debug('opening %s', this.uri);
  28072. this.engine = eio(this.uri, this.opts);
  28073. var socket = this.engine;
  28074. var self = this;
  28075. this.readyState = 'opening';
  28076. this.skipReconnect = false;
  28077. // emit `open`
  28078. var openSub = on(socket, 'open', function() {
  28079. self.onopen();
  28080. fn && fn();
  28081. });
  28082. // emit `connect_error`
  28083. var errorSub = on(socket, 'error', function(data){
  28084. debug('connect_error');
  28085. self.cleanup();
  28086. self.readyState = 'closed';
  28087. self.emitAll('connect_error', data);
  28088. if (fn) {
  28089. var err = new Error('Connection error');
  28090. err.data = data;
  28091. fn(err);
  28092. } else {
  28093. // Only do this if there is no fn to handle the error
  28094. self.maybeReconnectOnOpen();
  28095. }
  28096. });
  28097. // emit `connect_timeout`
  28098. if (false !== this._timeout) {
  28099. var timeout = this._timeout;
  28100. debug('connect attempt will timeout after %d', timeout);
  28101. // set timer
  28102. var timer = setTimeout(function(){
  28103. debug('connect attempt timed out after %d', timeout);
  28104. openSub.destroy();
  28105. socket.close();
  28106. socket.emit('error', 'timeout');
  28107. self.emitAll('connect_timeout', timeout);
  28108. }, timeout);
  28109. this.subs.push({
  28110. destroy: function(){
  28111. clearTimeout(timer);
  28112. }
  28113. });
  28114. }
  28115. this.subs.push(openSub);
  28116. this.subs.push(errorSub);
  28117. return this;
  28118. };
  28119. /**
  28120. * Called upon transport open.
  28121. *
  28122. * @api private
  28123. */
  28124. Manager.prototype.onopen = function(){
  28125. debug('open');
  28126. // clear old subs
  28127. this.cleanup();
  28128. // mark as open
  28129. this.readyState = 'open';
  28130. this.emit('open');
  28131. // add new subs
  28132. var socket = this.engine;
  28133. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  28134. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  28135. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  28136. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  28137. };
  28138. /**
  28139. * Called with data.
  28140. *
  28141. * @api private
  28142. */
  28143. Manager.prototype.ondata = function(data){
  28144. this.decoder.add(data);
  28145. };
  28146. /**
  28147. * Called when parser fully decodes a packet.
  28148. *
  28149. * @api private
  28150. */
  28151. Manager.prototype.ondecoded = function(packet) {
  28152. this.emit('packet', packet);
  28153. };
  28154. /**
  28155. * Called upon socket error.
  28156. *
  28157. * @api private
  28158. */
  28159. Manager.prototype.onerror = function(err){
  28160. debug('error', err);
  28161. this.emitAll('error', err);
  28162. };
  28163. /**
  28164. * Creates a new socket for the given `nsp`.
  28165. *
  28166. * @return {Socket}
  28167. * @api public
  28168. */
  28169. Manager.prototype.socket = function(nsp){
  28170. var socket = this.nsps[nsp];
  28171. if (!socket) {
  28172. socket = new Socket(this, nsp);
  28173. this.nsps[nsp] = socket;
  28174. var self = this;
  28175. socket.on('connect', function(){
  28176. socket.id = self.engine.id;
  28177. if (!~indexOf(self.connected, socket)) {
  28178. self.connected.push(socket);
  28179. }
  28180. });
  28181. }
  28182. return socket;
  28183. };
  28184. /**
  28185. * Called upon a socket close.
  28186. *
  28187. * @param {Socket} socket
  28188. */
  28189. Manager.prototype.destroy = function(socket){
  28190. var index = indexOf(this.connected, socket);
  28191. if (~index) this.connected.splice(index, 1);
  28192. if (this.connected.length) return;
  28193. this.close();
  28194. };
  28195. /**
  28196. * Writes a packet.
  28197. *
  28198. * @param {Object} packet
  28199. * @api private
  28200. */
  28201. Manager.prototype.packet = function(packet){
  28202. debug('writing packet %j', packet);
  28203. var self = this;
  28204. if (!self.encoding) {
  28205. // encode, then write to engine with result
  28206. self.encoding = true;
  28207. this.encoder.encode(packet, function(encodedPackets) {
  28208. for (var i = 0; i < encodedPackets.length; i++) {
  28209. self.engine.write(encodedPackets[i]);
  28210. }
  28211. self.encoding = false;
  28212. self.processPacketQueue();
  28213. });
  28214. } else { // add packet to the queue
  28215. self.packetBuffer.push(packet);
  28216. }
  28217. };
  28218. /**
  28219. * If packet buffer is non-empty, begins encoding the
  28220. * next packet in line.
  28221. *
  28222. * @api private
  28223. */
  28224. Manager.prototype.processPacketQueue = function() {
  28225. if (this.packetBuffer.length > 0 && !this.encoding) {
  28226. var pack = this.packetBuffer.shift();
  28227. this.packet(pack);
  28228. }
  28229. };
  28230. /**
  28231. * Clean up transport subscriptions and packet buffer.
  28232. *
  28233. * @api private
  28234. */
  28235. Manager.prototype.cleanup = function(){
  28236. var sub;
  28237. while (sub = this.subs.shift()) sub.destroy();
  28238. this.packetBuffer = [];
  28239. this.encoding = false;
  28240. this.decoder.destroy();
  28241. };
  28242. /**
  28243. * Close the current socket.
  28244. *
  28245. * @api private
  28246. */
  28247. Manager.prototype.close =
  28248. Manager.prototype.disconnect = function(){
  28249. this.skipReconnect = true;
  28250. this.backoff.reset();
  28251. this.readyState = 'closed';
  28252. this.engine && this.engine.close();
  28253. };
  28254. /**
  28255. * Called upon engine close.
  28256. *
  28257. * @api private
  28258. */
  28259. Manager.prototype.onclose = function(reason){
  28260. debug('close');
  28261. this.cleanup();
  28262. this.backoff.reset();
  28263. this.readyState = 'closed';
  28264. this.emit('close', reason);
  28265. if (this._reconnection && !this.skipReconnect) {
  28266. this.reconnect();
  28267. }
  28268. };
  28269. /**
  28270. * Attempt a reconnection.
  28271. *
  28272. * @api private
  28273. */
  28274. Manager.prototype.reconnect = function(){
  28275. if (this.reconnecting || this.skipReconnect) return this;
  28276. var self = this;
  28277. if (this.backoff.attempts >= this._reconnectionAttempts) {
  28278. debug('reconnect failed');
  28279. this.backoff.reset();
  28280. this.emitAll('reconnect_failed');
  28281. this.reconnecting = false;
  28282. } else {
  28283. var delay = this.backoff.duration();
  28284. debug('will wait %dms before reconnect attempt', delay);
  28285. this.reconnecting = true;
  28286. var timer = setTimeout(function(){
  28287. if (self.skipReconnect) return;
  28288. debug('attempting reconnect');
  28289. self.emitAll('reconnect_attempt', self.backoff.attempts);
  28290. self.emitAll('reconnecting', self.backoff.attempts);
  28291. // check again for the case socket closed in above events
  28292. if (self.skipReconnect) return;
  28293. self.open(function(err){
  28294. if (err) {
  28295. debug('reconnect attempt error');
  28296. self.reconnecting = false;
  28297. self.reconnect();
  28298. self.emitAll('reconnect_error', err.data);
  28299. } else {
  28300. debug('reconnect success');
  28301. self.onreconnect();
  28302. }
  28303. });
  28304. }, delay);
  28305. this.subs.push({
  28306. destroy: function(){
  28307. clearTimeout(timer);
  28308. }
  28309. });
  28310. }
  28311. };
  28312. /**
  28313. * Called upon successful reconnect.
  28314. *
  28315. * @api private
  28316. */
  28317. Manager.prototype.onreconnect = function(){
  28318. var attempt = this.backoff.attempts;
  28319. this.reconnecting = false;
  28320. this.backoff.reset();
  28321. this.updateSocketIds();
  28322. this.emitAll('reconnect', attempt);
  28323. };
  28324. },{"./on":117,"./socket":118,"./url":119,"backo2":120,"component-bind":121,"component-emitter":122,"debug":123,"engine.io-client":124,"indexof":155,"object-component":156,"socket.io-parser":159}],117:[function(require,module,exports){
  28325. /**
  28326. * Module exports.
  28327. */
  28328. module.exports = on;
  28329. /**
  28330. * Helper for subscriptions.
  28331. *
  28332. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  28333. * @param {String} event name
  28334. * @param {Function} callback
  28335. * @api public
  28336. */
  28337. function on(obj, ev, fn) {
  28338. obj.on(ev, fn);
  28339. return {
  28340. destroy: function(){
  28341. obj.removeListener(ev, fn);
  28342. }
  28343. };
  28344. }
  28345. },{}],118:[function(require,module,exports){
  28346. /**
  28347. * Module dependencies.
  28348. */
  28349. var parser = require('socket.io-parser');
  28350. var Emitter = require('component-emitter');
  28351. var toArray = require('to-array');
  28352. var on = require('./on');
  28353. var bind = require('component-bind');
  28354. var debug = require('debug')('socket.io-client:socket');
  28355. var hasBin = require('has-binary');
  28356. /**
  28357. * Module exports.
  28358. */
  28359. module.exports = exports = Socket;
  28360. /**
  28361. * Internal events (blacklisted).
  28362. * These events can't be emitted by the user.
  28363. *
  28364. * @api private
  28365. */
  28366. var events = {
  28367. connect: 1,
  28368. connect_error: 1,
  28369. connect_timeout: 1,
  28370. disconnect: 1,
  28371. error: 1,
  28372. reconnect: 1,
  28373. reconnect_attempt: 1,
  28374. reconnect_failed: 1,
  28375. reconnect_error: 1,
  28376. reconnecting: 1
  28377. };
  28378. /**
  28379. * Shortcut to `Emitter#emit`.
  28380. */
  28381. var emit = Emitter.prototype.emit;
  28382. /**
  28383. * `Socket` constructor.
  28384. *
  28385. * @api public
  28386. */
  28387. function Socket(io, nsp){
  28388. this.io = io;
  28389. this.nsp = nsp;
  28390. this.json = this; // compat
  28391. this.ids = 0;
  28392. this.acks = {};
  28393. if (this.io.autoConnect) this.open();
  28394. this.receiveBuffer = [];
  28395. this.sendBuffer = [];
  28396. this.connected = false;
  28397. this.disconnected = true;
  28398. }
  28399. /**
  28400. * Mix in `Emitter`.
  28401. */
  28402. Emitter(Socket.prototype);
  28403. /**
  28404. * Subscribe to open, close and packet events
  28405. *
  28406. * @api private
  28407. */
  28408. Socket.prototype.subEvents = function() {
  28409. if (this.subs) return;
  28410. var io = this.io;
  28411. this.subs = [
  28412. on(io, 'open', bind(this, 'onopen')),
  28413. on(io, 'packet', bind(this, 'onpacket')),
  28414. on(io, 'close', bind(this, 'onclose'))
  28415. ];
  28416. };
  28417. /**
  28418. * "Opens" the socket.
  28419. *
  28420. * @api public
  28421. */
  28422. Socket.prototype.open =
  28423. Socket.prototype.connect = function(){
  28424. if (this.connected) return this;
  28425. this.subEvents();
  28426. this.io.open(); // ensure open
  28427. if ('open' == this.io.readyState) this.onopen();
  28428. return this;
  28429. };
  28430. /**
  28431. * Sends a `message` event.
  28432. *
  28433. * @return {Socket} self
  28434. * @api public
  28435. */
  28436. Socket.prototype.send = function(){
  28437. var args = toArray(arguments);
  28438. args.unshift('message');
  28439. this.emit.apply(this, args);
  28440. return this;
  28441. };
  28442. /**
  28443. * Override `emit`.
  28444. * If the event is in `events`, it's emitted normally.
  28445. *
  28446. * @param {String} event name
  28447. * @return {Socket} self
  28448. * @api public
  28449. */
  28450. Socket.prototype.emit = function(ev){
  28451. if (events.hasOwnProperty(ev)) {
  28452. emit.apply(this, arguments);
  28453. return this;
  28454. }
  28455. var args = toArray(arguments);
  28456. var parserType = parser.EVENT; // default
  28457. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  28458. var packet = { type: parserType, data: args };
  28459. // event ack callback
  28460. if ('function' == typeof args[args.length - 1]) {
  28461. debug('emitting packet with ack id %d', this.ids);
  28462. this.acks[this.ids] = args.pop();
  28463. packet.id = this.ids++;
  28464. }
  28465. if (this.connected) {
  28466. this.packet(packet);
  28467. } else {
  28468. this.sendBuffer.push(packet);
  28469. }
  28470. return this;
  28471. };
  28472. /**
  28473. * Sends a packet.
  28474. *
  28475. * @param {Object} packet
  28476. * @api private
  28477. */
  28478. Socket.prototype.packet = function(packet){
  28479. packet.nsp = this.nsp;
  28480. this.io.packet(packet);
  28481. };
  28482. /**
  28483. * Called upon engine `open`.
  28484. *
  28485. * @api private
  28486. */
  28487. Socket.prototype.onopen = function(){
  28488. debug('transport is open - connecting');
  28489. // write connect packet if necessary
  28490. if ('/' != this.nsp) {
  28491. this.packet({ type: parser.CONNECT });
  28492. }
  28493. };
  28494. /**
  28495. * Called upon engine `close`.
  28496. *
  28497. * @param {String} reason
  28498. * @api private
  28499. */
  28500. Socket.prototype.onclose = function(reason){
  28501. debug('close (%s)', reason);
  28502. this.connected = false;
  28503. this.disconnected = true;
  28504. delete this.id;
  28505. this.emit('disconnect', reason);
  28506. };
  28507. /**
  28508. * Called with socket packet.
  28509. *
  28510. * @param {Object} packet
  28511. * @api private
  28512. */
  28513. Socket.prototype.onpacket = function(packet){
  28514. if (packet.nsp != this.nsp) return;
  28515. switch (packet.type) {
  28516. case parser.CONNECT:
  28517. this.onconnect();
  28518. break;
  28519. case parser.EVENT:
  28520. this.onevent(packet);
  28521. break;
  28522. case parser.BINARY_EVENT:
  28523. this.onevent(packet);
  28524. break;
  28525. case parser.ACK:
  28526. this.onack(packet);
  28527. break;
  28528. case parser.BINARY_ACK:
  28529. this.onack(packet);
  28530. break;
  28531. case parser.DISCONNECT:
  28532. this.ondisconnect();
  28533. break;
  28534. case parser.ERROR:
  28535. this.emit('error', packet.data);
  28536. break;
  28537. }
  28538. };
  28539. /**
  28540. * Called upon a server event.
  28541. *
  28542. * @param {Object} packet
  28543. * @api private
  28544. */
  28545. Socket.prototype.onevent = function(packet){
  28546. var args = packet.data || [];
  28547. debug('emitting event %j', args);
  28548. if (null != packet.id) {
  28549. debug('attaching ack callback to event');
  28550. args.push(this.ack(packet.id));
  28551. }
  28552. if (this.connected) {
  28553. emit.apply(this, args);
  28554. } else {
  28555. this.receiveBuffer.push(args);
  28556. }
  28557. };
  28558. /**
  28559. * Produces an ack callback to emit with an event.
  28560. *
  28561. * @api private
  28562. */
  28563. Socket.prototype.ack = function(id){
  28564. var self = this;
  28565. var sent = false;
  28566. return function(){
  28567. // prevent double callbacks
  28568. if (sent) return;
  28569. sent = true;
  28570. var args = toArray(arguments);
  28571. debug('sending ack %j', args);
  28572. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  28573. self.packet({
  28574. type: type,
  28575. id: id,
  28576. data: args
  28577. });
  28578. };
  28579. };
  28580. /**
  28581. * Called upon a server acknowlegement.
  28582. *
  28583. * @param {Object} packet
  28584. * @api private
  28585. */
  28586. Socket.prototype.onack = function(packet){
  28587. debug('calling ack %s with %j', packet.id, packet.data);
  28588. var fn = this.acks[packet.id];
  28589. fn.apply(this, packet.data);
  28590. delete this.acks[packet.id];
  28591. };
  28592. /**
  28593. * Called upon server connect.
  28594. *
  28595. * @api private
  28596. */
  28597. Socket.prototype.onconnect = function(){
  28598. this.connected = true;
  28599. this.disconnected = false;
  28600. this.emit('connect');
  28601. this.emitBuffered();
  28602. };
  28603. /**
  28604. * Emit buffered events (received and emitted).
  28605. *
  28606. * @api private
  28607. */
  28608. Socket.prototype.emitBuffered = function(){
  28609. var i;
  28610. for (i = 0; i < this.receiveBuffer.length; i++) {
  28611. emit.apply(this, this.receiveBuffer[i]);
  28612. }
  28613. this.receiveBuffer = [];
  28614. for (i = 0; i < this.sendBuffer.length; i++) {
  28615. this.packet(this.sendBuffer[i]);
  28616. }
  28617. this.sendBuffer = [];
  28618. };
  28619. /**
  28620. * Called upon server disconnect.
  28621. *
  28622. * @api private
  28623. */
  28624. Socket.prototype.ondisconnect = function(){
  28625. debug('server disconnect (%s)', this.nsp);
  28626. this.destroy();
  28627. this.onclose('io server disconnect');
  28628. };
  28629. /**
  28630. * Called upon forced client/server side disconnections,
  28631. * this method ensures the manager stops tracking us and
  28632. * that reconnections don't get triggered for this.
  28633. *
  28634. * @api private.
  28635. */
  28636. Socket.prototype.destroy = function(){
  28637. if (this.subs) {
  28638. // clean subscriptions to avoid reconnections
  28639. for (var i = 0; i < this.subs.length; i++) {
  28640. this.subs[i].destroy();
  28641. }
  28642. this.subs = null;
  28643. }
  28644. this.io.destroy(this);
  28645. };
  28646. /**
  28647. * Disconnects the socket manually.
  28648. *
  28649. * @return {Socket} self
  28650. * @api public
  28651. */
  28652. Socket.prototype.close =
  28653. Socket.prototype.disconnect = function(){
  28654. if (this.connected) {
  28655. debug('performing disconnect (%s)', this.nsp);
  28656. this.packet({ type: parser.DISCONNECT });
  28657. }
  28658. // remove socket from pool
  28659. this.destroy();
  28660. if (this.connected) {
  28661. // fire events
  28662. this.onclose('io client disconnect');
  28663. }
  28664. return this;
  28665. };
  28666. },{"./on":117,"component-bind":121,"component-emitter":122,"debug":123,"has-binary":153,"socket.io-parser":159,"to-array":163}],119:[function(require,module,exports){
  28667. (function (global){
  28668. /**
  28669. * Module dependencies.
  28670. */
  28671. var parseuri = require('parseuri');
  28672. var debug = require('debug')('socket.io-client:url');
  28673. /**
  28674. * Module exports.
  28675. */
  28676. module.exports = url;
  28677. /**
  28678. * URL parser.
  28679. *
  28680. * @param {String} url
  28681. * @param {Object} An object meant to mimic window.location.
  28682. * Defaults to window.location.
  28683. * @api public
  28684. */
  28685. function url(uri, loc){
  28686. var obj = uri;
  28687. // default to window.location
  28688. var loc = loc || global.location;
  28689. if (null == uri) uri = loc.protocol + '//' + loc.host;
  28690. // relative path support
  28691. if ('string' == typeof uri) {
  28692. if ('/' == uri.charAt(0)) {
  28693. if ('/' == uri.charAt(1)) {
  28694. uri = loc.protocol + uri;
  28695. } else {
  28696. uri = loc.hostname + uri;
  28697. }
  28698. }
  28699. if (!/^(https?|wss?):\/\//.test(uri)) {
  28700. debug('protocol-less url %s', uri);
  28701. if ('undefined' != typeof loc) {
  28702. uri = loc.protocol + '//' + uri;
  28703. } else {
  28704. uri = 'https://' + uri;
  28705. }
  28706. }
  28707. // parse
  28708. debug('parse %s', uri);
  28709. obj = parseuri(uri);
  28710. }
  28711. // make sure we treat `localhost:80` and `localhost` equally
  28712. if (!obj.port) {
  28713. if (/^(http|ws)$/.test(obj.protocol)) {
  28714. obj.port = '80';
  28715. }
  28716. else if (/^(http|ws)s$/.test(obj.protocol)) {
  28717. obj.port = '443';
  28718. }
  28719. }
  28720. obj.path = obj.path || '/';
  28721. // define unique id
  28722. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  28723. // define href
  28724. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  28725. return obj;
  28726. }
  28727. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  28728. },{"debug":123,"parseuri":157}],120:[function(require,module,exports){
  28729. /**
  28730. * Expose `Backoff`.
  28731. */
  28732. module.exports = Backoff;
  28733. /**
  28734. * Initialize backoff timer with `opts`.
  28735. *
  28736. * - `min` initial timeout in milliseconds [100]
  28737. * - `max` max timeout [10000]
  28738. * - `jitter` [0]
  28739. * - `factor` [2]
  28740. *
  28741. * @param {Object} opts
  28742. * @api public
  28743. */
  28744. function Backoff(opts) {
  28745. opts = opts || {};
  28746. this.ms = opts.min || 100;
  28747. this.max = opts.max || 10000;
  28748. this.factor = opts.factor || 2;
  28749. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  28750. this.attempts = 0;
  28751. }
  28752. /**
  28753. * Return the backoff duration.
  28754. *
  28755. * @return {Number}
  28756. * @api public
  28757. */
  28758. Backoff.prototype.duration = function(){
  28759. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  28760. if (this.jitter) {
  28761. var rand = Math.random();
  28762. var deviation = Math.floor(rand * this.jitter * ms);
  28763. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  28764. }
  28765. return Math.min(ms, this.max) | 0;
  28766. };
  28767. /**
  28768. * Reset the number of attempts.
  28769. *
  28770. * @api public
  28771. */
  28772. Backoff.prototype.reset = function(){
  28773. this.attempts = 0;
  28774. };
  28775. /**
  28776. * Set the minimum duration
  28777. *
  28778. * @api public
  28779. */
  28780. Backoff.prototype.setMin = function(min){
  28781. this.ms = min;
  28782. };
  28783. /**
  28784. * Set the maximum duration
  28785. *
  28786. * @api public
  28787. */
  28788. Backoff.prototype.setMax = function(max){
  28789. this.max = max;
  28790. };
  28791. /**
  28792. * Set the jitter
  28793. *
  28794. * @api public
  28795. */
  28796. Backoff.prototype.setJitter = function(jitter){
  28797. this.jitter = jitter;
  28798. };
  28799. },{}],121:[function(require,module,exports){
  28800. /**
  28801. * Slice reference.
  28802. */
  28803. var slice = [].slice;
  28804. /**
  28805. * Bind `obj` to `fn`.
  28806. *
  28807. * @param {Object} obj
  28808. * @param {Function|String} fn or string
  28809. * @return {Function}
  28810. * @api public
  28811. */
  28812. module.exports = function(obj, fn){
  28813. if ('string' == typeof fn) fn = obj[fn];
  28814. if ('function' != typeof fn) throw new Error('bind() requires a function');
  28815. var args = slice.call(arguments, 2);
  28816. return function(){
  28817. return fn.apply(obj, args.concat(slice.call(arguments)));
  28818. }
  28819. };
  28820. },{}],122:[function(require,module,exports){
  28821. /**
  28822. * Expose `Emitter`.
  28823. */
  28824. module.exports = Emitter;
  28825. /**
  28826. * Initialize a new `Emitter`.
  28827. *
  28828. * @api public
  28829. */
  28830. function Emitter(obj) {
  28831. if (obj) return mixin(obj);
  28832. };
  28833. /**
  28834. * Mixin the emitter properties.
  28835. *
  28836. * @param {Object} obj
  28837. * @return {Object}
  28838. * @api private
  28839. */
  28840. function mixin(obj) {
  28841. for (var key in Emitter.prototype) {
  28842. obj[key] = Emitter.prototype[key];
  28843. }
  28844. return obj;
  28845. }
  28846. /**
  28847. * Listen on the given `event` with `fn`.
  28848. *
  28849. * @param {String} event
  28850. * @param {Function} fn
  28851. * @return {Emitter}
  28852. * @api public
  28853. */
  28854. Emitter.prototype.on =
  28855. Emitter.prototype.addEventListener = function(event, fn){
  28856. this._callbacks = this._callbacks || {};
  28857. (this._callbacks[event] = this._callbacks[event] || [])
  28858. .push(fn);
  28859. return this;
  28860. };
  28861. /**
  28862. * Adds an `event` listener that will be invoked a single
  28863. * time then automatically removed.
  28864. *
  28865. * @param {String} event
  28866. * @param {Function} fn
  28867. * @return {Emitter}
  28868. * @api public
  28869. */
  28870. Emitter.prototype.once = function(event, fn){
  28871. var self = this;
  28872. this._callbacks = this._callbacks || {};
  28873. function on() {
  28874. self.off(event, on);
  28875. fn.apply(this, arguments);
  28876. }
  28877. on.fn = fn;
  28878. this.on(event, on);
  28879. return this;
  28880. };
  28881. /**
  28882. * Remove the given callback for `event` or all
  28883. * registered callbacks.
  28884. *
  28885. * @param {String} event
  28886. * @param {Function} fn
  28887. * @return {Emitter}
  28888. * @api public
  28889. */
  28890. Emitter.prototype.off =
  28891. Emitter.prototype.removeListener =
  28892. Emitter.prototype.removeAllListeners =
  28893. Emitter.prototype.removeEventListener = function(event, fn){
  28894. this._callbacks = this._callbacks || {};
  28895. // all
  28896. if (0 == arguments.length) {
  28897. this._callbacks = {};
  28898. return this;
  28899. }
  28900. // specific event
  28901. var callbacks = this._callbacks[event];
  28902. if (!callbacks) return this;
  28903. // remove all handlers
  28904. if (1 == arguments.length) {
  28905. delete this._callbacks[event];
  28906. return this;
  28907. }
  28908. // remove specific handler
  28909. var cb;
  28910. for (var i = 0; i < callbacks.length; i++) {
  28911. cb = callbacks[i];
  28912. if (cb === fn || cb.fn === fn) {
  28913. callbacks.splice(i, 1);
  28914. break;
  28915. }
  28916. }
  28917. return this;
  28918. };
  28919. /**
  28920. * Emit `event` with the given args.
  28921. *
  28922. * @param {String} event
  28923. * @param {Mixed} ...
  28924. * @return {Emitter}
  28925. */
  28926. Emitter.prototype.emit = function(event){
  28927. this._callbacks = this._callbacks || {};
  28928. var args = [].slice.call(arguments, 1)
  28929. , callbacks = this._callbacks[event];
  28930. if (callbacks) {
  28931. callbacks = callbacks.slice(0);
  28932. for (var i = 0, len = callbacks.length; i < len; ++i) {
  28933. callbacks[i].apply(this, args);
  28934. }
  28935. }
  28936. return this;
  28937. };
  28938. /**
  28939. * Return array of callbacks for `event`.
  28940. *
  28941. * @param {String} event
  28942. * @return {Array}
  28943. * @api public
  28944. */
  28945. Emitter.prototype.listeners = function(event){
  28946. this._callbacks = this._callbacks || {};
  28947. return this._callbacks[event] || [];
  28948. };
  28949. /**
  28950. * Check if this emitter has `event` handlers.
  28951. *
  28952. * @param {String} event
  28953. * @return {Boolean}
  28954. * @api public
  28955. */
  28956. Emitter.prototype.hasListeners = function(event){
  28957. return !! this.listeners(event).length;
  28958. };
  28959. },{}],123:[function(require,module,exports){
  28960. /**
  28961. * Expose `debug()` as the module.
  28962. */
  28963. module.exports = debug;
  28964. /**
  28965. * Create a debugger with the given `name`.
  28966. *
  28967. * @param {String} name
  28968. * @return {Type}
  28969. * @api public
  28970. */
  28971. function debug(name) {
  28972. if (!debug.enabled(name)) return function(){};
  28973. return function(fmt){
  28974. fmt = coerce(fmt);
  28975. var curr = new Date;
  28976. var ms = curr - (debug[name] || curr);
  28977. debug[name] = curr;
  28978. fmt = name
  28979. + ' '
  28980. + fmt
  28981. + ' +' + debug.humanize(ms);
  28982. // This hackery is required for IE8
  28983. // where `console.log` doesn't have 'apply'
  28984. window.console
  28985. && console.log
  28986. && Function.prototype.apply.call(console.log, console, arguments);
  28987. }
  28988. }
  28989. /**
  28990. * The currently active debug mode names.
  28991. */
  28992. debug.names = [];
  28993. debug.skips = [];
  28994. /**
  28995. * Enables a debug mode by name. This can include modes
  28996. * separated by a colon and wildcards.
  28997. *
  28998. * @param {String} name
  28999. * @api public
  29000. */
  29001. debug.enable = function(name) {
  29002. try {
  29003. localStorage.debug = name;
  29004. } catch(e){}
  29005. var split = (name || '').split(/[\s,]+/)
  29006. , len = split.length;
  29007. for (var i = 0; i < len; i++) {
  29008. name = split[i].replace('*', '.*?');
  29009. if (name[0] === '-') {
  29010. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  29011. }
  29012. else {
  29013. debug.names.push(new RegExp('^' + name + '$'));
  29014. }
  29015. }
  29016. };
  29017. /**
  29018. * Disable debug output.
  29019. *
  29020. * @api public
  29021. */
  29022. debug.disable = function(){
  29023. debug.enable('');
  29024. };
  29025. /**
  29026. * Humanize the given `ms`.
  29027. *
  29028. * @param {Number} m
  29029. * @return {String}
  29030. * @api private
  29031. */
  29032. debug.humanize = function(ms) {
  29033. var sec = 1000
  29034. , min = 60 * 1000
  29035. , hour = 60 * min;
  29036. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  29037. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  29038. if (ms >= sec) return (ms / sec | 0) + 's';
  29039. return ms + 'ms';
  29040. };
  29041. /**
  29042. * Returns true if the given mode name is enabled, false otherwise.
  29043. *
  29044. * @param {String} name
  29045. * @return {Boolean}
  29046. * @api public
  29047. */
  29048. debug.enabled = function(name) {
  29049. for (var i = 0, len = debug.skips.length; i < len; i++) {
  29050. if (debug.skips[i].test(name)) {
  29051. return false;
  29052. }
  29053. }
  29054. for (var i = 0, len = debug.names.length; i < len; i++) {
  29055. if (debug.names[i].test(name)) {
  29056. return true;
  29057. }
  29058. }
  29059. return false;
  29060. };
  29061. /**
  29062. * Coerce `val`.
  29063. */
  29064. function coerce(val) {
  29065. if (val instanceof Error) return val.stack || val.message;
  29066. return val;
  29067. }
  29068. // persist
  29069. try {
  29070. if (window.localStorage) debug.enable(localStorage.debug);
  29071. } catch(e){}
  29072. },{}],124:[function(require,module,exports){
  29073. module.exports = require('./lib/');
  29074. },{"./lib/":125}],125:[function(require,module,exports){
  29075. module.exports = require('./socket');
  29076. /**
  29077. * Exports parser
  29078. *
  29079. * @api public
  29080. *
  29081. */
  29082. module.exports.parser = require('engine.io-parser');
  29083. },{"./socket":126,"engine.io-parser":138}],126:[function(require,module,exports){
  29084. (function (global){
  29085. /**
  29086. * Module dependencies.
  29087. */
  29088. var transports = require('./transports');
  29089. var Emitter = require('component-emitter');
  29090. var debug = require('debug')('engine.io-client:socket');
  29091. var index = require('indexof');
  29092. var parser = require('engine.io-parser');
  29093. var parseuri = require('parseuri');
  29094. var parsejson = require('parsejson');
  29095. var parseqs = require('parseqs');
  29096. /**
  29097. * Module exports.
  29098. */
  29099. module.exports = Socket;
  29100. /**
  29101. * Noop function.
  29102. *
  29103. * @api private
  29104. */
  29105. function noop(){}
  29106. /**
  29107. * Socket constructor.
  29108. *
  29109. * @param {String|Object} uri or options
  29110. * @param {Object} options
  29111. * @api public
  29112. */
  29113. function Socket(uri, opts){
  29114. if (!(this instanceof Socket)) return new Socket(uri, opts);
  29115. opts = opts || {};
  29116. if (uri && 'object' == typeof uri) {
  29117. opts = uri;
  29118. uri = null;
  29119. }
  29120. if (uri) {
  29121. uri = parseuri(uri);
  29122. opts.host = uri.host;
  29123. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  29124. opts.port = uri.port;
  29125. if (uri.query) opts.query = uri.query;
  29126. }
  29127. this.secure = null != opts.secure ? opts.secure :
  29128. (global.location && 'https:' == location.protocol);
  29129. if (opts.host) {
  29130. var pieces = opts.host.split(':');
  29131. opts.hostname = pieces.shift();
  29132. if (pieces.length) {
  29133. opts.port = pieces.pop();
  29134. } else if (!opts.port) {
  29135. // if no port is specified manually, use the protocol default
  29136. opts.port = this.secure ? '443' : '80';
  29137. }
  29138. }
  29139. this.agent = opts.agent || false;
  29140. this.hostname = opts.hostname ||
  29141. (global.location ? location.hostname : 'localhost');
  29142. this.port = opts.port || (global.location && location.port ?
  29143. location.port :
  29144. (this.secure ? 443 : 80));
  29145. this.query = opts.query || {};
  29146. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  29147. this.upgrade = false !== opts.upgrade;
  29148. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  29149. this.forceJSONP = !!opts.forceJSONP;
  29150. this.jsonp = false !== opts.jsonp;
  29151. this.forceBase64 = !!opts.forceBase64;
  29152. this.enablesXDR = !!opts.enablesXDR;
  29153. this.timestampParam = opts.timestampParam || 't';
  29154. this.timestampRequests = opts.timestampRequests;
  29155. this.transports = opts.transports || ['polling', 'websocket'];
  29156. this.readyState = '';
  29157. this.writeBuffer = [];
  29158. this.callbackBuffer = [];
  29159. this.policyPort = opts.policyPort || 843;
  29160. this.rememberUpgrade = opts.rememberUpgrade || false;
  29161. this.binaryType = null;
  29162. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  29163. // SSL options for Node.js client
  29164. this.pfx = opts.pfx || null;
  29165. this.key = opts.key || null;
  29166. this.passphrase = opts.passphrase || null;
  29167. this.cert = opts.cert || null;
  29168. this.ca = opts.ca || null;
  29169. this.ciphers = opts.ciphers || null;
  29170. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  29171. this.open();
  29172. }
  29173. Socket.priorWebsocketSuccess = false;
  29174. /**
  29175. * Mix in `Emitter`.
  29176. */
  29177. Emitter(Socket.prototype);
  29178. /**
  29179. * Protocol version.
  29180. *
  29181. * @api public
  29182. */
  29183. Socket.protocol = parser.protocol; // this is an int
  29184. /**
  29185. * Expose deps for legacy compatibility
  29186. * and standalone browser access.
  29187. */
  29188. Socket.Socket = Socket;
  29189. Socket.Transport = require('./transport');
  29190. Socket.transports = require('./transports');
  29191. Socket.parser = require('engine.io-parser');
  29192. /**
  29193. * Creates transport of the given type.
  29194. *
  29195. * @param {String} transport name
  29196. * @return {Transport}
  29197. * @api private
  29198. */
  29199. Socket.prototype.createTransport = function (name) {
  29200. debug('creating transport "%s"', name);
  29201. var query = clone(this.query);
  29202. // append engine.io protocol identifier
  29203. query.EIO = parser.protocol;
  29204. // transport name
  29205. query.transport = name;
  29206. // session id if we already have one
  29207. if (this.id) query.sid = this.id;
  29208. var transport = new transports[name]({
  29209. agent: this.agent,
  29210. hostname: this.hostname,
  29211. port: this.port,
  29212. secure: this.secure,
  29213. path: this.path,
  29214. query: query,
  29215. forceJSONP: this.forceJSONP,
  29216. jsonp: this.jsonp,
  29217. forceBase64: this.forceBase64,
  29218. enablesXDR: this.enablesXDR,
  29219. timestampRequests: this.timestampRequests,
  29220. timestampParam: this.timestampParam,
  29221. policyPort: this.policyPort,
  29222. socket: this,
  29223. pfx: this.pfx,
  29224. key: this.key,
  29225. passphrase: this.passphrase,
  29226. cert: this.cert,
  29227. ca: this.ca,
  29228. ciphers: this.ciphers,
  29229. rejectUnauthorized: this.rejectUnauthorized
  29230. });
  29231. return transport;
  29232. };
  29233. function clone (obj) {
  29234. var o = {};
  29235. for (var i in obj) {
  29236. if (obj.hasOwnProperty(i)) {
  29237. o[i] = obj[i];
  29238. }
  29239. }
  29240. return o;
  29241. }
  29242. /**
  29243. * Initializes transport to use and starts probe.
  29244. *
  29245. * @api private
  29246. */
  29247. Socket.prototype.open = function () {
  29248. var transport;
  29249. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  29250. transport = 'websocket';
  29251. } else if (0 == this.transports.length) {
  29252. // Emit error on next tick so it can be listened to
  29253. var self = this;
  29254. setTimeout(function() {
  29255. self.emit('error', 'No transports available');
  29256. }, 0);
  29257. return;
  29258. } else {
  29259. transport = this.transports[0];
  29260. }
  29261. this.readyState = 'opening';
  29262. // Retry with the next transport if the transport is disabled (jsonp: false)
  29263. var transport;
  29264. try {
  29265. transport = this.createTransport(transport);
  29266. } catch (e) {
  29267. this.transports.shift();
  29268. this.open();
  29269. return;
  29270. }
  29271. transport.open();
  29272. this.setTransport(transport);
  29273. };
  29274. /**
  29275. * Sets the current transport. Disables the existing one (if any).
  29276. *
  29277. * @api private
  29278. */
  29279. Socket.prototype.setTransport = function(transport){
  29280. debug('setting transport %s', transport.name);
  29281. var self = this;
  29282. if (this.transport) {
  29283. debug('clearing existing transport %s', this.transport.name);
  29284. this.transport.removeAllListeners();
  29285. }
  29286. // set up transport
  29287. this.transport = transport;
  29288. // set up transport listeners
  29289. transport
  29290. .on('drain', function(){
  29291. self.onDrain();
  29292. })
  29293. .on('packet', function(packet){
  29294. self.onPacket(packet);
  29295. })
  29296. .on('error', function(e){
  29297. self.onError(e);
  29298. })
  29299. .on('close', function(){
  29300. self.onClose('transport close');
  29301. });
  29302. };
  29303. /**
  29304. * Probes a transport.
  29305. *
  29306. * @param {String} transport name
  29307. * @api private
  29308. */
  29309. Socket.prototype.probe = function (name) {
  29310. debug('probing transport "%s"', name);
  29311. var transport = this.createTransport(name, { probe: 1 })
  29312. , failed = false
  29313. , self = this;
  29314. Socket.priorWebsocketSuccess = false;
  29315. function onTransportOpen(){
  29316. if (self.onlyBinaryUpgrades) {
  29317. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  29318. failed = failed || upgradeLosesBinary;
  29319. }
  29320. if (failed) return;
  29321. debug('probe transport "%s" opened', name);
  29322. transport.send([{ type: 'ping', data: 'probe' }]);
  29323. transport.once('packet', function (msg) {
  29324. if (failed) return;
  29325. if ('pong' == msg.type && 'probe' == msg.data) {
  29326. debug('probe transport "%s" pong', name);
  29327. self.upgrading = true;
  29328. self.emit('upgrading', transport);
  29329. if (!transport) return;
  29330. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  29331. debug('pausing current transport "%s"', self.transport.name);
  29332. self.transport.pause(function () {
  29333. if (failed) return;
  29334. if ('closed' == self.readyState) return;
  29335. debug('changing transport and sending upgrade packet');
  29336. cleanup();
  29337. self.setTransport(transport);
  29338. transport.send([{ type: 'upgrade' }]);
  29339. self.emit('upgrade', transport);
  29340. transport = null;
  29341. self.upgrading = false;
  29342. self.flush();
  29343. });
  29344. } else {
  29345. debug('probe transport "%s" failed', name);
  29346. var err = new Error('probe error');
  29347. err.transport = transport.name;
  29348. self.emit('upgradeError', err);
  29349. }
  29350. });
  29351. }
  29352. function freezeTransport() {
  29353. if (failed) return;
  29354. // Any callback called by transport should be ignored since now
  29355. failed = true;
  29356. cleanup();
  29357. transport.close();
  29358. transport = null;
  29359. }
  29360. //Handle any error that happens while probing
  29361. function onerror(err) {
  29362. var error = new Error('probe error: ' + err);
  29363. error.transport = transport.name;
  29364. freezeTransport();
  29365. debug('probe transport "%s" failed because of error: %s', name, err);
  29366. self.emit('upgradeError', error);
  29367. }
  29368. function onTransportClose(){
  29369. onerror("transport closed");
  29370. }
  29371. //When the socket is closed while we're probing
  29372. function onclose(){
  29373. onerror("socket closed");
  29374. }
  29375. //When the socket is upgraded while we're probing
  29376. function onupgrade(to){
  29377. if (transport && to.name != transport.name) {
  29378. debug('"%s" works - aborting "%s"', to.name, transport.name);
  29379. freezeTransport();
  29380. }
  29381. }
  29382. //Remove all listeners on the transport and on self
  29383. function cleanup(){
  29384. transport.removeListener('open', onTransportOpen);
  29385. transport.removeListener('error', onerror);
  29386. transport.removeListener('close', onTransportClose);
  29387. self.removeListener('close', onclose);
  29388. self.removeListener('upgrading', onupgrade);
  29389. }
  29390. transport.once('open', onTransportOpen);
  29391. transport.once('error', onerror);
  29392. transport.once('close', onTransportClose);
  29393. this.once('close', onclose);
  29394. this.once('upgrading', onupgrade);
  29395. transport.open();
  29396. };
  29397. /**
  29398. * Called when connection is deemed open.
  29399. *
  29400. * @api public
  29401. */
  29402. Socket.prototype.onOpen = function () {
  29403. debug('socket open');
  29404. this.readyState = 'open';
  29405. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  29406. this.emit('open');
  29407. this.flush();
  29408. // we check for `readyState` in case an `open`
  29409. // listener already closed the socket
  29410. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  29411. debug('starting upgrade probes');
  29412. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  29413. this.probe(this.upgrades[i]);
  29414. }
  29415. }
  29416. };
  29417. /**
  29418. * Handles a packet.
  29419. *
  29420. * @api private
  29421. */
  29422. Socket.prototype.onPacket = function (packet) {
  29423. if ('opening' == this.readyState || 'open' == this.readyState) {
  29424. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  29425. this.emit('packet', packet);
  29426. // Socket is live - any packet counts
  29427. this.emit('heartbeat');
  29428. switch (packet.type) {
  29429. case 'open':
  29430. this.onHandshake(parsejson(packet.data));
  29431. break;
  29432. case 'pong':
  29433. this.setPing();
  29434. break;
  29435. case 'error':
  29436. var err = new Error('server error');
  29437. err.code = packet.data;
  29438. this.emit('error', err);
  29439. break;
  29440. case 'message':
  29441. this.emit('data', packet.data);
  29442. this.emit('message', packet.data);
  29443. break;
  29444. }
  29445. } else {
  29446. debug('packet received with socket readyState "%s"', this.readyState);
  29447. }
  29448. };
  29449. /**
  29450. * Called upon handshake completion.
  29451. *
  29452. * @param {Object} handshake obj
  29453. * @api private
  29454. */
  29455. Socket.prototype.onHandshake = function (data) {
  29456. this.emit('handshake', data);
  29457. this.id = data.sid;
  29458. this.transport.query.sid = data.sid;
  29459. this.upgrades = this.filterUpgrades(data.upgrades);
  29460. this.pingInterval = data.pingInterval;
  29461. this.pingTimeout = data.pingTimeout;
  29462. this.onOpen();
  29463. // In case open handler closes socket
  29464. if ('closed' == this.readyState) return;
  29465. this.setPing();
  29466. // Prolong liveness of socket on heartbeat
  29467. this.removeListener('heartbeat', this.onHeartbeat);
  29468. this.on('heartbeat', this.onHeartbeat);
  29469. };
  29470. /**
  29471. * Resets ping timeout.
  29472. *
  29473. * @api private
  29474. */
  29475. Socket.prototype.onHeartbeat = function (timeout) {
  29476. clearTimeout(this.pingTimeoutTimer);
  29477. var self = this;
  29478. self.pingTimeoutTimer = setTimeout(function () {
  29479. if ('closed' == self.readyState) return;
  29480. self.onClose('ping timeout');
  29481. }, timeout || (self.pingInterval + self.pingTimeout));
  29482. };
  29483. /**
  29484. * Pings server every `this.pingInterval` and expects response
  29485. * within `this.pingTimeout` or closes connection.
  29486. *
  29487. * @api private
  29488. */
  29489. Socket.prototype.setPing = function () {
  29490. var self = this;
  29491. clearTimeout(self.pingIntervalTimer);
  29492. self.pingIntervalTimer = setTimeout(function () {
  29493. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  29494. self.ping();
  29495. self.onHeartbeat(self.pingTimeout);
  29496. }, self.pingInterval);
  29497. };
  29498. /**
  29499. * Sends a ping packet.
  29500. *
  29501. * @api public
  29502. */
  29503. Socket.prototype.ping = function () {
  29504. this.sendPacket('ping');
  29505. };
  29506. /**
  29507. * Called on `drain` event
  29508. *
  29509. * @api private
  29510. */
  29511. Socket.prototype.onDrain = function() {
  29512. for (var i = 0; i < this.prevBufferLen; i++) {
  29513. if (this.callbackBuffer[i]) {
  29514. this.callbackBuffer[i]();
  29515. }
  29516. }
  29517. this.writeBuffer.splice(0, this.prevBufferLen);
  29518. this.callbackBuffer.splice(0, this.prevBufferLen);
  29519. // setting prevBufferLen = 0 is very important
  29520. // for example, when upgrading, upgrade packet is sent over,
  29521. // and a nonzero prevBufferLen could cause problems on `drain`
  29522. this.prevBufferLen = 0;
  29523. if (this.writeBuffer.length == 0) {
  29524. this.emit('drain');
  29525. } else {
  29526. this.flush();
  29527. }
  29528. };
  29529. /**
  29530. * Flush write buffers.
  29531. *
  29532. * @api private
  29533. */
  29534. Socket.prototype.flush = function () {
  29535. if ('closed' != this.readyState && this.transport.writable &&
  29536. !this.upgrading && this.writeBuffer.length) {
  29537. debug('flushing %d packets in socket', this.writeBuffer.length);
  29538. this.transport.send(this.writeBuffer);
  29539. // keep track of current length of writeBuffer
  29540. // splice writeBuffer and callbackBuffer on `drain`
  29541. this.prevBufferLen = this.writeBuffer.length;
  29542. this.emit('flush');
  29543. }
  29544. };
  29545. /**
  29546. * Sends a message.
  29547. *
  29548. * @param {String} message.
  29549. * @param {Function} callback function.
  29550. * @return {Socket} for chaining.
  29551. * @api public
  29552. */
  29553. Socket.prototype.write =
  29554. Socket.prototype.send = function (msg, fn) {
  29555. this.sendPacket('message', msg, fn);
  29556. return this;
  29557. };
  29558. /**
  29559. * Sends a packet.
  29560. *
  29561. * @param {String} packet type.
  29562. * @param {String} data.
  29563. * @param {Function} callback function.
  29564. * @api private
  29565. */
  29566. Socket.prototype.sendPacket = function (type, data, fn) {
  29567. if ('closing' == this.readyState || 'closed' == this.readyState) {
  29568. return;
  29569. }
  29570. var packet = { type: type, data: data };
  29571. this.emit('packetCreate', packet);
  29572. this.writeBuffer.push(packet);
  29573. this.callbackBuffer.push(fn);
  29574. this.flush();
  29575. };
  29576. /**
  29577. * Closes the connection.
  29578. *
  29579. * @api private
  29580. */
  29581. Socket.prototype.close = function () {
  29582. if ('opening' == this.readyState || 'open' == this.readyState) {
  29583. this.readyState = 'closing';
  29584. var self = this;
  29585. function close() {
  29586. self.onClose('forced close');
  29587. debug('socket closing - telling transport to close');
  29588. self.transport.close();
  29589. }
  29590. function cleanupAndClose() {
  29591. self.removeListener('upgrade', cleanupAndClose);
  29592. self.removeListener('upgradeError', cleanupAndClose);
  29593. close();
  29594. }
  29595. function waitForUpgrade() {
  29596. // wait for upgrade to finish since we can't send packets while pausing a transport
  29597. self.once('upgrade', cleanupAndClose);
  29598. self.once('upgradeError', cleanupAndClose);
  29599. }
  29600. if (this.writeBuffer.length) {
  29601. this.once('drain', function() {
  29602. if (this.upgrading) {
  29603. waitForUpgrade();
  29604. } else {
  29605. close();
  29606. }
  29607. });
  29608. } else if (this.upgrading) {
  29609. waitForUpgrade();
  29610. } else {
  29611. close();
  29612. }
  29613. }
  29614. return this;
  29615. };
  29616. /**
  29617. * Called upon transport error
  29618. *
  29619. * @api private
  29620. */
  29621. Socket.prototype.onError = function (err) {
  29622. debug('socket error %j', err);
  29623. Socket.priorWebsocketSuccess = false;
  29624. this.emit('error', err);
  29625. this.onClose('transport error', err);
  29626. };
  29627. /**
  29628. * Called upon transport close.
  29629. *
  29630. * @api private
  29631. */
  29632. Socket.prototype.onClose = function (reason, desc) {
  29633. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  29634. debug('socket close with reason: "%s"', reason);
  29635. var self = this;
  29636. // clear timers
  29637. clearTimeout(this.pingIntervalTimer);
  29638. clearTimeout(this.pingTimeoutTimer);
  29639. // clean buffers in next tick, so developers can still
  29640. // grab the buffers on `close` event
  29641. setTimeout(function() {
  29642. self.writeBuffer = [];
  29643. self.callbackBuffer = [];
  29644. self.prevBufferLen = 0;
  29645. }, 0);
  29646. // stop event from firing again for transport
  29647. this.transport.removeAllListeners('close');
  29648. // ensure transport won't stay open
  29649. this.transport.close();
  29650. // ignore further transport communication
  29651. this.transport.removeAllListeners();
  29652. // set ready state
  29653. this.readyState = 'closed';
  29654. // clear session id
  29655. this.id = null;
  29656. // emit close event
  29657. this.emit('close', reason, desc);
  29658. }
  29659. };
  29660. /**
  29661. * Filters upgrades, returning only those matching client transports.
  29662. *
  29663. * @param {Array} server upgrades
  29664. * @api private
  29665. *
  29666. */
  29667. Socket.prototype.filterUpgrades = function (upgrades) {
  29668. var filteredUpgrades = [];
  29669. for (var i = 0, j = upgrades.length; i<j; i++) {
  29670. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  29671. }
  29672. return filteredUpgrades;
  29673. };
  29674. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29675. },{"./transport":127,"./transports":128,"component-emitter":122,"debug":135,"engine.io-parser":138,"indexof":155,"parsejson":149,"parseqs":150,"parseuri":151}],127:[function(require,module,exports){
  29676. /**
  29677. * Module dependencies.
  29678. */
  29679. var parser = require('engine.io-parser');
  29680. var Emitter = require('component-emitter');
  29681. /**
  29682. * Module exports.
  29683. */
  29684. module.exports = Transport;
  29685. /**
  29686. * Transport abstract constructor.
  29687. *
  29688. * @param {Object} options.
  29689. * @api private
  29690. */
  29691. function Transport (opts) {
  29692. this.path = opts.path;
  29693. this.hostname = opts.hostname;
  29694. this.port = opts.port;
  29695. this.secure = opts.secure;
  29696. this.query = opts.query;
  29697. this.timestampParam = opts.timestampParam;
  29698. this.timestampRequests = opts.timestampRequests;
  29699. this.readyState = '';
  29700. this.agent = opts.agent || false;
  29701. this.socket = opts.socket;
  29702. this.enablesXDR = opts.enablesXDR;
  29703. // SSL options for Node.js client
  29704. this.pfx = opts.pfx;
  29705. this.key = opts.key;
  29706. this.passphrase = opts.passphrase;
  29707. this.cert = opts.cert;
  29708. this.ca = opts.ca;
  29709. this.ciphers = opts.ciphers;
  29710. this.rejectUnauthorized = opts.rejectUnauthorized;
  29711. }
  29712. /**
  29713. * Mix in `Emitter`.
  29714. */
  29715. Emitter(Transport.prototype);
  29716. /**
  29717. * A counter used to prevent collisions in the timestamps used
  29718. * for cache busting.
  29719. */
  29720. Transport.timestamps = 0;
  29721. /**
  29722. * Emits an error.
  29723. *
  29724. * @param {String} str
  29725. * @return {Transport} for chaining
  29726. * @api public
  29727. */
  29728. Transport.prototype.onError = function (msg, desc) {
  29729. var err = new Error(msg);
  29730. err.type = 'TransportError';
  29731. err.description = desc;
  29732. this.emit('error', err);
  29733. return this;
  29734. };
  29735. /**
  29736. * Opens the transport.
  29737. *
  29738. * @api public
  29739. */
  29740. Transport.prototype.open = function () {
  29741. if ('closed' == this.readyState || '' == this.readyState) {
  29742. this.readyState = 'opening';
  29743. this.doOpen();
  29744. }
  29745. return this;
  29746. };
  29747. /**
  29748. * Closes the transport.
  29749. *
  29750. * @api private
  29751. */
  29752. Transport.prototype.close = function () {
  29753. if ('opening' == this.readyState || 'open' == this.readyState) {
  29754. this.doClose();
  29755. this.onClose();
  29756. }
  29757. return this;
  29758. };
  29759. /**
  29760. * Sends multiple packets.
  29761. *
  29762. * @param {Array} packets
  29763. * @api private
  29764. */
  29765. Transport.prototype.send = function(packets){
  29766. if ('open' == this.readyState) {
  29767. this.write(packets);
  29768. } else {
  29769. throw new Error('Transport not open');
  29770. }
  29771. };
  29772. /**
  29773. * Called upon open
  29774. *
  29775. * @api private
  29776. */
  29777. Transport.prototype.onOpen = function () {
  29778. this.readyState = 'open';
  29779. this.writable = true;
  29780. this.emit('open');
  29781. };
  29782. /**
  29783. * Called with data.
  29784. *
  29785. * @param {String} data
  29786. * @api private
  29787. */
  29788. Transport.prototype.onData = function(data){
  29789. var packet = parser.decodePacket(data, this.socket.binaryType);
  29790. this.onPacket(packet);
  29791. };
  29792. /**
  29793. * Called with a decoded packet.
  29794. */
  29795. Transport.prototype.onPacket = function (packet) {
  29796. this.emit('packet', packet);
  29797. };
  29798. /**
  29799. * Called upon close.
  29800. *
  29801. * @api private
  29802. */
  29803. Transport.prototype.onClose = function () {
  29804. this.readyState = 'closed';
  29805. this.emit('close');
  29806. };
  29807. },{"component-emitter":122,"engine.io-parser":138}],128:[function(require,module,exports){
  29808. (function (global){
  29809. /**
  29810. * Module dependencies
  29811. */
  29812. var XMLHttpRequest = require('xmlhttprequest');
  29813. var XHR = require('./polling-xhr');
  29814. var JSONP = require('./polling-jsonp');
  29815. var websocket = require('./websocket');
  29816. /**
  29817. * Export transports.
  29818. */
  29819. exports.polling = polling;
  29820. exports.websocket = websocket;
  29821. /**
  29822. * Polling transport polymorphic constructor.
  29823. * Decides on xhr vs jsonp based on feature detection.
  29824. *
  29825. * @api private
  29826. */
  29827. function polling(opts){
  29828. var xhr;
  29829. var xd = false;
  29830. var xs = false;
  29831. var jsonp = false !== opts.jsonp;
  29832. if (global.location) {
  29833. var isSSL = 'https:' == location.protocol;
  29834. var port = location.port;
  29835. // some user agents have empty `location.port`
  29836. if (!port) {
  29837. port = isSSL ? 443 : 80;
  29838. }
  29839. xd = opts.hostname != location.hostname || port != opts.port;
  29840. xs = opts.secure != isSSL;
  29841. }
  29842. opts.xdomain = xd;
  29843. opts.xscheme = xs;
  29844. xhr = new XMLHttpRequest(opts);
  29845. if ('open' in xhr && !opts.forceJSONP) {
  29846. return new XHR(opts);
  29847. } else {
  29848. if (!jsonp) throw new Error('JSONP disabled');
  29849. return new JSONP(opts);
  29850. }
  29851. }
  29852. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29853. },{"./polling-jsonp":129,"./polling-xhr":130,"./websocket":132,"xmlhttprequest":133}],129:[function(require,module,exports){
  29854. (function (global){
  29855. /**
  29856. * Module requirements.
  29857. */
  29858. var Polling = require('./polling');
  29859. var inherit = require('component-inherit');
  29860. /**
  29861. * Module exports.
  29862. */
  29863. module.exports = JSONPPolling;
  29864. /**
  29865. * Cached regular expressions.
  29866. */
  29867. var rNewline = /\n/g;
  29868. var rEscapedNewline = /\\n/g;
  29869. /**
  29870. * Global JSONP callbacks.
  29871. */
  29872. var callbacks;
  29873. /**
  29874. * Callbacks count.
  29875. */
  29876. var index = 0;
  29877. /**
  29878. * Noop.
  29879. */
  29880. function empty () { }
  29881. /**
  29882. * JSONP Polling constructor.
  29883. *
  29884. * @param {Object} opts.
  29885. * @api public
  29886. */
  29887. function JSONPPolling (opts) {
  29888. Polling.call(this, opts);
  29889. this.query = this.query || {};
  29890. // define global callbacks array if not present
  29891. // we do this here (lazily) to avoid unneeded global pollution
  29892. if (!callbacks) {
  29893. // we need to consider multiple engines in the same page
  29894. if (!global.___eio) global.___eio = [];
  29895. callbacks = global.___eio;
  29896. }
  29897. // callback identifier
  29898. this.index = callbacks.length;
  29899. // add callback to jsonp global
  29900. var self = this;
  29901. callbacks.push(function (msg) {
  29902. self.onData(msg);
  29903. });
  29904. // append to query string
  29905. this.query.j = this.index;
  29906. // prevent spurious errors from being emitted when the window is unloaded
  29907. if (global.document && global.addEventListener) {
  29908. global.addEventListener('beforeunload', function () {
  29909. if (self.script) self.script.onerror = empty;
  29910. }, false);
  29911. }
  29912. }
  29913. /**
  29914. * Inherits from Polling.
  29915. */
  29916. inherit(JSONPPolling, Polling);
  29917. /*
  29918. * JSONP only supports binary as base64 encoded strings
  29919. */
  29920. JSONPPolling.prototype.supportsBinary = false;
  29921. /**
  29922. * Closes the socket.
  29923. *
  29924. * @api private
  29925. */
  29926. JSONPPolling.prototype.doClose = function () {
  29927. if (this.script) {
  29928. this.script.parentNode.removeChild(this.script);
  29929. this.script = null;
  29930. }
  29931. if (this.form) {
  29932. this.form.parentNode.removeChild(this.form);
  29933. this.form = null;
  29934. this.iframe = null;
  29935. }
  29936. Polling.prototype.doClose.call(this);
  29937. };
  29938. /**
  29939. * Starts a poll cycle.
  29940. *
  29941. * @api private
  29942. */
  29943. JSONPPolling.prototype.doPoll = function () {
  29944. var self = this;
  29945. var script = document.createElement('script');
  29946. if (this.script) {
  29947. this.script.parentNode.removeChild(this.script);
  29948. this.script = null;
  29949. }
  29950. script.async = true;
  29951. script.src = this.uri();
  29952. script.onerror = function(e){
  29953. self.onError('jsonp poll error',e);
  29954. };
  29955. var insertAt = document.getElementsByTagName('script')[0];
  29956. insertAt.parentNode.insertBefore(script, insertAt);
  29957. this.script = script;
  29958. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  29959. if (isUAgecko) {
  29960. setTimeout(function () {
  29961. var iframe = document.createElement('iframe');
  29962. document.body.appendChild(iframe);
  29963. document.body.removeChild(iframe);
  29964. }, 100);
  29965. }
  29966. };
  29967. /**
  29968. * Writes with a hidden iframe.
  29969. *
  29970. * @param {String} data to send
  29971. * @param {Function} called upon flush.
  29972. * @api private
  29973. */
  29974. JSONPPolling.prototype.doWrite = function (data, fn) {
  29975. var self = this;
  29976. if (!this.form) {
  29977. var form = document.createElement('form');
  29978. var area = document.createElement('textarea');
  29979. var id = this.iframeId = 'eio_iframe_' + this.index;
  29980. var iframe;
  29981. form.className = 'socketio';
  29982. form.style.position = 'absolute';
  29983. form.style.top = '-1000px';
  29984. form.style.left = '-1000px';
  29985. form.target = id;
  29986. form.method = 'POST';
  29987. form.setAttribute('accept-charset', 'utf-8');
  29988. area.name = 'd';
  29989. form.appendChild(area);
  29990. document.body.appendChild(form);
  29991. this.form = form;
  29992. this.area = area;
  29993. }
  29994. this.form.action = this.uri();
  29995. function complete () {
  29996. initIframe();
  29997. fn();
  29998. }
  29999. function initIframe () {
  30000. if (self.iframe) {
  30001. try {
  30002. self.form.removeChild(self.iframe);
  30003. } catch (e) {
  30004. self.onError('jsonp polling iframe removal error', e);
  30005. }
  30006. }
  30007. try {
  30008. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  30009. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  30010. iframe = document.createElement(html);
  30011. } catch (e) {
  30012. iframe = document.createElement('iframe');
  30013. iframe.name = self.iframeId;
  30014. iframe.src = 'javascript:0';
  30015. }
  30016. iframe.id = self.iframeId;
  30017. self.form.appendChild(iframe);
  30018. self.iframe = iframe;
  30019. }
  30020. initIframe();
  30021. // escape \n to prevent it from being converted into \r\n by some UAs
  30022. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  30023. data = data.replace(rEscapedNewline, '\\\n');
  30024. this.area.value = data.replace(rNewline, '\\n');
  30025. try {
  30026. this.form.submit();
  30027. } catch(e) {}
  30028. if (this.iframe.attachEvent) {
  30029. this.iframe.onreadystatechange = function(){
  30030. if (self.iframe.readyState == 'complete') {
  30031. complete();
  30032. }
  30033. };
  30034. } else {
  30035. this.iframe.onload = complete;
  30036. }
  30037. };
  30038. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  30039. },{"./polling":131,"component-inherit":134}],130:[function(require,module,exports){
  30040. (function (global){
  30041. /**
  30042. * Module requirements.
  30043. */
  30044. var XMLHttpRequest = require('xmlhttprequest');
  30045. var Polling = require('./polling');
  30046. var Emitter = require('component-emitter');
  30047. var inherit = require('component-inherit');
  30048. var debug = require('debug')('engine.io-client:polling-xhr');
  30049. /**
  30050. * Module exports.
  30051. */
  30052. module.exports = XHR;
  30053. module.exports.Request = Request;
  30054. /**
  30055. * Empty function
  30056. */
  30057. function empty(){}
  30058. /**
  30059. * XHR Polling constructor.
  30060. *
  30061. * @param {Object} opts
  30062. * @api public
  30063. */
  30064. function XHR(opts){
  30065. Polling.call(this, opts);
  30066. if (global.location) {
  30067. var isSSL = 'https:' == location.protocol;
  30068. var port = location.port;
  30069. // some user agents have empty `location.port`
  30070. if (!port) {
  30071. port = isSSL ? 443 : 80;
  30072. }
  30073. this.xd = opts.hostname != global.location.hostname ||
  30074. port != opts.port;
  30075. this.xs = opts.secure != isSSL;
  30076. }
  30077. }
  30078. /**
  30079. * Inherits from Polling.
  30080. */
  30081. inherit(XHR, Polling);
  30082. /**
  30083. * XHR supports binary
  30084. */
  30085. XHR.prototype.supportsBinary = true;
  30086. /**
  30087. * Creates a request.
  30088. *
  30089. * @param {String} method
  30090. * @api private
  30091. */
  30092. XHR.prototype.request = function(opts){
  30093. opts = opts || {};
  30094. opts.uri = this.uri();
  30095. opts.xd = this.xd;
  30096. opts.xs = this.xs;
  30097. opts.agent = this.agent || false;
  30098. opts.supportsBinary = this.supportsBinary;
  30099. opts.enablesXDR = this.enablesXDR;
  30100. // SSL options for Node.js client
  30101. opts.pfx = this.pfx;
  30102. opts.key = this.key;
  30103. opts.passphrase = this.passphrase;
  30104. opts.cert = this.cert;
  30105. opts.ca = this.ca;
  30106. opts.ciphers = this.ciphers;
  30107. opts.rejectUnauthorized = this.rejectUnauthorized;
  30108. return new Request(opts);
  30109. };
  30110. /**
  30111. * Sends data.
  30112. *
  30113. * @param {String} data to send.
  30114. * @param {Function} called upon flush.
  30115. * @api private
  30116. */
  30117. XHR.prototype.doWrite = function(data, fn){
  30118. var isBinary = typeof data !== 'string' && data !== undefined;
  30119. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  30120. var self = this;
  30121. req.on('success', fn);
  30122. req.on('error', function(err){
  30123. self.onError('xhr post error', err);
  30124. });
  30125. this.sendXhr = req;
  30126. };
  30127. /**
  30128. * Starts a poll cycle.
  30129. *
  30130. * @api private
  30131. */
  30132. XHR.prototype.doPoll = function(){
  30133. debug('xhr poll');
  30134. var req = this.request();
  30135. var self = this;
  30136. req.on('data', function(data){
  30137. self.onData(data);
  30138. });
  30139. req.on('error', function(err){
  30140. self.onError('xhr poll error', err);
  30141. });
  30142. this.pollXhr = req;
  30143. };
  30144. /**
  30145. * Request constructor
  30146. *
  30147. * @param {Object} options
  30148. * @api public
  30149. */
  30150. function Request(opts){
  30151. this.method = opts.method || 'GET';
  30152. this.uri = opts.uri;
  30153. this.xd = !!opts.xd;
  30154. this.xs = !!opts.xs;
  30155. this.async = false !== opts.async;
  30156. this.data = undefined != opts.data ? opts.data : null;
  30157. this.agent = opts.agent;
  30158. this.isBinary = opts.isBinary;
  30159. this.supportsBinary = opts.supportsBinary;
  30160. this.enablesXDR = opts.enablesXDR;
  30161. // SSL options for Node.js client
  30162. this.pfx = opts.pfx;
  30163. this.key = opts.key;
  30164. this.passphrase = opts.passphrase;
  30165. this.cert = opts.cert;
  30166. this.ca = opts.ca;
  30167. this.ciphers = opts.ciphers;
  30168. this.rejectUnauthorized = opts.rejectUnauthorized;
  30169. this.create();
  30170. }
  30171. /**
  30172. * Mix in `Emitter`.
  30173. */
  30174. Emitter(Request.prototype);
  30175. /**
  30176. * Creates the XHR object and sends the request.
  30177. *
  30178. * @api private
  30179. */
  30180. Request.prototype.create = function(){
  30181. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  30182. // SSL options for Node.js client
  30183. opts.pfx = this.pfx;
  30184. opts.key = this.key;
  30185. opts.passphrase = this.passphrase;
  30186. opts.cert = this.cert;
  30187. opts.ca = this.ca;
  30188. opts.ciphers = this.ciphers;
  30189. opts.rejectUnauthorized = this.rejectUnauthorized;
  30190. var xhr = this.xhr = new XMLHttpRequest(opts);
  30191. var self = this;
  30192. try {
  30193. debug('xhr open %s: %s', this.method, this.uri);
  30194. xhr.open(this.method, this.uri, this.async);
  30195. if (this.supportsBinary) {
  30196. // This has to be done after open because Firefox is stupid
  30197. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  30198. xhr.responseType = 'arraybuffer';
  30199. }
  30200. if ('POST' == this.method) {
  30201. try {
  30202. if (this.isBinary) {
  30203. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  30204. } else {
  30205. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  30206. }
  30207. } catch (e) {}
  30208. }
  30209. // ie6 check
  30210. if ('withCredentials' in xhr) {
  30211. xhr.withCredentials = true;
  30212. }
  30213. if (this.hasXDR()) {
  30214. xhr.onload = function(){
  30215. self.onLoad();
  30216. };
  30217. xhr.onerror = function(){
  30218. self.onError(xhr.responseText);
  30219. };
  30220. } else {
  30221. xhr.onreadystatechange = function(){
  30222. if (4 != xhr.readyState) return;
  30223. if (200 == xhr.status || 1223 == xhr.status) {
  30224. self.onLoad();
  30225. } else {
  30226. // make sure the `error` event handler that's user-set
  30227. // does not throw in the same tick and gets caught here
  30228. setTimeout(function(){
  30229. self.onError(xhr.status);
  30230. }, 0);
  30231. }
  30232. };
  30233. }
  30234. debug('xhr data %s', this.data);
  30235. xhr.send(this.data);
  30236. } catch (e) {
  30237. // Need to defer since .create() is called directly fhrom the constructor
  30238. // and thus the 'error' event can only be only bound *after* this exception
  30239. // occurs. Therefore, also, we cannot throw here at all.
  30240. setTimeout(function() {
  30241. self.onError(e);
  30242. }, 0);
  30243. return;
  30244. }
  30245. if (global.document) {
  30246. this.index = Request.requestsCount++;
  30247. Request.requests[this.index] = this;
  30248. }
  30249. };
  30250. /**
  30251. * Called upon successful response.
  30252. *
  30253. * @api private
  30254. */
  30255. Request.prototype.onSuccess = function(){
  30256. this.emit('success');
  30257. this.cleanup();
  30258. };
  30259. /**
  30260. * Called if we have data.
  30261. *
  30262. * @api private
  30263. */
  30264. Request.prototype.onData = function(data){
  30265. this.emit('data', data);
  30266. this.onSuccess();
  30267. };
  30268. /**
  30269. * Called upon error.
  30270. *
  30271. * @api private
  30272. */
  30273. Request.prototype.onError = function(err){
  30274. this.emit('error', err);
  30275. this.cleanup(true);
  30276. };
  30277. /**
  30278. * Cleans up house.
  30279. *
  30280. * @api private
  30281. */
  30282. Request.prototype.cleanup = function(fromError){
  30283. if ('undefined' == typeof this.xhr || null === this.xhr) {
  30284. return;
  30285. }
  30286. // xmlhttprequest
  30287. if (this.hasXDR()) {
  30288. this.xhr.onload = this.xhr.onerror = empty;
  30289. } else {
  30290. this.xhr.onreadystatechange = empty;
  30291. }
  30292. if (fromError) {
  30293. try {
  30294. this.xhr.abort();
  30295. } catch(e) {}
  30296. }
  30297. if (global.document) {
  30298. delete Request.requests[this.index];
  30299. }
  30300. this.xhr = null;
  30301. };
  30302. /**
  30303. * Called upon load.
  30304. *
  30305. * @api private
  30306. */
  30307. Request.prototype.onLoad = function(){
  30308. var data;
  30309. try {
  30310. var contentType;
  30311. try {
  30312. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  30313. } catch (e) {}
  30314. if (contentType === 'application/octet-stream') {
  30315. data = this.xhr.response;
  30316. } else {
  30317. if (!this.supportsBinary) {
  30318. data = this.xhr.responseText;
  30319. } else {
  30320. data = 'ok';
  30321. }
  30322. }
  30323. } catch (e) {
  30324. this.onError(e);
  30325. }
  30326. if (null != data) {
  30327. this.onData(data);
  30328. }
  30329. };
  30330. /**
  30331. * Check if it has XDomainRequest.
  30332. *
  30333. * @api private
  30334. */
  30335. Request.prototype.hasXDR = function(){
  30336. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  30337. };
  30338. /**
  30339. * Aborts the request.
  30340. *
  30341. * @api public
  30342. */
  30343. Request.prototype.abort = function(){
  30344. this.cleanup();
  30345. };
  30346. /**
  30347. * Aborts pending requests when unloading the window. This is needed to prevent
  30348. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  30349. * emitted.
  30350. */
  30351. if (global.document) {
  30352. Request.requestsCount = 0;
  30353. Request.requests = {};
  30354. if (global.attachEvent) {
  30355. global.attachEvent('onunload', unloadHandler);
  30356. } else if (global.addEventListener) {
  30357. global.addEventListener('beforeunload', unloadHandler, false);
  30358. }
  30359. }
  30360. function unloadHandler() {
  30361. for (var i in Request.requests) {
  30362. if (Request.requests.hasOwnProperty(i)) {
  30363. Request.requests[i].abort();
  30364. }
  30365. }
  30366. }
  30367. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  30368. },{"./polling":131,"component-emitter":122,"component-inherit":134,"debug":135,"xmlhttprequest":133}],131:[function(require,module,exports){
  30369. /**
  30370. * Module dependencies.
  30371. */
  30372. var Transport = require('../transport');
  30373. var parseqs = require('parseqs');
  30374. var parser = require('engine.io-parser');
  30375. var inherit = require('component-inherit');
  30376. var debug = require('debug')('engine.io-client:polling');
  30377. /**
  30378. * Module exports.
  30379. */
  30380. module.exports = Polling;
  30381. /**
  30382. * Is XHR2 supported?
  30383. */
  30384. var hasXHR2 = (function() {
  30385. var XMLHttpRequest = require('xmlhttprequest');
  30386. var xhr = new XMLHttpRequest({ xdomain: false });
  30387. return null != xhr.responseType;
  30388. })();
  30389. /**
  30390. * Polling interface.
  30391. *
  30392. * @param {Object} opts
  30393. * @api private
  30394. */
  30395. function Polling(opts){
  30396. var forceBase64 = (opts && opts.forceBase64);
  30397. if (!hasXHR2 || forceBase64) {
  30398. this.supportsBinary = false;
  30399. }
  30400. Transport.call(this, opts);
  30401. }
  30402. /**
  30403. * Inherits from Transport.
  30404. */
  30405. inherit(Polling, Transport);
  30406. /**
  30407. * Transport name.
  30408. */
  30409. Polling.prototype.name = 'polling';
  30410. /**
  30411. * Opens the socket (triggers polling). We write a PING message to determine
  30412. * when the transport is open.
  30413. *
  30414. * @api private
  30415. */
  30416. Polling.prototype.doOpen = function(){
  30417. this.poll();
  30418. };
  30419. /**
  30420. * Pauses polling.
  30421. *
  30422. * @param {Function} callback upon buffers are flushed and transport is paused
  30423. * @api private
  30424. */
  30425. Polling.prototype.pause = function(onPause){
  30426. var pending = 0;
  30427. var self = this;
  30428. this.readyState = 'pausing';
  30429. function pause(){
  30430. debug('paused');
  30431. self.readyState = 'paused';
  30432. onPause();
  30433. }
  30434. if (this.polling || !this.writable) {
  30435. var total = 0;
  30436. if (this.polling) {
  30437. debug('we are currently polling - waiting to pause');
  30438. total++;
  30439. this.once('pollComplete', function(){
  30440. debug('pre-pause polling complete');
  30441. --total || pause();
  30442. });
  30443. }
  30444. if (!this.writable) {
  30445. debug('we are currently writing - waiting to pause');
  30446. total++;
  30447. this.once('drain', function(){
  30448. debug('pre-pause writing complete');
  30449. --total || pause();
  30450. });
  30451. }
  30452. } else {
  30453. pause();
  30454. }
  30455. };
  30456. /**
  30457. * Starts polling cycle.
  30458. *
  30459. * @api public
  30460. */
  30461. Polling.prototype.poll = function(){
  30462. debug('polling');
  30463. this.polling = true;
  30464. this.doPoll();
  30465. this.emit('poll');
  30466. };
  30467. /**
  30468. * Overloads onData to detect payloads.
  30469. *
  30470. * @api private
  30471. */
  30472. Polling.prototype.onData = function(data){
  30473. var self = this;
  30474. debug('polling got data %s', data);
  30475. var callback = function(packet, index, total) {
  30476. // if its the first message we consider the transport open
  30477. if ('opening' == self.readyState) {
  30478. self.onOpen();
  30479. }
  30480. // if its a close packet, we close the ongoing requests
  30481. if ('close' == packet.type) {
  30482. self.onClose();
  30483. return false;
  30484. }
  30485. // otherwise bypass onData and handle the message
  30486. self.onPacket(packet);
  30487. };
  30488. // decode payload
  30489. parser.decodePayload(data, this.socket.binaryType, callback);
  30490. // if an event did not trigger closing
  30491. if ('closed' != this.readyState) {
  30492. // if we got data we're not polling
  30493. this.polling = false;
  30494. this.emit('pollComplete');
  30495. if ('open' == this.readyState) {
  30496. this.poll();
  30497. } else {
  30498. debug('ignoring poll - transport state "%s"', this.readyState);
  30499. }
  30500. }
  30501. };
  30502. /**
  30503. * For polling, send a close packet.
  30504. *
  30505. * @api private
  30506. */
  30507. Polling.prototype.doClose = function(){
  30508. var self = this;
  30509. function close(){
  30510. debug('writing close packet');
  30511. self.write([{ type: 'close' }]);
  30512. }
  30513. if ('open' == this.readyState) {
  30514. debug('transport open - closing');
  30515. close();
  30516. } else {
  30517. // in case we're trying to close while
  30518. // handshaking is in progress (GH-164)
  30519. debug('transport not open - deferring close');
  30520. this.once('open', close);
  30521. }
  30522. };
  30523. /**
  30524. * Writes a packets payload.
  30525. *
  30526. * @param {Array} data packets
  30527. * @param {Function} drain callback
  30528. * @api private
  30529. */
  30530. Polling.prototype.write = function(packets){
  30531. var self = this;
  30532. this.writable = false;
  30533. var callbackfn = function() {
  30534. self.writable = true;
  30535. self.emit('drain');
  30536. };
  30537. var self = this;
  30538. parser.encodePayload(packets, this.supportsBinary, function(data) {
  30539. self.doWrite(data, callbackfn);
  30540. });
  30541. };
  30542. /**
  30543. * Generates uri for connection.
  30544. *
  30545. * @api private
  30546. */
  30547. Polling.prototype.uri = function(){
  30548. var query = this.query || {};
  30549. var schema = this.secure ? 'https' : 'http';
  30550. var port = '';
  30551. // cache busting is forced
  30552. if (false !== this.timestampRequests) {
  30553. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  30554. }
  30555. if (!this.supportsBinary && !query.sid) {
  30556. query.b64 = 1;
  30557. }
  30558. query = parseqs.encode(query);
  30559. // avoid port if default for schema
  30560. if (this.port && (('https' == schema && this.port != 443) ||
  30561. ('http' == schema && this.port != 80))) {
  30562. port = ':' + this.port;
  30563. }
  30564. // prepend ? to query
  30565. if (query.length) {
  30566. query = '?' + query;
  30567. }
  30568. return schema + '://' + this.hostname + port + this.path + query;
  30569. };
  30570. },{"../transport":127,"component-inherit":134,"debug":135,"engine.io-parser":138,"parseqs":150,"xmlhttprequest":133}],132:[function(require,module,exports){
  30571. /**
  30572. * Module dependencies.
  30573. */
  30574. var Transport = require('../transport');
  30575. var parser = require('engine.io-parser');
  30576. var parseqs = require('parseqs');
  30577. var inherit = require('component-inherit');
  30578. var debug = require('debug')('engine.io-client:websocket');
  30579. /**
  30580. * `ws` exposes a WebSocket-compatible interface in
  30581. * Node, or the `WebSocket` or `MozWebSocket` globals
  30582. * in the browser.
  30583. */
  30584. var WebSocket = require('ws');
  30585. /**
  30586. * Module exports.
  30587. */
  30588. module.exports = WS;
  30589. /**
  30590. * WebSocket transport constructor.
  30591. *
  30592. * @api {Object} connection options
  30593. * @api public
  30594. */
  30595. function WS(opts){
  30596. var forceBase64 = (opts && opts.forceBase64);
  30597. if (forceBase64) {
  30598. this.supportsBinary = false;
  30599. }
  30600. Transport.call(this, opts);
  30601. }
  30602. /**
  30603. * Inherits from Transport.
  30604. */
  30605. inherit(WS, Transport);
  30606. /**
  30607. * Transport name.
  30608. *
  30609. * @api public
  30610. */
  30611. WS.prototype.name = 'websocket';
  30612. /*
  30613. * WebSockets support binary
  30614. */
  30615. WS.prototype.supportsBinary = true;
  30616. /**
  30617. * Opens socket.
  30618. *
  30619. * @api private
  30620. */
  30621. WS.prototype.doOpen = function(){
  30622. if (!this.check()) {
  30623. // let probe timeout
  30624. return;
  30625. }
  30626. var self = this;
  30627. var uri = this.uri();
  30628. var protocols = void(0);
  30629. var opts = { agent: this.agent };
  30630. // SSL options for Node.js client
  30631. opts.pfx = this.pfx;
  30632. opts.key = this.key;
  30633. opts.passphrase = this.passphrase;
  30634. opts.cert = this.cert;
  30635. opts.ca = this.ca;
  30636. opts.ciphers = this.ciphers;
  30637. opts.rejectUnauthorized = this.rejectUnauthorized;
  30638. this.ws = new WebSocket(uri, protocols, opts);
  30639. if (this.ws.binaryType === undefined) {
  30640. this.supportsBinary = false;
  30641. }
  30642. this.ws.binaryType = 'arraybuffer';
  30643. this.addEventListeners();
  30644. };
  30645. /**
  30646. * Adds event listeners to the socket
  30647. *
  30648. * @api private
  30649. */
  30650. WS.prototype.addEventListeners = function(){
  30651. var self = this;
  30652. this.ws.onopen = function(){
  30653. self.onOpen();
  30654. };
  30655. this.ws.onclose = function(){
  30656. self.onClose();
  30657. };
  30658. this.ws.onmessage = function(ev){
  30659. self.onData(ev.data);
  30660. };
  30661. this.ws.onerror = function(e){
  30662. self.onError('websocket error', e);
  30663. };
  30664. };
  30665. /**
  30666. * Override `onData` to use a timer on iOS.
  30667. * See: https://gist.github.com/mloughran/2052006
  30668. *
  30669. * @api private
  30670. */
  30671. if ('undefined' != typeof navigator
  30672. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  30673. WS.prototype.onData = function(data){
  30674. var self = this;
  30675. setTimeout(function(){
  30676. Transport.prototype.onData.call(self, data);
  30677. }, 0);
  30678. };
  30679. }
  30680. /**
  30681. * Writes data to socket.
  30682. *
  30683. * @param {Array} array of packets.
  30684. * @api private
  30685. */
  30686. WS.prototype.write = function(packets){
  30687. var self = this;
  30688. this.writable = false;
  30689. // encodePacket efficient as it uses WS framing
  30690. // no need for encodePayload
  30691. for (var i = 0, l = packets.length; i < l; i++) {
  30692. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  30693. //Sometimes the websocket has already been closed but the browser didn't
  30694. //have a chance of informing us about it yet, in that case send will
  30695. //throw an error
  30696. try {
  30697. self.ws.send(data);
  30698. } catch (e){
  30699. debug('websocket closed before onclose event');
  30700. }
  30701. });
  30702. }
  30703. function ondrain() {
  30704. self.writable = true;
  30705. self.emit('drain');
  30706. }
  30707. // fake drain
  30708. // defer to next tick to allow Socket to clear writeBuffer
  30709. setTimeout(ondrain, 0);
  30710. };
  30711. /**
  30712. * Called upon close
  30713. *
  30714. * @api private
  30715. */
  30716. WS.prototype.onClose = function(){
  30717. Transport.prototype.onClose.call(this);
  30718. };
  30719. /**
  30720. * Closes socket.
  30721. *
  30722. * @api private
  30723. */
  30724. WS.prototype.doClose = function(){
  30725. if (typeof this.ws !== 'undefined') {
  30726. this.ws.close();
  30727. }
  30728. };
  30729. /**
  30730. * Generates uri for connection.
  30731. *
  30732. * @api private
  30733. */
  30734. WS.prototype.uri = function(){
  30735. var query = this.query || {};
  30736. var schema = this.secure ? 'wss' : 'ws';
  30737. var port = '';
  30738. // avoid port if default for schema
  30739. if (this.port && (('wss' == schema && this.port != 443)
  30740. || ('ws' == schema && this.port != 80))) {
  30741. port = ':' + this.port;
  30742. }
  30743. // append timestamp to URI
  30744. if (this.timestampRequests) {
  30745. query[this.timestampParam] = +new Date;
  30746. }
  30747. // communicate binary support capabilities
  30748. if (!this.supportsBinary) {
  30749. query.b64 = 1;
  30750. }
  30751. query = parseqs.encode(query);
  30752. // prepend ? to query
  30753. if (query.length) {
  30754. query = '?' + query;
  30755. }
  30756. return schema + '://' + this.hostname + port + this.path + query;
  30757. };
  30758. /**
  30759. * Feature detection for WebSocket.
  30760. *
  30761. * @return {Boolean} whether this transport is available.
  30762. * @api public
  30763. */
  30764. WS.prototype.check = function(){
  30765. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  30766. };
  30767. },{"../transport":127,"component-inherit":134,"debug":135,"engine.io-parser":138,"parseqs":150,"ws":152}],133:[function(require,module,exports){
  30768. // browser shim for xmlhttprequest module
  30769. var hasCORS = require('has-cors');
  30770. module.exports = function(opts) {
  30771. var xdomain = opts.xdomain;
  30772. // scheme must be same when usign XDomainRequest
  30773. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  30774. var xscheme = opts.xscheme;
  30775. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  30776. // https://github.com/Automattic/engine.io-client/pull/217
  30777. var enablesXDR = opts.enablesXDR;
  30778. // XMLHttpRequest can be disabled on IE
  30779. try {
  30780. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  30781. return new XMLHttpRequest();
  30782. }
  30783. } catch (e) { }
  30784. // Use XDomainRequest for IE8 if enablesXDR is true
  30785. // because loading bar keeps flashing when using jsonp-polling
  30786. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  30787. try {
  30788. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  30789. return new XDomainRequest();
  30790. }
  30791. } catch (e) { }
  30792. if (!xdomain) {
  30793. try {
  30794. return new ActiveXObject('Microsoft.XMLHTTP');
  30795. } catch(e) { }
  30796. }
  30797. }
  30798. },{"has-cors":147}],134:[function(require,module,exports){
  30799. module.exports = function(a, b){
  30800. var fn = function(){};
  30801. fn.prototype = b.prototype;
  30802. a.prototype = new fn;
  30803. a.prototype.constructor = a;
  30804. };
  30805. },{}],135:[function(require,module,exports){
  30806. /**
  30807. * This is the web browser implementation of `debug()`.
  30808. *
  30809. * Expose `debug()` as the module.
  30810. */
  30811. exports = module.exports = require('./debug');
  30812. exports.log = log;
  30813. exports.formatArgs = formatArgs;
  30814. exports.save = save;
  30815. exports.load = load;
  30816. exports.useColors = useColors;
  30817. /**
  30818. * Colors.
  30819. */
  30820. exports.colors = [
  30821. 'lightseagreen',
  30822. 'forestgreen',
  30823. 'goldenrod',
  30824. 'dodgerblue',
  30825. 'darkorchid',
  30826. 'crimson'
  30827. ];
  30828. /**
  30829. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  30830. * and the Firebug extension (any Firefox version) are known
  30831. * to support "%c" CSS customizations.
  30832. *
  30833. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  30834. */
  30835. function useColors() {
  30836. // is webkit? http://stackoverflow.com/a/16459606/376773
  30837. return ('WebkitAppearance' in document.documentElement.style) ||
  30838. // is firebug? http://stackoverflow.com/a/398120/376773
  30839. (window.console && (console.firebug || (console.exception && console.table))) ||
  30840. // is firefox >= v31?
  30841. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  30842. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  30843. }
  30844. /**
  30845. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  30846. */
  30847. exports.formatters.j = function(v) {
  30848. return JSON.stringify(v);
  30849. };
  30850. /**
  30851. * Colorize log arguments if enabled.
  30852. *
  30853. * @api public
  30854. */
  30855. function formatArgs() {
  30856. var args = arguments;
  30857. var useColors = this.useColors;
  30858. args[0] = (useColors ? '%c' : '')
  30859. + this.namespace
  30860. + (useColors ? ' %c' : ' ')
  30861. + args[0]
  30862. + (useColors ? '%c ' : ' ')
  30863. + '+' + exports.humanize(this.diff);
  30864. if (!useColors) return args;
  30865. var c = 'color: ' + this.color;
  30866. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  30867. // the final "%c" is somewhat tricky, because there could be other
  30868. // arguments passed either before or after the %c, so we need to
  30869. // figure out the correct index to insert the CSS into
  30870. var index = 0;
  30871. var lastC = 0;
  30872. args[0].replace(/%[a-z%]/g, function(match) {
  30873. if ('%%' === match) return;
  30874. index++;
  30875. if ('%c' === match) {
  30876. // we only are interested in the *last* %c
  30877. // (the user may have provided their own)
  30878. lastC = index;
  30879. }
  30880. });
  30881. args.splice(lastC, 0, c);
  30882. return args;
  30883. }
  30884. /**
  30885. * Invokes `console.log()` when available.
  30886. * No-op when `console.log` is not a "function".
  30887. *
  30888. * @api public
  30889. */
  30890. function log() {
  30891. // This hackery is required for IE8,
  30892. // where the `console.log` function doesn't have 'apply'
  30893. return 'object' == typeof console
  30894. && 'function' == typeof console.log
  30895. && Function.prototype.apply.call(console.log, console, arguments);
  30896. }
  30897. /**
  30898. * Save `namespaces`.
  30899. *
  30900. * @param {String} namespaces
  30901. * @api private
  30902. */
  30903. function save(namespaces) {
  30904. try {
  30905. if (null == namespaces) {
  30906. localStorage.removeItem('debug');
  30907. } else {
  30908. localStorage.debug = namespaces;
  30909. }
  30910. } catch(e) {}
  30911. }
  30912. /**
  30913. * Load `namespaces`.
  30914. *
  30915. * @return {String} returns the previously persisted debug modes
  30916. * @api private
  30917. */
  30918. function load() {
  30919. var r;
  30920. try {
  30921. r = localStorage.debug;
  30922. } catch(e) {}
  30923. return r;
  30924. }
  30925. /**
  30926. * Enable namespaces listed in `localStorage.debug` initially.
  30927. */
  30928. exports.enable(load());
  30929. },{"./debug":136}],136:[function(require,module,exports){
  30930. /**
  30931. * This is the common logic for both the Node.js and web browser
  30932. * implementations of `debug()`.
  30933. *
  30934. * Expose `debug()` as the module.
  30935. */
  30936. exports = module.exports = debug;
  30937. exports.coerce = coerce;
  30938. exports.disable = disable;
  30939. exports.enable = enable;
  30940. exports.enabled = enabled;
  30941. exports.humanize = require('ms');
  30942. /**
  30943. * The currently active debug mode names, and names to skip.
  30944. */
  30945. exports.names = [];
  30946. exports.skips = [];
  30947. /**
  30948. * Map of special "%n" handling functions, for the debug "format" argument.
  30949. *
  30950. * Valid key names are a single, lowercased letter, i.e. "n".
  30951. */
  30952. exports.formatters = {};
  30953. /**
  30954. * Previously assigned color.
  30955. */
  30956. var prevColor = 0;
  30957. /**
  30958. * Previous log timestamp.
  30959. */
  30960. var prevTime;
  30961. /**
  30962. * Select a color.
  30963. *
  30964. * @return {Number}
  30965. * @api private
  30966. */
  30967. function selectColor() {
  30968. return exports.colors[prevColor++ % exports.colors.length];
  30969. }
  30970. /**
  30971. * Create a debugger with the given `namespace`.
  30972. *
  30973. * @param {String} namespace
  30974. * @return {Function}
  30975. * @api public
  30976. */
  30977. function debug(namespace) {
  30978. // define the `disabled` version
  30979. function disabled() {
  30980. }
  30981. disabled.enabled = false;
  30982. // define the `enabled` version
  30983. function enabled() {
  30984. var self = enabled;
  30985. // set `diff` timestamp
  30986. var curr = +new Date();
  30987. var ms = curr - (prevTime || curr);
  30988. self.diff = ms;
  30989. self.prev = prevTime;
  30990. self.curr = curr;
  30991. prevTime = curr;
  30992. // add the `color` if not set
  30993. if (null == self.useColors) self.useColors = exports.useColors();
  30994. if (null == self.color && self.useColors) self.color = selectColor();
  30995. var args = Array.prototype.slice.call(arguments);
  30996. args[0] = exports.coerce(args[0]);
  30997. if ('string' !== typeof args[0]) {
  30998. // anything else let's inspect with %o
  30999. args = ['%o'].concat(args);
  31000. }
  31001. // apply any `formatters` transformations
  31002. var index = 0;
  31003. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  31004. // if we encounter an escaped % then don't increase the array index
  31005. if (match === '%%') return match;
  31006. index++;
  31007. var formatter = exports.formatters[format];
  31008. if ('function' === typeof formatter) {
  31009. var val = args[index];
  31010. match = formatter.call(self, val);
  31011. // now we need to remove `args[index]` since it's inlined in the `format`
  31012. args.splice(index, 1);
  31013. index--;
  31014. }
  31015. return match;
  31016. });
  31017. if ('function' === typeof exports.formatArgs) {
  31018. args = exports.formatArgs.apply(self, args);
  31019. }
  31020. var logFn = enabled.log || exports.log || console.log.bind(console);
  31021. logFn.apply(self, args);
  31022. }
  31023. enabled.enabled = true;
  31024. var fn = exports.enabled(namespace) ? enabled : disabled;
  31025. fn.namespace = namespace;
  31026. return fn;
  31027. }
  31028. /**
  31029. * Enables a debug mode by namespaces. This can include modes
  31030. * separated by a colon and wildcards.
  31031. *
  31032. * @param {String} namespaces
  31033. * @api public
  31034. */
  31035. function enable(namespaces) {
  31036. exports.save(namespaces);
  31037. var split = (namespaces || '').split(/[\s,]+/);
  31038. var len = split.length;
  31039. for (var i = 0; i < len; i++) {
  31040. if (!split[i]) continue; // ignore empty strings
  31041. namespaces = split[i].replace(/\*/g, '.*?');
  31042. if (namespaces[0] === '-') {
  31043. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  31044. } else {
  31045. exports.names.push(new RegExp('^' + namespaces + '$'));
  31046. }
  31047. }
  31048. }
  31049. /**
  31050. * Disable debug output.
  31051. *
  31052. * @api public
  31053. */
  31054. function disable() {
  31055. exports.enable('');
  31056. }
  31057. /**
  31058. * Returns true if the given mode name is enabled, false otherwise.
  31059. *
  31060. * @param {String} name
  31061. * @return {Boolean}
  31062. * @api public
  31063. */
  31064. function enabled(name) {
  31065. var i, len;
  31066. for (i = 0, len = exports.skips.length; i < len; i++) {
  31067. if (exports.skips[i].test(name)) {
  31068. return false;
  31069. }
  31070. }
  31071. for (i = 0, len = exports.names.length; i < len; i++) {
  31072. if (exports.names[i].test(name)) {
  31073. return true;
  31074. }
  31075. }
  31076. return false;
  31077. }
  31078. /**
  31079. * Coerce `val`.
  31080. *
  31081. * @param {Mixed} val
  31082. * @return {Mixed}
  31083. * @api private
  31084. */
  31085. function coerce(val) {
  31086. if (val instanceof Error) return val.stack || val.message;
  31087. return val;
  31088. }
  31089. },{"ms":137}],137:[function(require,module,exports){
  31090. /**
  31091. * Helpers.
  31092. */
  31093. var s = 1000;
  31094. var m = s * 60;
  31095. var h = m * 60;
  31096. var d = h * 24;
  31097. var y = d * 365.25;
  31098. /**
  31099. * Parse or format the given `val`.
  31100. *
  31101. * Options:
  31102. *
  31103. * - `long` verbose formatting [false]
  31104. *
  31105. * @param {String|Number} val
  31106. * @param {Object} options
  31107. * @return {String|Number}
  31108. * @api public
  31109. */
  31110. module.exports = function(val, options){
  31111. options = options || {};
  31112. if ('string' == typeof val) return parse(val);
  31113. return options.long
  31114. ? long(val)
  31115. : short(val);
  31116. };
  31117. /**
  31118. * Parse the given `str` and return milliseconds.
  31119. *
  31120. * @param {String} str
  31121. * @return {Number}
  31122. * @api private
  31123. */
  31124. function parse(str) {
  31125. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  31126. if (!match) return;
  31127. var n = parseFloat(match[1]);
  31128. var type = (match[2] || 'ms').toLowerCase();
  31129. switch (type) {
  31130. case 'years':
  31131. case 'year':
  31132. case 'y':
  31133. return n * y;
  31134. case 'days':
  31135. case 'day':
  31136. case 'd':
  31137. return n * d;
  31138. case 'hours':
  31139. case 'hour':
  31140. case 'h':
  31141. return n * h;
  31142. case 'minutes':
  31143. case 'minute':
  31144. case 'm':
  31145. return n * m;
  31146. case 'seconds':
  31147. case 'second':
  31148. case 's':
  31149. return n * s;
  31150. case 'ms':
  31151. return n;
  31152. }
  31153. }
  31154. /**
  31155. * Short format for `ms`.
  31156. *
  31157. * @param {Number} ms
  31158. * @return {String}
  31159. * @api private
  31160. */
  31161. function short(ms) {
  31162. if (ms >= d) return Math.round(ms / d) + 'd';
  31163. if (ms >= h) return Math.round(ms / h) + 'h';
  31164. if (ms >= m) return Math.round(ms / m) + 'm';
  31165. if (ms >= s) return Math.round(ms / s) + 's';
  31166. return ms + 'ms';
  31167. }
  31168. /**
  31169. * Long format for `ms`.
  31170. *
  31171. * @param {Number} ms
  31172. * @return {String}
  31173. * @api private
  31174. */
  31175. function long(ms) {
  31176. return plural(ms, d, 'day')
  31177. || plural(ms, h, 'hour')
  31178. || plural(ms, m, 'minute')
  31179. || plural(ms, s, 'second')
  31180. || ms + ' ms';
  31181. }
  31182. /**
  31183. * Pluralization helper.
  31184. */
  31185. function plural(ms, n, name) {
  31186. if (ms < n) return;
  31187. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  31188. return Math.ceil(ms / n) + ' ' + name + 's';
  31189. }
  31190. },{}],138:[function(require,module,exports){
  31191. (function (global){
  31192. /**
  31193. * Module dependencies.
  31194. */
  31195. var keys = require('./keys');
  31196. var hasBinary = require('has-binary');
  31197. var sliceBuffer = require('arraybuffer.slice');
  31198. var base64encoder = require('base64-arraybuffer');
  31199. var after = require('after');
  31200. var utf8 = require('utf8');
  31201. /**
  31202. * Check if we are running an android browser. That requires us to use
  31203. * ArrayBuffer with polling transports...
  31204. *
  31205. * http://ghinda.net/jpeg-blob-ajax-android/
  31206. */
  31207. var isAndroid = navigator.userAgent.match(/Android/i);
  31208. /**
  31209. * Check if we are running in PhantomJS.
  31210. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  31211. * https://github.com/ariya/phantomjs/issues/11395
  31212. * @type boolean
  31213. */
  31214. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  31215. /**
  31216. * When true, avoids using Blobs to encode payloads.
  31217. * @type boolean
  31218. */
  31219. var dontSendBlobs = isAndroid || isPhantomJS;
  31220. /**
  31221. * Current protocol version.
  31222. */
  31223. exports.protocol = 3;
  31224. /**
  31225. * Packet types.
  31226. */
  31227. var packets = exports.packets = {
  31228. open: 0 // non-ws
  31229. , close: 1 // non-ws
  31230. , ping: 2
  31231. , pong: 3
  31232. , message: 4
  31233. , upgrade: 5
  31234. , noop: 6
  31235. };
  31236. var packetslist = keys(packets);
  31237. /**
  31238. * Premade error packet.
  31239. */
  31240. var err = { type: 'error', data: 'parser error' };
  31241. /**
  31242. * Create a blob api even for blob builder when vendor prefixes exist
  31243. */
  31244. var Blob = require('blob');
  31245. /**
  31246. * Encodes a packet.
  31247. *
  31248. * <packet type id> [ <data> ]
  31249. *
  31250. * Example:
  31251. *
  31252. * 5hello world
  31253. * 3
  31254. * 4
  31255. *
  31256. * Binary is encoded in an identical principle
  31257. *
  31258. * @api private
  31259. */
  31260. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  31261. if ('function' == typeof supportsBinary) {
  31262. callback = supportsBinary;
  31263. supportsBinary = false;
  31264. }
  31265. if ('function' == typeof utf8encode) {
  31266. callback = utf8encode;
  31267. utf8encode = null;
  31268. }
  31269. var data = (packet.data === undefined)
  31270. ? undefined
  31271. : packet.data.buffer || packet.data;
  31272. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  31273. return encodeArrayBuffer(packet, supportsBinary, callback);
  31274. } else if (Blob && data instanceof global.Blob) {
  31275. return encodeBlob(packet, supportsBinary, callback);
  31276. }
  31277. // might be an object with { base64: true, data: dataAsBase64String }
  31278. if (data && data.base64) {
  31279. return encodeBase64Object(packet, callback);
  31280. }
  31281. // Sending data as a utf-8 string
  31282. var encoded = packets[packet.type];
  31283. // data fragment is optional
  31284. if (undefined !== packet.data) {
  31285. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  31286. }
  31287. return callback('' + encoded);
  31288. };
  31289. function encodeBase64Object(packet, callback) {
  31290. // packet data is an object { base64: true, data: dataAsBase64String }
  31291. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  31292. return callback(message);
  31293. }
  31294. /**
  31295. * Encode packet helpers for binary types
  31296. */
  31297. function encodeArrayBuffer(packet, supportsBinary, callback) {
  31298. if (!supportsBinary) {
  31299. return exports.encodeBase64Packet(packet, callback);
  31300. }
  31301. var data = packet.data;
  31302. var contentArray = new Uint8Array(data);
  31303. var resultBuffer = new Uint8Array(1 + data.byteLength);
  31304. resultBuffer[0] = packets[packet.type];
  31305. for (var i = 0; i < contentArray.length; i++) {
  31306. resultBuffer[i+1] = contentArray[i];
  31307. }
  31308. return callback(resultBuffer.buffer);
  31309. }
  31310. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  31311. if (!supportsBinary) {
  31312. return exports.encodeBase64Packet(packet, callback);
  31313. }
  31314. var fr = new FileReader();
  31315. fr.onload = function() {
  31316. packet.data = fr.result;
  31317. exports.encodePacket(packet, supportsBinary, true, callback);
  31318. };
  31319. return fr.readAsArrayBuffer(packet.data);
  31320. }
  31321. function encodeBlob(packet, supportsBinary, callback) {
  31322. if (!supportsBinary) {
  31323. return exports.encodeBase64Packet(packet, callback);
  31324. }
  31325. if (dontSendBlobs) {
  31326. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  31327. }
  31328. var length = new Uint8Array(1);
  31329. length[0] = packets[packet.type];
  31330. var blob = new Blob([length.buffer, packet.data]);
  31331. return callback(blob);
  31332. }
  31333. /**
  31334. * Encodes a packet with binary data in a base64 string
  31335. *
  31336. * @param {Object} packet, has `type` and `data`
  31337. * @return {String} base64 encoded message
  31338. */
  31339. exports.encodeBase64Packet = function(packet, callback) {
  31340. var message = 'b' + exports.packets[packet.type];
  31341. if (Blob && packet.data instanceof Blob) {
  31342. var fr = new FileReader();
  31343. fr.onload = function() {
  31344. var b64 = fr.result.split(',')[1];
  31345. callback(message + b64);
  31346. };
  31347. return fr.readAsDataURL(packet.data);
  31348. }
  31349. var b64data;
  31350. try {
  31351. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  31352. } catch (e) {
  31353. // iPhone Safari doesn't let you apply with typed arrays
  31354. var typed = new Uint8Array(packet.data);
  31355. var basic = new Array(typed.length);
  31356. for (var i = 0; i < typed.length; i++) {
  31357. basic[i] = typed[i];
  31358. }
  31359. b64data = String.fromCharCode.apply(null, basic);
  31360. }
  31361. message += global.btoa(b64data);
  31362. return callback(message);
  31363. };
  31364. /**
  31365. * Decodes a packet. Changes format to Blob if requested.
  31366. *
  31367. * @return {Object} with `type` and `data` (if any)
  31368. * @api private
  31369. */
  31370. exports.decodePacket = function (data, binaryType, utf8decode) {
  31371. // String data
  31372. if (typeof data == 'string' || data === undefined) {
  31373. if (data.charAt(0) == 'b') {
  31374. return exports.decodeBase64Packet(data.substr(1), binaryType);
  31375. }
  31376. if (utf8decode) {
  31377. try {
  31378. data = utf8.decode(data);
  31379. } catch (e) {
  31380. return err;
  31381. }
  31382. }
  31383. var type = data.charAt(0);
  31384. if (Number(type) != type || !packetslist[type]) {
  31385. return err;
  31386. }
  31387. if (data.length > 1) {
  31388. return { type: packetslist[type], data: data.substring(1) };
  31389. } else {
  31390. return { type: packetslist[type] };
  31391. }
  31392. }
  31393. var asArray = new Uint8Array(data);
  31394. var type = asArray[0];
  31395. var rest = sliceBuffer(data, 1);
  31396. if (Blob && binaryType === 'blob') {
  31397. rest = new Blob([rest]);
  31398. }
  31399. return { type: packetslist[type], data: rest };
  31400. };
  31401. /**
  31402. * Decodes a packet encoded in a base64 string
  31403. *
  31404. * @param {String} base64 encoded message
  31405. * @return {Object} with `type` and `data` (if any)
  31406. */
  31407. exports.decodeBase64Packet = function(msg, binaryType) {
  31408. var type = packetslist[msg.charAt(0)];
  31409. if (!global.ArrayBuffer) {
  31410. return { type: type, data: { base64: true, data: msg.substr(1) } };
  31411. }
  31412. var data = base64encoder.decode(msg.substr(1));
  31413. if (binaryType === 'blob' && Blob) {
  31414. data = new Blob([data]);
  31415. }
  31416. return { type: type, data: data };
  31417. };
  31418. /**
  31419. * Encodes multiple messages (payload).
  31420. *
  31421. * <length>:data
  31422. *
  31423. * Example:
  31424. *
  31425. * 11:hello world2:hi
  31426. *
  31427. * If any contents are binary, they will be encoded as base64 strings. Base64
  31428. * encoded strings are marked with a b before the length specifier
  31429. *
  31430. * @param {Array} packets
  31431. * @api private
  31432. */
  31433. exports.encodePayload = function (packets, supportsBinary, callback) {
  31434. if (typeof supportsBinary == 'function') {
  31435. callback = supportsBinary;
  31436. supportsBinary = null;
  31437. }
  31438. var isBinary = hasBinary(packets);
  31439. if (supportsBinary && isBinary) {
  31440. if (Blob && !dontSendBlobs) {
  31441. return exports.encodePayloadAsBlob(packets, callback);
  31442. }
  31443. return exports.encodePayloadAsArrayBuffer(packets, callback);
  31444. }
  31445. if (!packets.length) {
  31446. return callback('0:');
  31447. }
  31448. function setLengthHeader(message) {
  31449. return message.length + ':' + message;
  31450. }
  31451. function encodeOne(packet, doneCallback) {
  31452. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  31453. doneCallback(null, setLengthHeader(message));
  31454. });
  31455. }
  31456. map(packets, encodeOne, function(err, results) {
  31457. return callback(results.join(''));
  31458. });
  31459. };
  31460. /**
  31461. * Async array map using after
  31462. */
  31463. function map(ary, each, done) {
  31464. var result = new Array(ary.length);
  31465. var next = after(ary.length, done);
  31466. var eachWithIndex = function(i, el, cb) {
  31467. each(el, function(error, msg) {
  31468. result[i] = msg;
  31469. cb(error, result);
  31470. });
  31471. };
  31472. for (var i = 0; i < ary.length; i++) {
  31473. eachWithIndex(i, ary[i], next);
  31474. }
  31475. }
  31476. /*
  31477. * Decodes data when a payload is maybe expected. Possible binary contents are
  31478. * decoded from their base64 representation
  31479. *
  31480. * @param {String} data, callback method
  31481. * @api public
  31482. */
  31483. exports.decodePayload = function (data, binaryType, callback) {
  31484. if (typeof data != 'string') {
  31485. return exports.decodePayloadAsBinary(data, binaryType, callback);
  31486. }
  31487. if (typeof binaryType === 'function') {
  31488. callback = binaryType;
  31489. binaryType = null;
  31490. }
  31491. var packet;
  31492. if (data == '') {
  31493. // parser error - ignoring payload
  31494. return callback(err, 0, 1);
  31495. }
  31496. var length = ''
  31497. , n, msg;
  31498. for (var i = 0, l = data.length; i < l; i++) {
  31499. var chr = data.charAt(i);
  31500. if (':' != chr) {
  31501. length += chr;
  31502. } else {
  31503. if ('' == length || (length != (n = Number(length)))) {
  31504. // parser error - ignoring payload
  31505. return callback(err, 0, 1);
  31506. }
  31507. msg = data.substr(i + 1, n);
  31508. if (length != msg.length) {
  31509. // parser error - ignoring payload
  31510. return callback(err, 0, 1);
  31511. }
  31512. if (msg.length) {
  31513. packet = exports.decodePacket(msg, binaryType, true);
  31514. if (err.type == packet.type && err.data == packet.data) {
  31515. // parser error in individual packet - ignoring payload
  31516. return callback(err, 0, 1);
  31517. }
  31518. var ret = callback(packet, i + n, l);
  31519. if (false === ret) return;
  31520. }
  31521. // advance cursor
  31522. i += n;
  31523. length = '';
  31524. }
  31525. }
  31526. if (length != '') {
  31527. // parser error - ignoring payload
  31528. return callback(err, 0, 1);
  31529. }
  31530. };
  31531. /**
  31532. * Encodes multiple messages (payload) as binary.
  31533. *
  31534. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  31535. * 255><data>
  31536. *
  31537. * Example:
  31538. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  31539. *
  31540. * @param {Array} packets
  31541. * @return {ArrayBuffer} encoded payload
  31542. * @api private
  31543. */
  31544. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  31545. if (!packets.length) {
  31546. return callback(new ArrayBuffer(0));
  31547. }
  31548. function encodeOne(packet, doneCallback) {
  31549. exports.encodePacket(packet, true, true, function(data) {
  31550. return doneCallback(null, data);
  31551. });
  31552. }
  31553. map(packets, encodeOne, function(err, encodedPackets) {
  31554. var totalLength = encodedPackets.reduce(function(acc, p) {
  31555. var len;
  31556. if (typeof p === 'string'){
  31557. len = p.length;
  31558. } else {
  31559. len = p.byteLength;
  31560. }
  31561. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  31562. }, 0);
  31563. var resultArray = new Uint8Array(totalLength);
  31564. var bufferIndex = 0;
  31565. encodedPackets.forEach(function(p) {
  31566. var isString = typeof p === 'string';
  31567. var ab = p;
  31568. if (isString) {
  31569. var view = new Uint8Array(p.length);
  31570. for (var i = 0; i < p.length; i++) {
  31571. view[i] = p.charCodeAt(i);
  31572. }
  31573. ab = view.buffer;
  31574. }
  31575. if (isString) { // not true binary
  31576. resultArray[bufferIndex++] = 0;
  31577. } else { // true binary
  31578. resultArray[bufferIndex++] = 1;
  31579. }
  31580. var lenStr = ab.byteLength.toString();
  31581. for (var i = 0; i < lenStr.length; i++) {
  31582. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  31583. }
  31584. resultArray[bufferIndex++] = 255;
  31585. var view = new Uint8Array(ab);
  31586. for (var i = 0; i < view.length; i++) {
  31587. resultArray[bufferIndex++] = view[i];
  31588. }
  31589. });
  31590. return callback(resultArray.buffer);
  31591. });
  31592. };
  31593. /**
  31594. * Encode as Blob
  31595. */
  31596. exports.encodePayloadAsBlob = function(packets, callback) {
  31597. function encodeOne(packet, doneCallback) {
  31598. exports.encodePacket(packet, true, true, function(encoded) {
  31599. var binaryIdentifier = new Uint8Array(1);
  31600. binaryIdentifier[0] = 1;
  31601. if (typeof encoded === 'string') {
  31602. var view = new Uint8Array(encoded.length);
  31603. for (var i = 0; i < encoded.length; i++) {
  31604. view[i] = encoded.charCodeAt(i);
  31605. }
  31606. encoded = view.buffer;
  31607. binaryIdentifier[0] = 0;
  31608. }
  31609. var len = (encoded instanceof ArrayBuffer)
  31610. ? encoded.byteLength
  31611. : encoded.size;
  31612. var lenStr = len.toString();
  31613. var lengthAry = new Uint8Array(lenStr.length + 1);
  31614. for (var i = 0; i < lenStr.length; i++) {
  31615. lengthAry[i] = parseInt(lenStr[i]);
  31616. }
  31617. lengthAry[lenStr.length] = 255;
  31618. if (Blob) {
  31619. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  31620. doneCallback(null, blob);
  31621. }
  31622. });
  31623. }
  31624. map(packets, encodeOne, function(err, results) {
  31625. return callback(new Blob(results));
  31626. });
  31627. };
  31628. /*
  31629. * Decodes data when a payload is maybe expected. Strings are decoded by
  31630. * interpreting each byte as a key code for entries marked to start with 0. See
  31631. * description of encodePayloadAsBinary
  31632. *
  31633. * @param {ArrayBuffer} data, callback method
  31634. * @api public
  31635. */
  31636. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  31637. if (typeof binaryType === 'function') {
  31638. callback = binaryType;
  31639. binaryType = null;
  31640. }
  31641. var bufferTail = data;
  31642. var buffers = [];
  31643. var numberTooLong = false;
  31644. while (bufferTail.byteLength > 0) {
  31645. var tailArray = new Uint8Array(bufferTail);
  31646. var isString = tailArray[0] === 0;
  31647. var msgLength = '';
  31648. for (var i = 1; ; i++) {
  31649. if (tailArray[i] == 255) break;
  31650. if (msgLength.length > 310) {
  31651. numberTooLong = true;
  31652. break;
  31653. }
  31654. msgLength += tailArray[i];
  31655. }
  31656. if(numberTooLong) return callback(err, 0, 1);
  31657. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  31658. msgLength = parseInt(msgLength);
  31659. var msg = sliceBuffer(bufferTail, 0, msgLength);
  31660. if (isString) {
  31661. try {
  31662. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  31663. } catch (e) {
  31664. // iPhone Safari doesn't let you apply to typed arrays
  31665. var typed = new Uint8Array(msg);
  31666. msg = '';
  31667. for (var i = 0; i < typed.length; i++) {
  31668. msg += String.fromCharCode(typed[i]);
  31669. }
  31670. }
  31671. }
  31672. buffers.push(msg);
  31673. bufferTail = sliceBuffer(bufferTail, msgLength);
  31674. }
  31675. var total = buffers.length;
  31676. buffers.forEach(function(buffer, i) {
  31677. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  31678. });
  31679. };
  31680. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31681. },{"./keys":139,"after":140,"arraybuffer.slice":141,"base64-arraybuffer":142,"blob":143,"has-binary":144,"utf8":146}],139:[function(require,module,exports){
  31682. /**
  31683. * Gets the keys for an object.
  31684. *
  31685. * @return {Array} keys
  31686. * @api private
  31687. */
  31688. module.exports = Object.keys || function keys (obj){
  31689. var arr = [];
  31690. var has = Object.prototype.hasOwnProperty;
  31691. for (var i in obj) {
  31692. if (has.call(obj, i)) {
  31693. arr.push(i);
  31694. }
  31695. }
  31696. return arr;
  31697. };
  31698. },{}],140:[function(require,module,exports){
  31699. module.exports = after
  31700. function after(count, callback, err_cb) {
  31701. var bail = false
  31702. err_cb = err_cb || noop
  31703. proxy.count = count
  31704. return (count === 0) ? callback() : proxy
  31705. function proxy(err, result) {
  31706. if (proxy.count <= 0) {
  31707. throw new Error('after called too many times')
  31708. }
  31709. --proxy.count
  31710. // after first error, rest are passed to err_cb
  31711. if (err) {
  31712. bail = true
  31713. callback(err)
  31714. // future error callbacks will go to error handler
  31715. callback = err_cb
  31716. } else if (proxy.count === 0 && !bail) {
  31717. callback(null, result)
  31718. }
  31719. }
  31720. }
  31721. function noop() {}
  31722. },{}],141:[function(require,module,exports){
  31723. /**
  31724. * An abstraction for slicing an arraybuffer even when
  31725. * ArrayBuffer.prototype.slice is not supported
  31726. *
  31727. * @api public
  31728. */
  31729. module.exports = function(arraybuffer, start, end) {
  31730. var bytes = arraybuffer.byteLength;
  31731. start = start || 0;
  31732. end = end || bytes;
  31733. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  31734. if (start < 0) { start += bytes; }
  31735. if (end < 0) { end += bytes; }
  31736. if (end > bytes) { end = bytes; }
  31737. if (start >= bytes || start >= end || bytes === 0) {
  31738. return new ArrayBuffer(0);
  31739. }
  31740. var abv = new Uint8Array(arraybuffer);
  31741. var result = new Uint8Array(end - start);
  31742. for (var i = start, ii = 0; i < end; i++, ii++) {
  31743. result[ii] = abv[i];
  31744. }
  31745. return result.buffer;
  31746. };
  31747. },{}],142:[function(require,module,exports){
  31748. /*
  31749. * base64-arraybuffer
  31750. * https://github.com/niklasvh/base64-arraybuffer
  31751. *
  31752. * Copyright (c) 2012 Niklas von Hertzen
  31753. * Licensed under the MIT license.
  31754. */
  31755. (function(chars){
  31756. "use strict";
  31757. exports.encode = function(arraybuffer) {
  31758. var bytes = new Uint8Array(arraybuffer),
  31759. i, len = bytes.length, base64 = "";
  31760. for (i = 0; i < len; i+=3) {
  31761. base64 += chars[bytes[i] >> 2];
  31762. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  31763. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  31764. base64 += chars[bytes[i + 2] & 63];
  31765. }
  31766. if ((len % 3) === 2) {
  31767. base64 = base64.substring(0, base64.length - 1) + "=";
  31768. } else if (len % 3 === 1) {
  31769. base64 = base64.substring(0, base64.length - 2) + "==";
  31770. }
  31771. return base64;
  31772. };
  31773. exports.decode = function(base64) {
  31774. var bufferLength = base64.length * 0.75,
  31775. len = base64.length, i, p = 0,
  31776. encoded1, encoded2, encoded3, encoded4;
  31777. if (base64[base64.length - 1] === "=") {
  31778. bufferLength--;
  31779. if (base64[base64.length - 2] === "=") {
  31780. bufferLength--;
  31781. }
  31782. }
  31783. var arraybuffer = new ArrayBuffer(bufferLength),
  31784. bytes = new Uint8Array(arraybuffer);
  31785. for (i = 0; i < len; i+=4) {
  31786. encoded1 = chars.indexOf(base64[i]);
  31787. encoded2 = chars.indexOf(base64[i+1]);
  31788. encoded3 = chars.indexOf(base64[i+2]);
  31789. encoded4 = chars.indexOf(base64[i+3]);
  31790. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  31791. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  31792. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  31793. }
  31794. return arraybuffer;
  31795. };
  31796. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  31797. },{}],143:[function(require,module,exports){
  31798. (function (global){
  31799. /**
  31800. * Create a blob builder even when vendor prefixes exist
  31801. */
  31802. var BlobBuilder = global.BlobBuilder
  31803. || global.WebKitBlobBuilder
  31804. || global.MSBlobBuilder
  31805. || global.MozBlobBuilder;
  31806. /**
  31807. * Check if Blob constructor is supported
  31808. */
  31809. var blobSupported = (function() {
  31810. try {
  31811. var b = new Blob(['hi']);
  31812. return b.size == 2;
  31813. } catch(e) {
  31814. return false;
  31815. }
  31816. })();
  31817. /**
  31818. * Check if BlobBuilder is supported
  31819. */
  31820. var blobBuilderSupported = BlobBuilder
  31821. && BlobBuilder.prototype.append
  31822. && BlobBuilder.prototype.getBlob;
  31823. function BlobBuilderConstructor(ary, options) {
  31824. options = options || {};
  31825. var bb = new BlobBuilder();
  31826. for (var i = 0; i < ary.length; i++) {
  31827. bb.append(ary[i]);
  31828. }
  31829. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  31830. };
  31831. module.exports = (function() {
  31832. if (blobSupported) {
  31833. return global.Blob;
  31834. } else if (blobBuilderSupported) {
  31835. return BlobBuilderConstructor;
  31836. } else {
  31837. return undefined;
  31838. }
  31839. })();
  31840. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31841. },{}],144:[function(require,module,exports){
  31842. (function (global){
  31843. /*
  31844. * Module requirements.
  31845. */
  31846. var isArray = require('isarray');
  31847. /**
  31848. * Module exports.
  31849. */
  31850. module.exports = hasBinary;
  31851. /**
  31852. * Checks for binary data.
  31853. *
  31854. * Right now only Buffer and ArrayBuffer are supported..
  31855. *
  31856. * @param {Object} anything
  31857. * @api public
  31858. */
  31859. function hasBinary(data) {
  31860. function _hasBinary(obj) {
  31861. if (!obj) return false;
  31862. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  31863. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  31864. (global.Blob && obj instanceof Blob) ||
  31865. (global.File && obj instanceof File)
  31866. ) {
  31867. return true;
  31868. }
  31869. if (isArray(obj)) {
  31870. for (var i = 0; i < obj.length; i++) {
  31871. if (_hasBinary(obj[i])) {
  31872. return true;
  31873. }
  31874. }
  31875. } else if (obj && 'object' == typeof obj) {
  31876. if (obj.toJSON) {
  31877. obj = obj.toJSON();
  31878. }
  31879. for (var key in obj) {
  31880. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  31881. return true;
  31882. }
  31883. }
  31884. }
  31885. return false;
  31886. }
  31887. return _hasBinary(data);
  31888. }
  31889. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31890. },{"isarray":145}],145:[function(require,module,exports){
  31891. module.exports = Array.isArray || function (arr) {
  31892. return Object.prototype.toString.call(arr) == '[object Array]';
  31893. };
  31894. },{}],146:[function(require,module,exports){
  31895. (function (global){
  31896. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  31897. ;(function(root) {
  31898. // Detect free variables `exports`
  31899. var freeExports = typeof exports == 'object' && exports;
  31900. // Detect free variable `module`
  31901. var freeModule = typeof module == 'object' && module &&
  31902. module.exports == freeExports && module;
  31903. // Detect free variable `global`, from Node.js or Browserified code,
  31904. // and use it as `root`
  31905. var freeGlobal = typeof global == 'object' && global;
  31906. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  31907. root = freeGlobal;
  31908. }
  31909. /*--------------------------------------------------------------------------*/
  31910. var stringFromCharCode = String.fromCharCode;
  31911. // Taken from http://mths.be/punycode
  31912. function ucs2decode(string) {
  31913. var output = [];
  31914. var counter = 0;
  31915. var length = string.length;
  31916. var value;
  31917. var extra;
  31918. while (counter < length) {
  31919. value = string.charCodeAt(counter++);
  31920. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  31921. // high surrogate, and there is a next character
  31922. extra = string.charCodeAt(counter++);
  31923. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  31924. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  31925. } else {
  31926. // unmatched surrogate; only append this code unit, in case the next
  31927. // code unit is the high surrogate of a surrogate pair
  31928. output.push(value);
  31929. counter--;
  31930. }
  31931. } else {
  31932. output.push(value);
  31933. }
  31934. }
  31935. return output;
  31936. }
  31937. // Taken from http://mths.be/punycode
  31938. function ucs2encode(array) {
  31939. var length = array.length;
  31940. var index = -1;
  31941. var value;
  31942. var output = '';
  31943. while (++index < length) {
  31944. value = array[index];
  31945. if (value > 0xFFFF) {
  31946. value -= 0x10000;
  31947. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  31948. value = 0xDC00 | value & 0x3FF;
  31949. }
  31950. output += stringFromCharCode(value);
  31951. }
  31952. return output;
  31953. }
  31954. /*--------------------------------------------------------------------------*/
  31955. function createByte(codePoint, shift) {
  31956. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  31957. }
  31958. function encodeCodePoint(codePoint) {
  31959. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  31960. return stringFromCharCode(codePoint);
  31961. }
  31962. var symbol = '';
  31963. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  31964. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  31965. }
  31966. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  31967. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  31968. symbol += createByte(codePoint, 6);
  31969. }
  31970. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  31971. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  31972. symbol += createByte(codePoint, 12);
  31973. symbol += createByte(codePoint, 6);
  31974. }
  31975. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  31976. return symbol;
  31977. }
  31978. function utf8encode(string) {
  31979. var codePoints = ucs2decode(string);
  31980. // console.log(JSON.stringify(codePoints.map(function(x) {
  31981. // return 'U+' + x.toString(16).toUpperCase();
  31982. // })));
  31983. var length = codePoints.length;
  31984. var index = -1;
  31985. var codePoint;
  31986. var byteString = '';
  31987. while (++index < length) {
  31988. codePoint = codePoints[index];
  31989. byteString += encodeCodePoint(codePoint);
  31990. }
  31991. return byteString;
  31992. }
  31993. /*--------------------------------------------------------------------------*/
  31994. function readContinuationByte() {
  31995. if (byteIndex >= byteCount) {
  31996. throw Error('Invalid byte index');
  31997. }
  31998. var continuationByte = byteArray[byteIndex] & 0xFF;
  31999. byteIndex++;
  32000. if ((continuationByte & 0xC0) == 0x80) {
  32001. return continuationByte & 0x3F;
  32002. }
  32003. // If we end up here, it’s not a continuation byte
  32004. throw Error('Invalid continuation byte');
  32005. }
  32006. function decodeSymbol() {
  32007. var byte1;
  32008. var byte2;
  32009. var byte3;
  32010. var byte4;
  32011. var codePoint;
  32012. if (byteIndex > byteCount) {
  32013. throw Error('Invalid byte index');
  32014. }
  32015. if (byteIndex == byteCount) {
  32016. return false;
  32017. }
  32018. // Read first byte
  32019. byte1 = byteArray[byteIndex] & 0xFF;
  32020. byteIndex++;
  32021. // 1-byte sequence (no continuation bytes)
  32022. if ((byte1 & 0x80) == 0) {
  32023. return byte1;
  32024. }
  32025. // 2-byte sequence
  32026. if ((byte1 & 0xE0) == 0xC0) {
  32027. var byte2 = readContinuationByte();
  32028. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  32029. if (codePoint >= 0x80) {
  32030. return codePoint;
  32031. } else {
  32032. throw Error('Invalid continuation byte');
  32033. }
  32034. }
  32035. // 3-byte sequence (may include unpaired surrogates)
  32036. if ((byte1 & 0xF0) == 0xE0) {
  32037. byte2 = readContinuationByte();
  32038. byte3 = readContinuationByte();
  32039. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  32040. if (codePoint >= 0x0800) {
  32041. return codePoint;
  32042. } else {
  32043. throw Error('Invalid continuation byte');
  32044. }
  32045. }
  32046. // 4-byte sequence
  32047. if ((byte1 & 0xF8) == 0xF0) {
  32048. byte2 = readContinuationByte();
  32049. byte3 = readContinuationByte();
  32050. byte4 = readContinuationByte();
  32051. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  32052. (byte3 << 0x06) | byte4;
  32053. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  32054. return codePoint;
  32055. }
  32056. }
  32057. throw Error('Invalid UTF-8 detected');
  32058. }
  32059. var byteArray;
  32060. var byteCount;
  32061. var byteIndex;
  32062. function utf8decode(byteString) {
  32063. byteArray = ucs2decode(byteString);
  32064. byteCount = byteArray.length;
  32065. byteIndex = 0;
  32066. var codePoints = [];
  32067. var tmp;
  32068. while ((tmp = decodeSymbol()) !== false) {
  32069. codePoints.push(tmp);
  32070. }
  32071. return ucs2encode(codePoints);
  32072. }
  32073. /*--------------------------------------------------------------------------*/
  32074. var utf8 = {
  32075. 'version': '2.0.0',
  32076. 'encode': utf8encode,
  32077. 'decode': utf8decode
  32078. };
  32079. // Some AMD build optimizers, like r.js, check for specific condition patterns
  32080. // like the following:
  32081. if (
  32082. typeof define == 'function' &&
  32083. typeof define.amd == 'object' &&
  32084. define.amd
  32085. ) {
  32086. define(function() {
  32087. return utf8;
  32088. });
  32089. } else if (freeExports && !freeExports.nodeType) {
  32090. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  32091. freeModule.exports = utf8;
  32092. } else { // in Narwhal or RingoJS v0.7.0-
  32093. var object = {};
  32094. var hasOwnProperty = object.hasOwnProperty;
  32095. for (var key in utf8) {
  32096. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  32097. }
  32098. }
  32099. } else { // in Rhino or a web browser
  32100. root.utf8 = utf8;
  32101. }
  32102. }(this));
  32103. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  32104. },{}],147:[function(require,module,exports){
  32105. /**
  32106. * Module dependencies.
  32107. */
  32108. var global = require('global');
  32109. /**
  32110. * Module exports.
  32111. *
  32112. * Logic borrowed from Modernizr:
  32113. *
  32114. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  32115. */
  32116. try {
  32117. module.exports = 'XMLHttpRequest' in global &&
  32118. 'withCredentials' in new global.XMLHttpRequest();
  32119. } catch (err) {
  32120. // if XMLHttp support is disabled in IE then it will throw
  32121. // when trying to create
  32122. module.exports = false;
  32123. }
  32124. },{"global":148}],148:[function(require,module,exports){
  32125. /**
  32126. * Returns `this`. Execute this without a "context" (i.e. without it being
  32127. * attached to an object of the left-hand side), and `this` points to the
  32128. * "global" scope of the current JS execution.
  32129. */
  32130. module.exports = (function () { return this; })();
  32131. },{}],149:[function(require,module,exports){
  32132. (function (global){
  32133. /**
  32134. * JSON parse.
  32135. *
  32136. * @see Based on jQuery#parseJSON (MIT) and JSON2
  32137. * @api private
  32138. */
  32139. var rvalidchars = /^[\],:{}\s]*$/;
  32140. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  32141. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  32142. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  32143. var rtrimLeft = /^\s+/;
  32144. var rtrimRight = /\s+$/;
  32145. module.exports = function parsejson(data) {
  32146. if ('string' != typeof data || !data) {
  32147. return null;
  32148. }
  32149. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  32150. // Attempt to parse using the native JSON parser first
  32151. if (global.JSON && JSON.parse) {
  32152. return JSON.parse(data);
  32153. }
  32154. if (rvalidchars.test(data.replace(rvalidescape, '@')
  32155. .replace(rvalidtokens, ']')
  32156. .replace(rvalidbraces, ''))) {
  32157. return (new Function('return ' + data))();
  32158. }
  32159. };
  32160. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  32161. },{}],150:[function(require,module,exports){
  32162. /**
  32163. * Compiles a querystring
  32164. * Returns string representation of the object
  32165. *
  32166. * @param {Object}
  32167. * @api private
  32168. */
  32169. exports.encode = function (obj) {
  32170. var str = '';
  32171. for (var i in obj) {
  32172. if (obj.hasOwnProperty(i)) {
  32173. if (str.length) str += '&';
  32174. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  32175. }
  32176. }
  32177. return str;
  32178. };
  32179. /**
  32180. * Parses a simple querystring into an object
  32181. *
  32182. * @param {String} qs
  32183. * @api private
  32184. */
  32185. exports.decode = function(qs){
  32186. var qry = {};
  32187. var pairs = qs.split('&');
  32188. for (var i = 0, l = pairs.length; i < l; i++) {
  32189. var pair = pairs[i].split('=');
  32190. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  32191. }
  32192. return qry;
  32193. };
  32194. },{}],151:[function(require,module,exports){
  32195. /**
  32196. * Parses an URI
  32197. *
  32198. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  32199. * @api private
  32200. */
  32201. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  32202. var parts = [
  32203. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  32204. ];
  32205. module.exports = function parseuri(str) {
  32206. var src = str,
  32207. b = str.indexOf('['),
  32208. e = str.indexOf(']');
  32209. if (b != -1 && e != -1) {
  32210. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  32211. }
  32212. var m = re.exec(str || ''),
  32213. uri = {},
  32214. i = 14;
  32215. while (i--) {
  32216. uri[parts[i]] = m[i] || '';
  32217. }
  32218. if (b != -1 && e != -1) {
  32219. uri.source = src;
  32220. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  32221. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  32222. uri.ipv6uri = true;
  32223. }
  32224. return uri;
  32225. };
  32226. },{}],152:[function(require,module,exports){
  32227. /**
  32228. * Module dependencies.
  32229. */
  32230. var global = (function() { return this; })();
  32231. /**
  32232. * WebSocket constructor.
  32233. */
  32234. var WebSocket = global.WebSocket || global.MozWebSocket;
  32235. /**
  32236. * Module exports.
  32237. */
  32238. module.exports = WebSocket ? ws : null;
  32239. /**
  32240. * WebSocket constructor.
  32241. *
  32242. * The third `opts` options object gets ignored in web browsers, since it's
  32243. * non-standard, and throws a TypeError if passed to the constructor.
  32244. * See: https://github.com/einaros/ws/issues/227
  32245. *
  32246. * @param {String} uri
  32247. * @param {Array} protocols (optional)
  32248. * @param {Object) opts (optional)
  32249. * @api public
  32250. */
  32251. function ws(uri, protocols, opts) {
  32252. var instance;
  32253. if (protocols) {
  32254. instance = new WebSocket(uri, protocols);
  32255. } else {
  32256. instance = new WebSocket(uri);
  32257. }
  32258. return instance;
  32259. }
  32260. if (WebSocket) ws.prototype = WebSocket.prototype;
  32261. },{}],153:[function(require,module,exports){
  32262. (function (global){
  32263. /*
  32264. * Module requirements.
  32265. */
  32266. var isArray = require('isarray');
  32267. /**
  32268. * Module exports.
  32269. */
  32270. module.exports = hasBinary;
  32271. /**
  32272. * Checks for binary data.
  32273. *
  32274. * Right now only Buffer and ArrayBuffer are supported..
  32275. *
  32276. * @param {Object} anything
  32277. * @api public
  32278. */
  32279. function hasBinary(data) {
  32280. function _hasBinary(obj) {
  32281. if (!obj) return false;
  32282. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  32283. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  32284. (global.Blob && obj instanceof Blob) ||
  32285. (global.File && obj instanceof File)
  32286. ) {
  32287. return true;
  32288. }
  32289. if (isArray(obj)) {
  32290. for (var i = 0; i < obj.length; i++) {
  32291. if (_hasBinary(obj[i])) {
  32292. return true;
  32293. }
  32294. }
  32295. } else if (obj && 'object' == typeof obj) {
  32296. if (obj.toJSON) {
  32297. obj = obj.toJSON();
  32298. }
  32299. for (var key in obj) {
  32300. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  32301. return true;
  32302. }
  32303. }
  32304. }
  32305. return false;
  32306. }
  32307. return _hasBinary(data);
  32308. }
  32309. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  32310. },{"isarray":154}],154:[function(require,module,exports){
  32311. arguments[4][145][0].apply(exports,arguments)
  32312. },{"dup":145}],155:[function(require,module,exports){
  32313. var indexOf = [].indexOf;
  32314. module.exports = function(arr, obj){
  32315. if (indexOf) return arr.indexOf(obj);
  32316. for (var i = 0; i < arr.length; ++i) {
  32317. if (arr[i] === obj) return i;
  32318. }
  32319. return -1;
  32320. };
  32321. },{}],156:[function(require,module,exports){
  32322. /**
  32323. * HOP ref.
  32324. */
  32325. var has = Object.prototype.hasOwnProperty;
  32326. /**
  32327. * Return own keys in `obj`.
  32328. *
  32329. * @param {Object} obj
  32330. * @return {Array}
  32331. * @api public
  32332. */
  32333. exports.keys = Object.keys || function(obj){
  32334. var keys = [];
  32335. for (var key in obj) {
  32336. if (has.call(obj, key)) {
  32337. keys.push(key);
  32338. }
  32339. }
  32340. return keys;
  32341. };
  32342. /**
  32343. * Return own values in `obj`.
  32344. *
  32345. * @param {Object} obj
  32346. * @return {Array}
  32347. * @api public
  32348. */
  32349. exports.values = function(obj){
  32350. var vals = [];
  32351. for (var key in obj) {
  32352. if (has.call(obj, key)) {
  32353. vals.push(obj[key]);
  32354. }
  32355. }
  32356. return vals;
  32357. };
  32358. /**
  32359. * Merge `b` into `a`.
  32360. *
  32361. * @param {Object} a
  32362. * @param {Object} b
  32363. * @return {Object} a
  32364. * @api public
  32365. */
  32366. exports.merge = function(a, b){
  32367. for (var key in b) {
  32368. if (has.call(b, key)) {
  32369. a[key] = b[key];
  32370. }
  32371. }
  32372. return a;
  32373. };
  32374. /**
  32375. * Return length of `obj`.
  32376. *
  32377. * @param {Object} obj
  32378. * @return {Number}
  32379. * @api public
  32380. */
  32381. exports.length = function(obj){
  32382. return exports.keys(obj).length;
  32383. };
  32384. /**
  32385. * Check if `obj` is empty.
  32386. *
  32387. * @param {Object} obj
  32388. * @return {Boolean}
  32389. * @api public
  32390. */
  32391. exports.isEmpty = function(obj){
  32392. return 0 == exports.length(obj);
  32393. };
  32394. },{}],157:[function(require,module,exports){
  32395. /**
  32396. * Parses an URI
  32397. *
  32398. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  32399. * @api private
  32400. */
  32401. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  32402. var parts = [
  32403. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  32404. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  32405. ];
  32406. module.exports = function parseuri(str) {
  32407. var m = re.exec(str || '')
  32408. , uri = {}
  32409. , i = 14;
  32410. while (i--) {
  32411. uri[parts[i]] = m[i] || '';
  32412. }
  32413. return uri;
  32414. };
  32415. },{}],158:[function(require,module,exports){
  32416. (function (global){
  32417. /*global Blob,File*/
  32418. /**
  32419. * Module requirements
  32420. */
  32421. var isArray = require('isarray');
  32422. var isBuf = require('./is-buffer');
  32423. /**
  32424. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  32425. * Anything with blobs or files should be fed through removeBlobs before coming
  32426. * here.
  32427. *
  32428. * @param {Object} packet - socket.io event packet
  32429. * @return {Object} with deconstructed packet and list of buffers
  32430. * @api public
  32431. */
  32432. exports.deconstructPacket = function(packet){
  32433. var buffers = [];
  32434. var packetData = packet.data;
  32435. function _deconstructPacket(data) {
  32436. if (!data) return data;
  32437. if (isBuf(data)) {
  32438. var placeholder = { _placeholder: true, num: buffers.length };
  32439. buffers.push(data);
  32440. return placeholder;
  32441. } else if (isArray(data)) {
  32442. var newData = new Array(data.length);
  32443. for (var i = 0; i < data.length; i++) {
  32444. newData[i] = _deconstructPacket(data[i]);
  32445. }
  32446. return newData;
  32447. } else if ('object' == typeof data && !(data instanceof Date)) {
  32448. var newData = {};
  32449. for (var key in data) {
  32450. newData[key] = _deconstructPacket(data[key]);
  32451. }
  32452. return newData;
  32453. }
  32454. return data;
  32455. }
  32456. var pack = packet;
  32457. pack.data = _deconstructPacket(packetData);
  32458. pack.attachments = buffers.length; // number of binary 'attachments'
  32459. return {packet: pack, buffers: buffers};
  32460. };
  32461. /**
  32462. * Reconstructs a binary packet from its placeholder packet and buffers
  32463. *
  32464. * @param {Object} packet - event packet with placeholders
  32465. * @param {Array} buffers - binary buffers to put in placeholder positions
  32466. * @return {Object} reconstructed packet
  32467. * @api public
  32468. */
  32469. exports.reconstructPacket = function(packet, buffers) {
  32470. var curPlaceHolder = 0;
  32471. function _reconstructPacket(data) {
  32472. if (data && data._placeholder) {
  32473. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  32474. return buf;
  32475. } else if (isArray(data)) {
  32476. for (var i = 0; i < data.length; i++) {
  32477. data[i] = _reconstructPacket(data[i]);
  32478. }
  32479. return data;
  32480. } else if (data && 'object' == typeof data) {
  32481. for (var key in data) {
  32482. data[key] = _reconstructPacket(data[key]);
  32483. }
  32484. return data;
  32485. }
  32486. return data;
  32487. }
  32488. packet.data = _reconstructPacket(packet.data);
  32489. packet.attachments = undefined; // no longer useful
  32490. return packet;
  32491. };
  32492. /**
  32493. * Asynchronously removes Blobs or Files from data via
  32494. * FileReader's readAsArrayBuffer method. Used before encoding
  32495. * data as msgpack. Calls callback with the blobless data.
  32496. *
  32497. * @param {Object} data
  32498. * @param {Function} callback
  32499. * @api private
  32500. */
  32501. exports.removeBlobs = function(data, callback) {
  32502. function _removeBlobs(obj, curKey, containingObject) {
  32503. if (!obj) return obj;
  32504. // convert any blob
  32505. if ((global.Blob && obj instanceof Blob) ||
  32506. (global.File && obj instanceof File)) {
  32507. pendingBlobs++;
  32508. // async filereader
  32509. var fileReader = new FileReader();
  32510. fileReader.onload = function() { // this.result == arraybuffer
  32511. if (containingObject) {
  32512. containingObject[curKey] = this.result;
  32513. }
  32514. else {
  32515. bloblessData = this.result;
  32516. }
  32517. // if nothing pending its callback time
  32518. if(! --pendingBlobs) {
  32519. callback(bloblessData);
  32520. }
  32521. };
  32522. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  32523. } else if (isArray(obj)) { // handle array
  32524. for (var i = 0; i < obj.length; i++) {
  32525. _removeBlobs(obj[i], i, obj);
  32526. }
  32527. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  32528. for (var key in obj) {
  32529. _removeBlobs(obj[key], key, obj);
  32530. }
  32531. }
  32532. }
  32533. var pendingBlobs = 0;
  32534. var bloblessData = data;
  32535. _removeBlobs(bloblessData);
  32536. if (!pendingBlobs) {
  32537. callback(bloblessData);
  32538. }
  32539. };
  32540. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  32541. },{"./is-buffer":160,"isarray":161}],159:[function(require,module,exports){
  32542. /**
  32543. * Module dependencies.
  32544. */
  32545. var debug = require('debug')('socket.io-parser');
  32546. var json = require('json3');
  32547. var isArray = require('isarray');
  32548. var Emitter = require('component-emitter');
  32549. var binary = require('./binary');
  32550. var isBuf = require('./is-buffer');
  32551. /**
  32552. * Protocol version.
  32553. *
  32554. * @api public
  32555. */
  32556. exports.protocol = 4;
  32557. /**
  32558. * Packet types.
  32559. *
  32560. * @api public
  32561. */
  32562. exports.types = [
  32563. 'CONNECT',
  32564. 'DISCONNECT',
  32565. 'EVENT',
  32566. 'BINARY_EVENT',
  32567. 'ACK',
  32568. 'BINARY_ACK',
  32569. 'ERROR'
  32570. ];
  32571. /**
  32572. * Packet type `connect`.
  32573. *
  32574. * @api public
  32575. */
  32576. exports.CONNECT = 0;
  32577. /**
  32578. * Packet type `disconnect`.
  32579. *
  32580. * @api public
  32581. */
  32582. exports.DISCONNECT = 1;
  32583. /**
  32584. * Packet type `event`.
  32585. *
  32586. * @api public
  32587. */
  32588. exports.EVENT = 2;
  32589. /**
  32590. * Packet type `ack`.
  32591. *
  32592. * @api public
  32593. */
  32594. exports.ACK = 3;
  32595. /**
  32596. * Packet type `error`.
  32597. *
  32598. * @api public
  32599. */
  32600. exports.ERROR = 4;
  32601. /**
  32602. * Packet type 'binary event'
  32603. *
  32604. * @api public
  32605. */
  32606. exports.BINARY_EVENT = 5;
  32607. /**
  32608. * Packet type `binary ack`. For acks with binary arguments.
  32609. *
  32610. * @api public
  32611. */
  32612. exports.BINARY_ACK = 6;
  32613. /**
  32614. * Encoder constructor.
  32615. *
  32616. * @api public
  32617. */
  32618. exports.Encoder = Encoder;
  32619. /**
  32620. * Decoder constructor.
  32621. *
  32622. * @api public
  32623. */
  32624. exports.Decoder = Decoder;
  32625. /**
  32626. * A socket.io Encoder instance
  32627. *
  32628. * @api public
  32629. */
  32630. function Encoder() {}
  32631. /**
  32632. * Encode a packet as a single string if non-binary, or as a
  32633. * buffer sequence, depending on packet type.
  32634. *
  32635. * @param {Object} obj - packet object
  32636. * @param {Function} callback - function to handle encodings (likely engine.write)
  32637. * @return Calls callback with Array of encodings
  32638. * @api public
  32639. */
  32640. Encoder.prototype.encode = function(obj, callback){
  32641. debug('encoding packet %j', obj);
  32642. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  32643. encodeAsBinary(obj, callback);
  32644. }
  32645. else {
  32646. var encoding = encodeAsString(obj);
  32647. callback([encoding]);
  32648. }
  32649. };
  32650. /**
  32651. * Encode packet as string.
  32652. *
  32653. * @param {Object} packet
  32654. * @return {String} encoded
  32655. * @api private
  32656. */
  32657. function encodeAsString(obj) {
  32658. var str = '';
  32659. var nsp = false;
  32660. // first is type
  32661. str += obj.type;
  32662. // attachments if we have them
  32663. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  32664. str += obj.attachments;
  32665. str += '-';
  32666. }
  32667. // if we have a namespace other than `/`
  32668. // we append it followed by a comma `,`
  32669. if (obj.nsp && '/' != obj.nsp) {
  32670. nsp = true;
  32671. str += obj.nsp;
  32672. }
  32673. // immediately followed by the id
  32674. if (null != obj.id) {
  32675. if (nsp) {
  32676. str += ',';
  32677. nsp = false;
  32678. }
  32679. str += obj.id;
  32680. }
  32681. // json data
  32682. if (null != obj.data) {
  32683. if (nsp) str += ',';
  32684. str += json.stringify(obj.data);
  32685. }
  32686. debug('encoded %j as %s', obj, str);
  32687. return str;
  32688. }
  32689. /**
  32690. * Encode packet as 'buffer sequence' by removing blobs, and
  32691. * deconstructing packet into object with placeholders and
  32692. * a list of buffers.
  32693. *
  32694. * @param {Object} packet
  32695. * @return {Buffer} encoded
  32696. * @api private
  32697. */
  32698. function encodeAsBinary(obj, callback) {
  32699. function writeEncoding(bloblessData) {
  32700. var deconstruction = binary.deconstructPacket(bloblessData);
  32701. var pack = encodeAsString(deconstruction.packet);
  32702. var buffers = deconstruction.buffers;
  32703. buffers.unshift(pack); // add packet info to beginning of data list
  32704. callback(buffers); // write all the buffers
  32705. }
  32706. binary.removeBlobs(obj, writeEncoding);
  32707. }
  32708. /**
  32709. * A socket.io Decoder instance
  32710. *
  32711. * @return {Object} decoder
  32712. * @api public
  32713. */
  32714. function Decoder() {
  32715. this.reconstructor = null;
  32716. }
  32717. /**
  32718. * Mix in `Emitter` with Decoder.
  32719. */
  32720. Emitter(Decoder.prototype);
  32721. /**
  32722. * Decodes an ecoded packet string into packet JSON.
  32723. *
  32724. * @param {String} obj - encoded packet
  32725. * @return {Object} packet
  32726. * @api public
  32727. */
  32728. Decoder.prototype.add = function(obj) {
  32729. var packet;
  32730. if ('string' == typeof obj) {
  32731. packet = decodeString(obj);
  32732. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  32733. this.reconstructor = new BinaryReconstructor(packet);
  32734. // no attachments, labeled binary but no binary data to follow
  32735. if (this.reconstructor.reconPack.attachments === 0) {
  32736. this.emit('decoded', packet);
  32737. }
  32738. } else { // non-binary full packet
  32739. this.emit('decoded', packet);
  32740. }
  32741. }
  32742. else if (isBuf(obj) || obj.base64) { // raw binary data
  32743. if (!this.reconstructor) {
  32744. throw new Error('got binary data when not reconstructing a packet');
  32745. } else {
  32746. packet = this.reconstructor.takeBinaryData(obj);
  32747. if (packet) { // received final buffer
  32748. this.reconstructor = null;
  32749. this.emit('decoded', packet);
  32750. }
  32751. }
  32752. }
  32753. else {
  32754. throw new Error('Unknown type: ' + obj);
  32755. }
  32756. };
  32757. /**
  32758. * Decode a packet String (JSON data)
  32759. *
  32760. * @param {String} str
  32761. * @return {Object} packet
  32762. * @api private
  32763. */
  32764. function decodeString(str) {
  32765. var p = {};
  32766. var i = 0;
  32767. // look up type
  32768. p.type = Number(str.charAt(0));
  32769. if (null == exports.types[p.type]) return error();
  32770. // look up attachments if type binary
  32771. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  32772. var buf = '';
  32773. while (str.charAt(++i) != '-') {
  32774. buf += str.charAt(i);
  32775. if (i == str.length) break;
  32776. }
  32777. if (buf != Number(buf) || str.charAt(i) != '-') {
  32778. throw new Error('Illegal attachments');
  32779. }
  32780. p.attachments = Number(buf);
  32781. }
  32782. // look up namespace (if any)
  32783. if ('/' == str.charAt(i + 1)) {
  32784. p.nsp = '';
  32785. while (++i) {
  32786. var c = str.charAt(i);
  32787. if (',' == c) break;
  32788. p.nsp += c;
  32789. if (i == str.length) break;
  32790. }
  32791. } else {
  32792. p.nsp = '/';
  32793. }
  32794. // look up id
  32795. var next = str.charAt(i + 1);
  32796. if ('' !== next && Number(next) == next) {
  32797. p.id = '';
  32798. while (++i) {
  32799. var c = str.charAt(i);
  32800. if (null == c || Number(c) != c) {
  32801. --i;
  32802. break;
  32803. }
  32804. p.id += str.charAt(i);
  32805. if (i == str.length) break;
  32806. }
  32807. p.id = Number(p.id);
  32808. }
  32809. // look up json data
  32810. if (str.charAt(++i)) {
  32811. try {
  32812. p.data = json.parse(str.substr(i));
  32813. } catch(e){
  32814. return error();
  32815. }
  32816. }
  32817. debug('decoded %s as %j', str, p);
  32818. return p;
  32819. }
  32820. /**
  32821. * Deallocates a parser's resources
  32822. *
  32823. * @api public
  32824. */
  32825. Decoder.prototype.destroy = function() {
  32826. if (this.reconstructor) {
  32827. this.reconstructor.finishedReconstruction();
  32828. }
  32829. };
  32830. /**
  32831. * A manager of a binary event's 'buffer sequence'. Should
  32832. * be constructed whenever a packet of type BINARY_EVENT is
  32833. * decoded.
  32834. *
  32835. * @param {Object} packet
  32836. * @return {BinaryReconstructor} initialized reconstructor
  32837. * @api private
  32838. */
  32839. function BinaryReconstructor(packet) {
  32840. this.reconPack = packet;
  32841. this.buffers = [];
  32842. }
  32843. /**
  32844. * Method to be called when binary data received from connection
  32845. * after a BINARY_EVENT packet.
  32846. *
  32847. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  32848. * @return {null | Object} returns null if more binary data is expected or
  32849. * a reconstructed packet object if all buffers have been received.
  32850. * @api private
  32851. */
  32852. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  32853. this.buffers.push(binData);
  32854. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  32855. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  32856. this.finishedReconstruction();
  32857. return packet;
  32858. }
  32859. return null;
  32860. };
  32861. /**
  32862. * Cleans up binary packet reconstruction variables.
  32863. *
  32864. * @api private
  32865. */
  32866. BinaryReconstructor.prototype.finishedReconstruction = function() {
  32867. this.reconPack = null;
  32868. this.buffers = [];
  32869. };
  32870. function error(data){
  32871. return {
  32872. type: exports.ERROR,
  32873. data: 'parser error'
  32874. };
  32875. }
  32876. },{"./binary":158,"./is-buffer":160,"component-emitter":122,"debug":123,"isarray":161,"json3":162}],160:[function(require,module,exports){
  32877. (function (global){
  32878. module.exports = isBuf;
  32879. /**
  32880. * Returns true if obj is a buffer or an arraybuffer.
  32881. *
  32882. * @api private
  32883. */
  32884. function isBuf(obj) {
  32885. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  32886. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  32887. }
  32888. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  32889. },{}],161:[function(require,module,exports){
  32890. arguments[4][145][0].apply(exports,arguments)
  32891. },{"dup":145}],162:[function(require,module,exports){
  32892. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  32893. ;(function (window) {
  32894. // Convenience aliases.
  32895. var getClass = {}.toString, isProperty, forEach, undef;
  32896. // Detect the `define` function exposed by asynchronous module loaders. The
  32897. // strict `define` check is necessary for compatibility with `r.js`.
  32898. var isLoader = typeof define === "function" && define.amd;
  32899. // Detect native implementations.
  32900. var nativeJSON = typeof JSON == "object" && JSON;
  32901. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  32902. // available.
  32903. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  32904. if (JSON3 && nativeJSON) {
  32905. // Explicitly delegate to the native `stringify` and `parse`
  32906. // implementations in CommonJS environments.
  32907. JSON3.stringify = nativeJSON.stringify;
  32908. JSON3.parse = nativeJSON.parse;
  32909. } else {
  32910. // Export for web browsers, JavaScript engines, and asynchronous module
  32911. // loaders, using the global `JSON` object if available.
  32912. JSON3 = window.JSON = nativeJSON || {};
  32913. }
  32914. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  32915. var isExtended = new Date(-3509827334573292);
  32916. try {
  32917. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  32918. // results for certain dates in Opera >= 10.53.
  32919. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  32920. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  32921. // but clips the values returned by the date methods to the range of
  32922. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  32923. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  32924. } catch (exception) {}
  32925. // Internal: Determines whether the native `JSON.stringify` and `parse`
  32926. // implementations are spec-compliant. Based on work by Ken Snyder.
  32927. function has(name) {
  32928. if (has[name] !== undef) {
  32929. // Return cached feature test result.
  32930. return has[name];
  32931. }
  32932. var isSupported;
  32933. if (name == "bug-string-char-index") {
  32934. // IE <= 7 doesn't support accessing string characters using square
  32935. // bracket notation. IE 8 only supports this for primitives.
  32936. isSupported = "a"[0] != "a";
  32937. } else if (name == "json") {
  32938. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  32939. // supported.
  32940. isSupported = has("json-stringify") && has("json-parse");
  32941. } else {
  32942. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  32943. // Test `JSON.stringify`.
  32944. if (name == "json-stringify") {
  32945. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  32946. if (stringifySupported) {
  32947. // A test function object with a custom `toJSON` method.
  32948. (value = function () {
  32949. return 1;
  32950. }).toJSON = value;
  32951. try {
  32952. stringifySupported =
  32953. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  32954. // primitives as object literals.
  32955. stringify(0) === "0" &&
  32956. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  32957. // literals.
  32958. stringify(new Number()) === "0" &&
  32959. stringify(new String()) == '""' &&
  32960. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  32961. // does not define a canonical JSON representation (this applies to
  32962. // objects with `toJSON` properties as well, *unless* they are nested
  32963. // within an object or array).
  32964. stringify(getClass) === undef &&
  32965. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  32966. // FF 3.1b3 pass this test.
  32967. stringify(undef) === undef &&
  32968. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  32969. // respectively, if the value is omitted entirely.
  32970. stringify() === undef &&
  32971. // FF 3.1b1, 2 throw an error if the given value is not a number,
  32972. // string, array, object, Boolean, or `null` literal. This applies to
  32973. // objects with custom `toJSON` methods as well, unless they are nested
  32974. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  32975. // methods entirely.
  32976. stringify(value) === "1" &&
  32977. stringify([value]) == "[1]" &&
  32978. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  32979. // `"[null]"`.
  32980. stringify([undef]) == "[null]" &&
  32981. // YUI 3.0.0b1 fails to serialize `null` literals.
  32982. stringify(null) == "null" &&
  32983. // FF 3.1b1, 2 halts serialization if an array contains a function:
  32984. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  32985. // elides non-JSON values from objects and arrays, unless they
  32986. // define custom `toJSON` methods.
  32987. stringify([undef, getClass, null]) == "[null,null,null]" &&
  32988. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  32989. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  32990. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  32991. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  32992. stringify(null, value) === "1" &&
  32993. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  32994. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  32995. // serialize extended years.
  32996. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  32997. // The milliseconds are optional in ES 5, but required in 5.1.
  32998. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  32999. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  33000. // four-digit years instead of six-digit years. Credits: @Yaffle.
  33001. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  33002. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  33003. // values less than 1000. Credits: @Yaffle.
  33004. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  33005. } catch (exception) {
  33006. stringifySupported = false;
  33007. }
  33008. }
  33009. isSupported = stringifySupported;
  33010. }
  33011. // Test `JSON.parse`.
  33012. if (name == "json-parse") {
  33013. var parse = JSON3.parse;
  33014. if (typeof parse == "function") {
  33015. try {
  33016. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  33017. // Conforming implementations should also coerce the initial argument to
  33018. // a string prior to parsing.
  33019. if (parse("0") === 0 && !parse(false)) {
  33020. // Simple parsing test.
  33021. value = parse(serialized);
  33022. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  33023. if (parseSupported) {
  33024. try {
  33025. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  33026. parseSupported = !parse('"\t"');
  33027. } catch (exception) {}
  33028. if (parseSupported) {
  33029. try {
  33030. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  33031. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  33032. // certain octal literals.
  33033. parseSupported = parse("01") !== 1;
  33034. } catch (exception) {}
  33035. }
  33036. if (parseSupported) {
  33037. try {
  33038. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  33039. // points. These environments, along with FF 3.1b1 and 2,
  33040. // also allow trailing commas in JSON objects and arrays.
  33041. parseSupported = parse("1.") !== 1;
  33042. } catch (exception) {}
  33043. }
  33044. }
  33045. }
  33046. } catch (exception) {
  33047. parseSupported = false;
  33048. }
  33049. }
  33050. isSupported = parseSupported;
  33051. }
  33052. }
  33053. return has[name] = !!isSupported;
  33054. }
  33055. if (!has("json")) {
  33056. // Common `[[Class]]` name aliases.
  33057. var functionClass = "[object Function]";
  33058. var dateClass = "[object Date]";
  33059. var numberClass = "[object Number]";
  33060. var stringClass = "[object String]";
  33061. var arrayClass = "[object Array]";
  33062. var booleanClass = "[object Boolean]";
  33063. // Detect incomplete support for accessing string characters by index.
  33064. var charIndexBuggy = has("bug-string-char-index");
  33065. // Define additional utility methods if the `Date` methods are buggy.
  33066. if (!isExtended) {
  33067. var floor = Math.floor;
  33068. // A mapping between the months of the year and the number of days between
  33069. // January 1st and the first of the respective month.
  33070. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  33071. // Internal: Calculates the number of days between the Unix epoch and the
  33072. // first day of the given month.
  33073. var getDay = function (year, month) {
  33074. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  33075. };
  33076. }
  33077. // Internal: Determines if a property is a direct property of the given
  33078. // object. Delegates to the native `Object#hasOwnProperty` method.
  33079. if (!(isProperty = {}.hasOwnProperty)) {
  33080. isProperty = function (property) {
  33081. var members = {}, constructor;
  33082. if ((members.__proto__ = null, members.__proto__ = {
  33083. // The *proto* property cannot be set multiple times in recent
  33084. // versions of Firefox and SeaMonkey.
  33085. "toString": 1
  33086. }, members).toString != getClass) {
  33087. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  33088. // supports the mutable *proto* property.
  33089. isProperty = function (property) {
  33090. // Capture and break the object's prototype chain (see section 8.6.2
  33091. // of the ES 5.1 spec). The parenthesized expression prevents an
  33092. // unsafe transformation by the Closure Compiler.
  33093. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  33094. // Restore the original prototype chain.
  33095. this.__proto__ = original;
  33096. return result;
  33097. };
  33098. } else {
  33099. // Capture a reference to the top-level `Object` constructor.
  33100. constructor = members.constructor;
  33101. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  33102. // other environments.
  33103. isProperty = function (property) {
  33104. var parent = (this.constructor || constructor).prototype;
  33105. return property in this && !(property in parent && this[property] === parent[property]);
  33106. };
  33107. }
  33108. members = null;
  33109. return isProperty.call(this, property);
  33110. };
  33111. }
  33112. // Internal: A set of primitive types used by `isHostType`.
  33113. var PrimitiveTypes = {
  33114. 'boolean': 1,
  33115. 'number': 1,
  33116. 'string': 1,
  33117. 'undefined': 1
  33118. };
  33119. // Internal: Determines if the given object `property` value is a
  33120. // non-primitive.
  33121. var isHostType = function (object, property) {
  33122. var type = typeof object[property];
  33123. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  33124. };
  33125. // Internal: Normalizes the `for...in` iteration algorithm across
  33126. // environments. Each enumerated key is yielded to a `callback` function.
  33127. forEach = function (object, callback) {
  33128. var size = 0, Properties, members, property;
  33129. // Tests for bugs in the current environment's `for...in` algorithm. The
  33130. // `valueOf` property inherits the non-enumerable flag from
  33131. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  33132. (Properties = function () {
  33133. this.valueOf = 0;
  33134. }).prototype.valueOf = 0;
  33135. // Iterate over a new instance of the `Properties` class.
  33136. members = new Properties();
  33137. for (property in members) {
  33138. // Ignore all properties inherited from `Object.prototype`.
  33139. if (isProperty.call(members, property)) {
  33140. size++;
  33141. }
  33142. }
  33143. Properties = members = null;
  33144. // Normalize the iteration algorithm.
  33145. if (!size) {
  33146. // A list of non-enumerable properties inherited from `Object.prototype`.
  33147. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  33148. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  33149. // properties.
  33150. forEach = function (object, callback) {
  33151. var isFunction = getClass.call(object) == functionClass, property, length;
  33152. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  33153. for (property in object) {
  33154. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  33155. // certain conditions; IE does not.
  33156. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  33157. callback(property);
  33158. }
  33159. }
  33160. // Manually invoke the callback for each non-enumerable property.
  33161. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  33162. };
  33163. } else if (size == 2) {
  33164. // Safari <= 2.0.4 enumerates shadowed properties twice.
  33165. forEach = function (object, callback) {
  33166. // Create a set of iterated properties.
  33167. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  33168. for (property in object) {
  33169. // Store each property name to prevent double enumeration. The
  33170. // `prototype` property of functions is not enumerated due to cross-
  33171. // environment inconsistencies.
  33172. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  33173. callback(property);
  33174. }
  33175. }
  33176. };
  33177. } else {
  33178. // No bugs detected; use the standard `for...in` algorithm.
  33179. forEach = function (object, callback) {
  33180. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  33181. for (property in object) {
  33182. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  33183. callback(property);
  33184. }
  33185. }
  33186. // Manually invoke the callback for the `constructor` property due to
  33187. // cross-environment inconsistencies.
  33188. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  33189. callback(property);
  33190. }
  33191. };
  33192. }
  33193. return forEach(object, callback);
  33194. };
  33195. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  33196. // `filter` argument may specify either a function that alters how object and
  33197. // array members are serialized, or an array of strings and numbers that
  33198. // indicates which properties should be serialized. The optional `width`
  33199. // argument may be either a string or number that specifies the indentation
  33200. // level of the output.
  33201. if (!has("json-stringify")) {
  33202. // Internal: A map of control characters and their escaped equivalents.
  33203. var Escapes = {
  33204. 92: "\\\\",
  33205. 34: '\\"',
  33206. 8: "\\b",
  33207. 12: "\\f",
  33208. 10: "\\n",
  33209. 13: "\\r",
  33210. 9: "\\t"
  33211. };
  33212. // Internal: Converts `value` into a zero-padded string such that its
  33213. // length is at least equal to `width`. The `width` must be <= 6.
  33214. var leadingZeroes = "000000";
  33215. var toPaddedString = function (width, value) {
  33216. // The `|| 0` expression is necessary to work around a bug in
  33217. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  33218. return (leadingZeroes + (value || 0)).slice(-width);
  33219. };
  33220. // Internal: Double-quotes a string `value`, replacing all ASCII control
  33221. // characters (characters with code unit values between 0 and 31) with
  33222. // their escaped equivalents. This is an implementation of the
  33223. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  33224. var unicodePrefix = "\\u00";
  33225. var quote = function (value) {
  33226. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  33227. if (isLarge) {
  33228. symbols = value.split("");
  33229. }
  33230. for (; index < length; index++) {
  33231. var charCode = value.charCodeAt(index);
  33232. // If the character is a control character, append its Unicode or
  33233. // shorthand escape sequence; otherwise, append the character as-is.
  33234. switch (charCode) {
  33235. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  33236. result += Escapes[charCode];
  33237. break;
  33238. default:
  33239. if (charCode < 32) {
  33240. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  33241. break;
  33242. }
  33243. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  33244. }
  33245. }
  33246. return result + '"';
  33247. };
  33248. // Internal: Recursively serializes an object. Implements the
  33249. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  33250. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  33251. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  33252. try {
  33253. // Necessary for host object support.
  33254. value = object[property];
  33255. } catch (exception) {}
  33256. if (typeof value == "object" && value) {
  33257. className = getClass.call(value);
  33258. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  33259. if (value > -1 / 0 && value < 1 / 0) {
  33260. // Dates are serialized according to the `Date#toJSON` method
  33261. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  33262. // for the ISO 8601 date time string format.
  33263. if (getDay) {
  33264. // Manually compute the year, month, date, hours, minutes,
  33265. // seconds, and milliseconds if the `getUTC*` methods are
  33266. // buggy. Adapted from @Yaffle's `date-shim` project.
  33267. date = floor(value / 864e5);
  33268. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  33269. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  33270. date = 1 + date - getDay(year, month);
  33271. // The `time` value specifies the time within the day (see ES
  33272. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  33273. // to compute `A modulo B`, as the `%` operator does not
  33274. // correspond to the `modulo` operation for negative numbers.
  33275. time = (value % 864e5 + 864e5) % 864e5;
  33276. // The hours, minutes, seconds, and milliseconds are obtained by
  33277. // decomposing the time within the day. See section 15.9.1.10.
  33278. hours = floor(time / 36e5) % 24;
  33279. minutes = floor(time / 6e4) % 60;
  33280. seconds = floor(time / 1e3) % 60;
  33281. milliseconds = time % 1e3;
  33282. } else {
  33283. year = value.getUTCFullYear();
  33284. month = value.getUTCMonth();
  33285. date = value.getUTCDate();
  33286. hours = value.getUTCHours();
  33287. minutes = value.getUTCMinutes();
  33288. seconds = value.getUTCSeconds();
  33289. milliseconds = value.getUTCMilliseconds();
  33290. }
  33291. // Serialize extended years correctly.
  33292. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  33293. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  33294. // Months, dates, hours, minutes, and seconds should have two
  33295. // digits; milliseconds should have three.
  33296. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  33297. // Milliseconds are optional in ES 5.0, but required in 5.1.
  33298. "." + toPaddedString(3, milliseconds) + "Z";
  33299. } else {
  33300. value = null;
  33301. }
  33302. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  33303. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  33304. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  33305. // ignores all `toJSON` methods on these objects unless they are
  33306. // defined directly on an instance.
  33307. value = value.toJSON(property);
  33308. }
  33309. }
  33310. if (callback) {
  33311. // If a replacement function was provided, call it to obtain the value
  33312. // for serialization.
  33313. value = callback.call(object, property, value);
  33314. }
  33315. if (value === null) {
  33316. return "null";
  33317. }
  33318. className = getClass.call(value);
  33319. if (className == booleanClass) {
  33320. // Booleans are represented literally.
  33321. return "" + value;
  33322. } else if (className == numberClass) {
  33323. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  33324. // `"null"`.
  33325. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  33326. } else if (className == stringClass) {
  33327. // Strings are double-quoted and escaped.
  33328. return quote("" + value);
  33329. }
  33330. // Recursively serialize objects and arrays.
  33331. if (typeof value == "object") {
  33332. // Check for cyclic structures. This is a linear search; performance
  33333. // is inversely proportional to the number of unique nested objects.
  33334. for (length = stack.length; length--;) {
  33335. if (stack[length] === value) {
  33336. // Cyclic structures cannot be serialized by `JSON.stringify`.
  33337. throw TypeError();
  33338. }
  33339. }
  33340. // Add the object to the stack of traversed objects.
  33341. stack.push(value);
  33342. results = [];
  33343. // Save the current indentation level and indent one additional level.
  33344. prefix = indentation;
  33345. indentation += whitespace;
  33346. if (className == arrayClass) {
  33347. // Recursively serialize array elements.
  33348. for (index = 0, length = value.length; index < length; index++) {
  33349. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  33350. results.push(element === undef ? "null" : element);
  33351. }
  33352. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  33353. } else {
  33354. // Recursively serialize object members. Members are selected from
  33355. // either a user-specified list of property names, or the object
  33356. // itself.
  33357. forEach(properties || value, function (property) {
  33358. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  33359. if (element !== undef) {
  33360. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  33361. // is not the empty string, let `member` {quote(property) + ":"}
  33362. // be the concatenation of `member` and the `space` character."
  33363. // The "`space` character" refers to the literal space
  33364. // character, not the `space` {width} argument provided to
  33365. // `JSON.stringify`.
  33366. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  33367. }
  33368. });
  33369. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  33370. }
  33371. // Remove the object from the traversed object stack.
  33372. stack.pop();
  33373. return result;
  33374. }
  33375. };
  33376. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  33377. JSON3.stringify = function (source, filter, width) {
  33378. var whitespace, callback, properties, className;
  33379. if (typeof filter == "function" || typeof filter == "object" && filter) {
  33380. if ((className = getClass.call(filter)) == functionClass) {
  33381. callback = filter;
  33382. } else if (className == arrayClass) {
  33383. // Convert the property names array into a makeshift set.
  33384. properties = {};
  33385. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  33386. }
  33387. }
  33388. if (width) {
  33389. if ((className = getClass.call(width)) == numberClass) {
  33390. // Convert the `width` to an integer and create a string containing
  33391. // `width` number of space characters.
  33392. if ((width -= width % 1) > 0) {
  33393. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  33394. }
  33395. } else if (className == stringClass) {
  33396. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  33397. }
  33398. }
  33399. // Opera <= 7.54u2 discards the values associated with empty string keys
  33400. // (`""`) only if they are used directly within an object member list
  33401. // (e.g., `!("" in { "": 1})`).
  33402. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  33403. };
  33404. }
  33405. // Public: Parses a JSON source string.
  33406. if (!has("json-parse")) {
  33407. var fromCharCode = String.fromCharCode;
  33408. // Internal: A map of escaped control characters and their unescaped
  33409. // equivalents.
  33410. var Unescapes = {
  33411. 92: "\\",
  33412. 34: '"',
  33413. 47: "/",
  33414. 98: "\b",
  33415. 116: "\t",
  33416. 110: "\n",
  33417. 102: "\f",
  33418. 114: "\r"
  33419. };
  33420. // Internal: Stores the parser state.
  33421. var Index, Source;
  33422. // Internal: Resets the parser state and throws a `SyntaxError`.
  33423. var abort = function() {
  33424. Index = Source = null;
  33425. throw SyntaxError();
  33426. };
  33427. // Internal: Returns the next token, or `"$"` if the parser has reached
  33428. // the end of the source string. A token may be a string, number, `null`
  33429. // literal, or Boolean literal.
  33430. var lex = function () {
  33431. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  33432. while (Index < length) {
  33433. charCode = source.charCodeAt(Index);
  33434. switch (charCode) {
  33435. case 9: case 10: case 13: case 32:
  33436. // Skip whitespace tokens, including tabs, carriage returns, line
  33437. // feeds, and space characters.
  33438. Index++;
  33439. break;
  33440. case 123: case 125: case 91: case 93: case 58: case 44:
  33441. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  33442. // the current position.
  33443. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  33444. Index++;
  33445. return value;
  33446. case 34:
  33447. // `"` delimits a JSON string; advance to the next character and
  33448. // begin parsing the string. String tokens are prefixed with the
  33449. // sentinel `@` character to distinguish them from punctuators and
  33450. // end-of-string tokens.
  33451. for (value = "@", Index++; Index < length;) {
  33452. charCode = source.charCodeAt(Index);
  33453. if (charCode < 32) {
  33454. // Unescaped ASCII control characters (those with a code unit
  33455. // less than the space character) are not permitted.
  33456. abort();
  33457. } else if (charCode == 92) {
  33458. // A reverse solidus (`\`) marks the beginning of an escaped
  33459. // control character (including `"`, `\`, and `/`) or Unicode
  33460. // escape sequence.
  33461. charCode = source.charCodeAt(++Index);
  33462. switch (charCode) {
  33463. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  33464. // Revive escaped control characters.
  33465. value += Unescapes[charCode];
  33466. Index++;
  33467. break;
  33468. case 117:
  33469. // `\u` marks the beginning of a Unicode escape sequence.
  33470. // Advance to the first character and validate the
  33471. // four-digit code point.
  33472. begin = ++Index;
  33473. for (position = Index + 4; Index < position; Index++) {
  33474. charCode = source.charCodeAt(Index);
  33475. // A valid sequence comprises four hexdigits (case-
  33476. // insensitive) that form a single hexadecimal value.
  33477. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  33478. // Invalid Unicode escape sequence.
  33479. abort();
  33480. }
  33481. }
  33482. // Revive the escaped character.
  33483. value += fromCharCode("0x" + source.slice(begin, Index));
  33484. break;
  33485. default:
  33486. // Invalid escape sequence.
  33487. abort();
  33488. }
  33489. } else {
  33490. if (charCode == 34) {
  33491. // An unescaped double-quote character marks the end of the
  33492. // string.
  33493. break;
  33494. }
  33495. charCode = source.charCodeAt(Index);
  33496. begin = Index;
  33497. // Optimize for the common case where a string is valid.
  33498. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  33499. charCode = source.charCodeAt(++Index);
  33500. }
  33501. // Append the string as-is.
  33502. value += source.slice(begin, Index);
  33503. }
  33504. }
  33505. if (source.charCodeAt(Index) == 34) {
  33506. // Advance to the next character and return the revived string.
  33507. Index++;
  33508. return value;
  33509. }
  33510. // Unterminated string.
  33511. abort();
  33512. default:
  33513. // Parse numbers and literals.
  33514. begin = Index;
  33515. // Advance past the negative sign, if one is specified.
  33516. if (charCode == 45) {
  33517. isSigned = true;
  33518. charCode = source.charCodeAt(++Index);
  33519. }
  33520. // Parse an integer or floating-point value.
  33521. if (charCode >= 48 && charCode <= 57) {
  33522. // Leading zeroes are interpreted as octal literals.
  33523. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  33524. // Illegal octal literal.
  33525. abort();
  33526. }
  33527. isSigned = false;
  33528. // Parse the integer component.
  33529. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  33530. // Floats cannot contain a leading decimal point; however, this
  33531. // case is already accounted for by the parser.
  33532. if (source.charCodeAt(Index) == 46) {
  33533. position = ++Index;
  33534. // Parse the decimal component.
  33535. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  33536. if (position == Index) {
  33537. // Illegal trailing decimal.
  33538. abort();
  33539. }
  33540. Index = position;
  33541. }
  33542. // Parse exponents. The `e` denoting the exponent is
  33543. // case-insensitive.
  33544. charCode = source.charCodeAt(Index);
  33545. if (charCode == 101 || charCode == 69) {
  33546. charCode = source.charCodeAt(++Index);
  33547. // Skip past the sign following the exponent, if one is
  33548. // specified.
  33549. if (charCode == 43 || charCode == 45) {
  33550. Index++;
  33551. }
  33552. // Parse the exponential component.
  33553. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  33554. if (position == Index) {
  33555. // Illegal empty exponent.
  33556. abort();
  33557. }
  33558. Index = position;
  33559. }
  33560. // Coerce the parsed value to a JavaScript number.
  33561. return +source.slice(begin, Index);
  33562. }
  33563. // A negative sign may only precede numbers.
  33564. if (isSigned) {
  33565. abort();
  33566. }
  33567. // `true`, `false`, and `null` literals.
  33568. if (source.slice(Index, Index + 4) == "true") {
  33569. Index += 4;
  33570. return true;
  33571. } else if (source.slice(Index, Index + 5) == "false") {
  33572. Index += 5;
  33573. return false;
  33574. } else if (source.slice(Index, Index + 4) == "null") {
  33575. Index += 4;
  33576. return null;
  33577. }
  33578. // Unrecognized token.
  33579. abort();
  33580. }
  33581. }
  33582. // Return the sentinel `$` character if the parser has reached the end
  33583. // of the source string.
  33584. return "$";
  33585. };
  33586. // Internal: Parses a JSON `value` token.
  33587. var get = function (value) {
  33588. var results, hasMembers;
  33589. if (value == "$") {
  33590. // Unexpected end of input.
  33591. abort();
  33592. }
  33593. if (typeof value == "string") {
  33594. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  33595. // Remove the sentinel `@` character.
  33596. return value.slice(1);
  33597. }
  33598. // Parse object and array literals.
  33599. if (value == "[") {
  33600. // Parses a JSON array, returning a new JavaScript array.
  33601. results = [];
  33602. for (;; hasMembers || (hasMembers = true)) {
  33603. value = lex();
  33604. // A closing square bracket marks the end of the array literal.
  33605. if (value == "]") {
  33606. break;
  33607. }
  33608. // If the array literal contains elements, the current token
  33609. // should be a comma separating the previous element from the
  33610. // next.
  33611. if (hasMembers) {
  33612. if (value == ",") {
  33613. value = lex();
  33614. if (value == "]") {
  33615. // Unexpected trailing `,` in array literal.
  33616. abort();
  33617. }
  33618. } else {
  33619. // A `,` must separate each array element.
  33620. abort();
  33621. }
  33622. }
  33623. // Elisions and leading commas are not permitted.
  33624. if (value == ",") {
  33625. abort();
  33626. }
  33627. results.push(get(value));
  33628. }
  33629. return results;
  33630. } else if (value == "{") {
  33631. // Parses a JSON object, returning a new JavaScript object.
  33632. results = {};
  33633. for (;; hasMembers || (hasMembers = true)) {
  33634. value = lex();
  33635. // A closing curly brace marks the end of the object literal.
  33636. if (value == "}") {
  33637. break;
  33638. }
  33639. // If the object literal contains members, the current token
  33640. // should be a comma separator.
  33641. if (hasMembers) {
  33642. if (value == ",") {
  33643. value = lex();
  33644. if (value == "}") {
  33645. // Unexpected trailing `,` in object literal.
  33646. abort();
  33647. }
  33648. } else {
  33649. // A `,` must separate each object member.
  33650. abort();
  33651. }
  33652. }
  33653. // Leading commas are not permitted, object property names must be
  33654. // double-quoted strings, and a `:` must separate each property
  33655. // name and value.
  33656. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  33657. abort();
  33658. }
  33659. results[value.slice(1)] = get(lex());
  33660. }
  33661. return results;
  33662. }
  33663. // Unexpected token encountered.
  33664. abort();
  33665. }
  33666. return value;
  33667. };
  33668. // Internal: Updates a traversed object member.
  33669. var update = function(source, property, callback) {
  33670. var element = walk(source, property, callback);
  33671. if (element === undef) {
  33672. delete source[property];
  33673. } else {
  33674. source[property] = element;
  33675. }
  33676. };
  33677. // Internal: Recursively traverses a parsed JSON object, invoking the
  33678. // `callback` function for each value. This is an implementation of the
  33679. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  33680. var walk = function (source, property, callback) {
  33681. var value = source[property], length;
  33682. if (typeof value == "object" && value) {
  33683. // `forEach` can't be used to traverse an array in Opera <= 8.54
  33684. // because its `Object#hasOwnProperty` implementation returns `false`
  33685. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  33686. if (getClass.call(value) == arrayClass) {
  33687. for (length = value.length; length--;) {
  33688. update(value, length, callback);
  33689. }
  33690. } else {
  33691. forEach(value, function (property) {
  33692. update(value, property, callback);
  33693. });
  33694. }
  33695. }
  33696. return callback.call(source, property, value);
  33697. };
  33698. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  33699. JSON3.parse = function (source, callback) {
  33700. var result, value;
  33701. Index = 0;
  33702. Source = "" + source;
  33703. result = get(lex());
  33704. // If a JSON string contains multiple tokens, it is invalid.
  33705. if (lex() != "$") {
  33706. abort();
  33707. }
  33708. // Reset the parser state.
  33709. Index = Source = null;
  33710. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  33711. };
  33712. }
  33713. }
  33714. // Export for asynchronous module loaders.
  33715. if (isLoader) {
  33716. define(function () {
  33717. return JSON3;
  33718. });
  33719. }
  33720. }(this));
  33721. },{}],163:[function(require,module,exports){
  33722. module.exports = toArray
  33723. function toArray(list, index) {
  33724. var array = []
  33725. index = index || 0
  33726. for (var i = index || 0; i < list.length; i++) {
  33727. array[i - index] = list[i]
  33728. }
  33729. return array
  33730. }
  33731. },{}],164:[function(require,module,exports){
  33732. var MediaStreamType = {
  33733. VIDEO_TYPE: "Video",
  33734. AUDIO_TYPE: "Audio"
  33735. };
  33736. module.exports = MediaStreamType;
  33737. },{}],165:[function(require,module,exports){
  33738. var RTCEvents = {
  33739. RTC_READY: "rtc.ready",
  33740. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  33741. LASTN_CHANGED: "rtc.lastn_changed",
  33742. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  33743. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  33744. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  33745. AUDIO_MUTE: "rtc.audio_mute",
  33746. VIDEO_MUTE: "rtc.video_mute"
  33747. };
  33748. module.exports = RTCEvents;
  33749. },{}],166:[function(require,module,exports){
  33750. var Resolutions = {
  33751. "1080": {
  33752. width: 1920,
  33753. height: 1080,
  33754. order: 7
  33755. },
  33756. "fullhd": {
  33757. width: 1920,
  33758. height: 1080,
  33759. order: 7
  33760. },
  33761. "720": {
  33762. width: 1280,
  33763. height: 720,
  33764. order: 6
  33765. },
  33766. "hd": {
  33767. width: 1280,
  33768. height: 720,
  33769. order: 6
  33770. },
  33771. "960": {
  33772. width: 960,
  33773. height: 720,
  33774. order: 5
  33775. },
  33776. "640": {
  33777. width: 640,
  33778. height: 480,
  33779. order: 4
  33780. },
  33781. "vga": {
  33782. width: 640,
  33783. height: 480,
  33784. order: 4
  33785. },
  33786. "360": {
  33787. width: 640,
  33788. height: 360,
  33789. order: 3
  33790. },
  33791. "320": {
  33792. width: 320,
  33793. height: 240,
  33794. order: 2
  33795. },
  33796. "180": {
  33797. width: 320,
  33798. height: 180,
  33799. order: 1
  33800. }
  33801. };
  33802. module.exports = Resolutions;
  33803. },{}],167:[function(require,module,exports){
  33804. var StreamEventTypes = {
  33805. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  33806. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  33807. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  33808. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  33809. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  33810. };
  33811. module.exports = StreamEventTypes;
  33812. },{}],168:[function(require,module,exports){
  33813. var UIEvents = {
  33814. NICKNAME_CHANGED: "UI.nickname_changed",
  33815. SELECTED_ENDPOINT: "UI.selected_endpoint",
  33816. PINNED_ENDPOINT: "UI.pinned_endpoint",
  33817. LARGEVIDEO_INIT: "UI.largevideo_init"
  33818. };
  33819. module.exports = UIEvents;
  33820. },{}],169:[function(require,module,exports){
  33821. var AuthenticationEvents = {
  33822. /**
  33823. * Event callback arguments:
  33824. * function(authenticationEnabled, userIdentity)
  33825. * authenticationEnabled - indicates whether authentication has been enabled
  33826. * in this session
  33827. * userIdentity - if user has been logged in then it contains user name. If
  33828. * contains 'null' or 'undefined' then user is not logged in.
  33829. */
  33830. IDENTITY_UPDATED: "authentication.identity_updated"
  33831. };
  33832. module.exports = AuthenticationEvents;
  33833. },{}],170:[function(require,module,exports){
  33834. var CQEvents = {
  33835. LOCALSTATS_UPDATED: "cq.localstats_updated",
  33836. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  33837. STOP: "cq.stop"
  33838. };
  33839. module.exports = CQEvents;
  33840. },{}],171:[function(require,module,exports){
  33841. var DesktopSharingEventTypes = {
  33842. INIT: "ds.init",
  33843. SWITCHING_DONE: "ds.switching_done",
  33844. NEW_STREAM_CREATED: "ds.new_stream_created"
  33845. };
  33846. module.exports = DesktopSharingEventTypes;
  33847. },{}],172:[function(require,module,exports){
  33848. var Events = {
  33849. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  33850. };
  33851. module.exports = Events;
  33852. },{}],173:[function(require,module,exports){
  33853. module.exports = {
  33854. getLanguages : function () {
  33855. var languages = [];
  33856. for(var lang in this)
  33857. {
  33858. if(typeof this[lang] === "string")
  33859. languages.push(this[lang]);
  33860. }
  33861. return languages;
  33862. },
  33863. EN: "en",
  33864. BG: "bg",
  33865. DE: "de",
  33866. TR: "tr",
  33867. FR: "fr"
  33868. }
  33869. },{}],174:[function(require,module,exports){
  33870. var XMPPEvents = {
  33871. // Designates an event indicating that the connection to the XMPP server
  33872. // failed.
  33873. CONNECTION_FAILED: "xmpp.connection.failed",
  33874. // Designates an event indicating that the media (ICE) connection was
  33875. // interrupted. This should go to the RTC module.
  33876. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  33877. // Designates an event indicating that the media (ICE) connection was
  33878. // restored. This should go to the RTC module.
  33879. CONNECTION_RESTORED: "xmpp.connection.restored",
  33880. // Designates an event indicating that an offer (e.g. Jingle
  33881. // session-initiate) was received.
  33882. CALL_INCOMING: "xmpp.callincoming.jingle",
  33883. // Designates an event indicating that we were kicked from the XMPP MUC.
  33884. KICKED: "xmpp.kicked",
  33885. // Designates an event indicating that the userID for a specific JID has
  33886. // changed.
  33887. USER_ID_CHANGED: "xmpp.user_id_changed",
  33888. // Designates an event indicating that we have joined the XMPP MUC.
  33889. MUC_JOINED: "xmpp.muc_joined",
  33890. // Designates an event indicating that a participant joined the XMPP MUC.
  33891. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  33892. // Designates an event indicating that a participant left the XMPP MUC.
  33893. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  33894. // Designates an event indicating that the MUC role of a participant has
  33895. // changed.
  33896. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  33897. // Designates an event indicating that the XMPP MUC was destroyed.
  33898. MUC_DESTROYED: "xmpp.muc_destroyed",
  33899. // Designates an event indicating that the display name of a participant
  33900. // has changed.
  33901. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  33902. // Designates an event indicating that we received statistics from a
  33903. // participant in the MUC.
  33904. REMOTE_STATS: "xmpp.remote_stats",
  33905. // Designates an event indicating that our role in the XMPP MUC has changed.
  33906. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  33907. // Designates an event indicating that the subject of the XMPP MUC has
  33908. // changed.
  33909. SUBJECT_CHANGED: "xmpp.subject_changed",
  33910. // Designates an event indicating that an XMPP message in the MUC was
  33911. // received.
  33912. MESSAGE_RECEIVED: "xmpp.message_received",
  33913. // Designates an event indicating that we sent an XMPP message to the MUC.
  33914. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  33915. // Designates an event indicating that the video type (e.g. 'camera' or
  33916. // 'screen') for a participant has changed.
  33917. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  33918. // Designates an event indicating that a participant in the XMPP MUC has
  33919. // advertised that they have audio muted (or unmuted).
  33920. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  33921. // Designates an event indicating that a participant in the XMPP MUC has
  33922. // advertised that they have video muted (or unmuted).
  33923. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  33924. // Designates an event indicating that the focus has asked us to mute our
  33925. // audio.
  33926. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  33927. // Designates an event indicating that a moderator in the room changed the
  33928. // "start muted" settings for the conference.
  33929. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  33930. // Designates an event indicating that we should join the conference with
  33931. // audio and/or video muted.
  33932. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  33933. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  33934. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  33935. PASSWORD_REQUIRED: "xmpp.password_required",
  33936. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  33937. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  33938. ETHERPAD: "xmpp.etherpad",
  33939. DEVICE_AVAILABLE: "xmpp.device_available",
  33940. BRIDGE_DOWN: "xmpp.bridge_down",
  33941. PRESENCE_STATUS: "xmpp.presence_status",
  33942. RESERVATION_ERROR: "xmpp.room_reservation_error",
  33943. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  33944. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  33945. // TODO: only used in a hack, should probably be removed.
  33946. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  33947. // TODO: only used in a hack, should probably be removed.
  33948. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  33949. // TODO: only used in a hack, should probably be removed.
  33950. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  33951. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  33952. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  33953. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  33954. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  33955. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  33956. // xmpp is connected and obtained user media
  33957. READY_TO_JOIN: 'xmpp.ready_to_join'
  33958. };
  33959. module.exports = XMPPEvents;
  33960. },{}]},{},[3])(3)
  33961. });