選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

app.bundle.js 1.2MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452
  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. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  13. this.xmpp = require("./modules/xmpp/xmpp");
  14. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  15. this.translation = require("./modules/translation/translation");
  16. this.settings = require("./modules/settings/Settings");
  17. this.DTMF = require("./modules/DTMF/DTMF");
  18. this.members = require("./modules/members/MemberList");
  19. }
  20. };
  21. function init() {
  22. APP.desktopsharing.init();
  23. APP.RTC.start();
  24. APP.xmpp.start();
  25. APP.statistics.start();
  26. APP.connectionquality.init();
  27. APP.keyboardshortcut.init();
  28. APP.members.start();
  29. }
  30. $(document).ready(function () {
  31. var URLProcessor = require("./modules/URLProcessor/URLProcessor");
  32. URLProcessor.setConfigParametersFromUrl();
  33. APP.init();
  34. APP.translation.init();
  35. if(APP.API.isEnabled())
  36. APP.API.init();
  37. APP.UI.start(init);
  38. });
  39. $(window).bind('beforeunload', function () {
  40. if(APP.API.isEnabled())
  41. APP.API.dispose();
  42. });
  43. module.exports = APP;
  44. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":11,"./modules/URLProcessor/URLProcessor":42,"./modules/connectionquality/connectionquality":43,"./modules/desktopsharing/desktopsharing":44,"./modules/keyboardshortcut/keyboardshortcut":45,"./modules/members/MemberList":46,"./modules/settings/Settings":47,"./modules/statistics/statistics":51,"./modules/translation/translation":52,"./modules/xmpp/xmpp":68}],2:[function(require,module,exports){
  45. /* global APP */
  46. /**
  47. * Implements API class that communicates with external api class
  48. * and provides interface to access Jitsi Meet features by external
  49. * applications that embed Jitsi Meet
  50. */
  51. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  52. /**
  53. * List of the available commands.
  54. * @type {{
  55. * displayName: inputDisplayNameHandler,
  56. * toggleAudio: toggleAudio,
  57. * toggleVideo: toggleVideo,
  58. * toggleFilmStrip: toggleFilmStrip,
  59. * toggleChat: toggleChat,
  60. * toggleContactList: toggleContactList
  61. * }}
  62. */
  63. var commands = {};
  64. function initCommands() {
  65. commands = {
  66. displayName: APP.UI.inputDisplayNameHandler,
  67. toggleAudio: APP.UI.toggleAudio,
  68. toggleVideo: APP.UI.toggleVideo,
  69. toggleFilmStrip: APP.UI.toggleFilmStrip,
  70. toggleChat: APP.UI.toggleChat,
  71. toggleContactList: APP.UI.toggleContactList
  72. };
  73. }
  74. /**
  75. * Maps the supported events and their status
  76. * (true it the event is enabled and false if it is disabled)
  77. * @type {{
  78. * incomingMessage: boolean,
  79. * outgoingMessage: boolean,
  80. * displayNameChange: boolean,
  81. * participantJoined: boolean,
  82. * participantLeft: boolean
  83. * }}
  84. */
  85. var events = {
  86. incomingMessage: false,
  87. outgoingMessage:false,
  88. displayNameChange: false,
  89. participantJoined: false,
  90. participantLeft: false
  91. };
  92. var displayName = {};
  93. /**
  94. * Processes commands from external application.
  95. * @param message the object with the command
  96. */
  97. function processCommand(message) {
  98. if (message.action != "execute") {
  99. console.error("Unknown action of the message");
  100. return;
  101. }
  102. for (var key in message) {
  103. if(commands[key])
  104. commands[key].apply(null, message[key]);
  105. }
  106. }
  107. /**
  108. * Processes events objects from external applications
  109. * @param event the event
  110. */
  111. function processEvent(event) {
  112. if (!event.action) {
  113. console.error("Event with no action is received.");
  114. return;
  115. }
  116. var i = 0;
  117. switch(event.action) {
  118. case "add":
  119. for (; i < event.events.length; i++) {
  120. events[event.events[i]] = true;
  121. }
  122. break;
  123. case "remove":
  124. for (; i < event.events.length; i++) {
  125. events[event.events[i]] = false;
  126. }
  127. break;
  128. default:
  129. console.error("Unknown action for event.");
  130. }
  131. }
  132. /**
  133. * Sends message to the external application.
  134. * @param object
  135. */
  136. function sendMessage(object) {
  137. window.parent.postMessage(JSON.stringify(object), "*");
  138. }
  139. /**
  140. * Processes a message event from the external application
  141. * @param event the message event
  142. */
  143. function processMessage(event) {
  144. var message;
  145. try {
  146. message = JSON.parse(event.data);
  147. } catch (e) {}
  148. if(!message.type)
  149. return;
  150. switch (message.type) {
  151. case "command":
  152. processCommand(message);
  153. break;
  154. case "event":
  155. processEvent(message);
  156. break;
  157. default:
  158. console.error("Unknown type of the message");
  159. return;
  160. }
  161. }
  162. function setupListeners() {
  163. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  164. API.triggerEvent("participantJoined", {jid: from});
  165. });
  166. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  167. if (from != myjid)
  168. API.triggerEvent("incomingMessage",
  169. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  170. });
  171. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  172. API.triggerEvent("participantLeft", {jid: jid});
  173. });
  174. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  175. var name = displayName[jid];
  176. if(!name || name != newDisplayName) {
  177. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  178. displayName[jid] = newDisplayName;
  179. }
  180. });
  181. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  182. APP.API.triggerEvent("outgoingMessage", {"message": body});
  183. });
  184. }
  185. var API = {
  186. /**
  187. * Check whether the API should be enabled or not.
  188. * @returns {boolean}
  189. */
  190. isEnabled: function () {
  191. var hash = location.hash;
  192. if (hash && hash.indexOf("external") > -1 && window.postMessage)
  193. return true;
  194. return false;
  195. },
  196. /**
  197. * Initializes the APIConnector. Setups message event listeners that will
  198. * receive information from external applications that embed Jitsi Meet.
  199. * It also sends a message to the external application that APIConnector
  200. * is initialized.
  201. */
  202. init: function () {
  203. initCommands();
  204. if (window.addEventListener) {
  205. window.addEventListener('message',
  206. processMessage, false);
  207. }
  208. else {
  209. window.attachEvent('onmessage', processMessage);
  210. }
  211. sendMessage({type: "system", loaded: true});
  212. setupListeners();
  213. },
  214. /**
  215. * Checks whether the event is enabled ot not.
  216. * @param name the name of the event.
  217. * @returns {*}
  218. */
  219. isEventEnabled: function (name) {
  220. return events[name];
  221. },
  222. /**
  223. * Sends event object to the external application that has been subscribed
  224. * for that event.
  225. * @param name the name event
  226. * @param object data associated with the event
  227. */
  228. triggerEvent: function (name, object) {
  229. if(this.isEnabled() && this.isEventEnabled(name))
  230. sendMessage({
  231. type: "event", action: "result", event: name, result: object});
  232. },
  233. /**
  234. * Removes the listeners.
  235. */
  236. dispose: function () {
  237. if(window.removeEventListener) {
  238. window.removeEventListener("message",
  239. processMessage, false);
  240. }
  241. else {
  242. window.detachEvent('onmessage', processMessage);
  243. }
  244. }
  245. };
  246. module.exports = API;
  247. },{"../../service/xmpp/XMPPEvents":169}],3:[function(require,module,exports){
  248. /* global APP */
  249. /**
  250. * A module for sending DTMF tones.
  251. */
  252. var DTMFSender;
  253. var initDtmfSender = function() {
  254. // TODO: This needs to reset this if the peerconnection changes
  255. // (e.g. the call is re-made)
  256. if (DTMFSender)
  257. return;
  258. var localAudio = APP.RTC.localAudio;
  259. if (localAudio && localAudio.getTracks().length > 0)
  260. {
  261. var peerconnection
  262. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  263. if (peerconnection) {
  264. DTMFSender =
  265. peerconnection.peerconnection
  266. .createDTMFSender(localAudio.getTracks()[0]);
  267. console.log("Initialized DTMFSender");
  268. }
  269. else {
  270. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  271. }
  272. }
  273. else {
  274. console.log("Failed to initialize DTMFSender: no audio track.");
  275. }
  276. };
  277. var DTMF = {
  278. sendTones: function (tones, duration, pause) {
  279. if (!DTMFSender)
  280. initDtmfSender();
  281. if (DTMFSender){
  282. DTMFSender.insertDTMF(tones,
  283. (duration || 200),
  284. (pause || 200));
  285. }
  286. }
  287. };
  288. module.exports = DTMF;
  289. },{}],4:[function(require,module,exports){
  290. /* global config, APP, Strophe */
  291. // cache datachannels to avoid garbage collection
  292. // https://code.google.com/p/chromium/issues/detail?id=405545
  293. var RTCEvents = require("../../service/RTC/RTCEvents");
  294. var _dataChannels = [];
  295. var eventEmitter = null;
  296. var DataChannels = {
  297. /**
  298. * Callback triggered by PeerConnection when new data channel is opened
  299. * on the bridge.
  300. * @param event the event info object.
  301. */
  302. onDataChannel: function (event) {
  303. var dataChannel = event.channel;
  304. dataChannel.onopen = function () {
  305. console.info("Data channel opened by the Videobridge!", dataChannel);
  306. // Code sample for sending string and/or binary data
  307. // Sends String message to the bridge
  308. //dataChannel.send("Hello bridge!");
  309. // Sends 12 bytes binary message to the bridge
  310. //dataChannel.send(new ArrayBuffer(12));
  311. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  312. };
  313. dataChannel.onerror = function (error) {
  314. console.error("Data Channel Error:", error, dataChannel);
  315. };
  316. dataChannel.onmessage = function (event) {
  317. var data = event.data;
  318. // JSON
  319. var obj;
  320. try {
  321. obj = JSON.parse(data);
  322. }
  323. catch (e) {
  324. console.error(
  325. "Failed to parse data channel message as JSON: ",
  326. data,
  327. dataChannel);
  328. }
  329. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  330. var colibriClass = obj.colibriClass;
  331. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  332. // Endpoint ID from the Videobridge.
  333. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  334. console.info(
  335. "Data channel new dominant speaker event: ",
  336. dominantSpeakerEndpoint);
  337. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  338. }
  339. else if ("InLastNChangeEvent" === colibriClass) {
  340. var oldValue = obj.oldValue;
  341. var newValue = obj.newValue;
  342. // Make sure that oldValue and newValue are of type boolean.
  343. var type;
  344. if ((type = typeof oldValue) !== 'boolean') {
  345. if (type === 'string') {
  346. oldValue = (oldValue == "true");
  347. } else {
  348. oldValue = new Boolean(oldValue).valueOf();
  349. }
  350. }
  351. if ((type = typeof newValue) !== 'boolean') {
  352. if (type === 'string') {
  353. newValue = (newValue == "true");
  354. } else {
  355. newValue = new Boolean(newValue).valueOf();
  356. }
  357. }
  358. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  359. }
  360. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  361. // The new/latest list of last-n endpoint IDs.
  362. var lastNEndpoints = obj.lastNEndpoints;
  363. // The list of endpoint IDs which are entering the list of
  364. // last-n at this time i.e. were not in the old list of last-n
  365. // endpoint IDs.
  366. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  367. console.log(
  368. "Data channel new last-n event: ",
  369. lastNEndpoints, endpointsEnteringLastN, obj);
  370. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  371. lastNEndpoints, endpointsEnteringLastN, obj);
  372. }
  373. else {
  374. console.debug("Data channel JSON-formatted message: ", obj);
  375. }
  376. }
  377. };
  378. dataChannel.onclose = function () {
  379. console.info("The Data Channel closed", dataChannel);
  380. var idx = _dataChannels.indexOf(dataChannel);
  381. if (idx > -1)
  382. _dataChannels = _dataChannels.splice(idx, 1);
  383. };
  384. _dataChannels.push(dataChannel);
  385. },
  386. /**
  387. * Binds "ondatachannel" event listener to given PeerConnection instance.
  388. * @param peerConnection WebRTC peer connection instance.
  389. */
  390. init: function (peerConnection, emitter) {
  391. if(!config.openSctp)
  392. return;
  393. peerConnection.ondatachannel = this.onDataChannel;
  394. eventEmitter = emitter;
  395. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  396. // Although it's not a requirement to open separate channels from both bridge
  397. // and peer as single channel can be used for sending and receiving data.
  398. // So either channel opened by the bridge or the one opened here is enough
  399. // for communication with the bridge.
  400. /*var dataChannelOptions =
  401. {
  402. reliable: true
  403. };
  404. var dataChannel
  405. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  406. // Can be used only when is in open state
  407. dataChannel.onopen = function ()
  408. {
  409. dataChannel.send("My channel !!!");
  410. };
  411. dataChannel.onmessage = function (event)
  412. {
  413. var msgData = event.data;
  414. console.info("Got My Data Channel Message:", msgData, dataChannel);
  415. };*/
  416. },
  417. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  418. handlePinnedEndpointEvent: onPinnedEndpointChanged
  419. };
  420. function onSelectedEndpointChanged(userResource) {
  421. console.log('selected endpoint changed: ', userResource);
  422. if (_dataChannels && _dataChannels.length != 0) {
  423. _dataChannels.some(function (dataChannel) {
  424. if (dataChannel.readyState == 'open') {
  425. console.log('sending selected endpoint changed ' +
  426. 'notification to the bridge: ', userResource);
  427. dataChannel.send(JSON.stringify({
  428. 'colibriClass': 'SelectedEndpointChangedEvent',
  429. 'selectedEndpoint':
  430. (!userResource || userResource === null)?
  431. null : userResource
  432. }));
  433. return true;
  434. }
  435. });
  436. }
  437. }
  438. function onPinnedEndpointChanged(userResource) {
  439. console.log('pinned endpoint changed: ', userResource);
  440. if (_dataChannels && _dataChannels.length != 0) {
  441. _dataChannels.some(function (dataChannel) {
  442. if (dataChannel.readyState == 'open') {
  443. dataChannel.send(JSON.stringify({
  444. 'colibriClass': 'PinnedEndpointChangedEvent',
  445. 'pinnedEndpoint':
  446. (!userResource || userResource == null)?
  447. null : userResource
  448. }));
  449. return true;
  450. }
  451. });
  452. }
  453. }
  454. module.exports = DataChannels;
  455. },{"../../service/RTC/RTCEvents":160}],5:[function(require,module,exports){
  456. /* global APP */
  457. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  458. var RTCEvents = require("../../service/RTC/RTCEvents");
  459. var RTCBrowserType = require("./RTCBrowserType");
  460. /**
  461. * This implements 'onended' callback normally fired by WebRTC after the stream
  462. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  463. * @param stream original WebRTC stream object to which 'onended' handling
  464. * will be added.
  465. */
  466. function implementOnEndedHandling(stream) {
  467. var originalStop = stream.stop;
  468. stream.stop = function () {
  469. originalStop.apply(stream);
  470. if (!stream.ended) {
  471. stream.ended = true;
  472. stream.onended();
  473. }
  474. };
  475. }
  476. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  477. this.stream = stream;
  478. this.eventEmitter = eventEmitter;
  479. this.type = type;
  480. this.videoType = videoType;
  481. this.isGUMStream = true;
  482. if(isGUMStream === false)
  483. this.isGUMStream = isGUMStream;
  484. var self = this;
  485. if(type == "audio") {
  486. this.getTracks = function () {
  487. return self.stream.getAudioTracks();
  488. };
  489. } else {
  490. this.getTracks = function () {
  491. return self.stream.getVideoTracks();
  492. };
  493. }
  494. this.stream.onended = function () {
  495. self.streamEnded();
  496. };
  497. if (RTCBrowserType.isFirefox()) {
  498. implementOnEndedHandling(this.stream);
  499. }
  500. }
  501. LocalStream.prototype.streamEnded = function () {
  502. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  503. };
  504. LocalStream.prototype.getOriginalStream = function()
  505. {
  506. return this.stream;
  507. };
  508. LocalStream.prototype.isAudioStream = function () {
  509. return this.type === "audio";
  510. };
  511. LocalStream.prototype.setMute = function (mute)
  512. {
  513. var isAudio = this.isAudioStream();
  514. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  515. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  516. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  517. // FIXME FF does not support 'removeStream' method used to mute
  518. RTCBrowserType.isFirefox()) {
  519. var tracks = this.getTracks();
  520. for (var idx = 0; idx < tracks.length; idx++) {
  521. tracks[idx].enabled = !mute;
  522. }
  523. this.eventEmitter.emit(eventType, mute);
  524. } else {
  525. if (mute) {
  526. APP.xmpp.removeStream(this.stream);
  527. this.stream.stop();
  528. this.eventEmitter.emit(eventType, true);
  529. } else {
  530. var self = this;
  531. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  532. (this.isAudioStream() ? ["audio"] : ["video"]),
  533. function (stream) {
  534. if (isAudio) {
  535. APP.RTC.changeLocalAudio(stream,
  536. function () {
  537. self.eventEmitter.emit(eventType, false);
  538. });
  539. } else {
  540. APP.RTC.changeLocalVideo(stream, false,
  541. function () {
  542. self.eventEmitter.emit(eventType, false);
  543. });
  544. }
  545. });
  546. }
  547. }
  548. };
  549. LocalStream.prototype.isMuted = function () {
  550. var tracks = [];
  551. if (this.isAudioStream()) {
  552. tracks = this.stream.getAudioTracks();
  553. } else {
  554. if (this.stream.ended)
  555. return true;
  556. tracks = this.stream.getVideoTracks();
  557. }
  558. for (var idx = 0; idx < tracks.length; idx++) {
  559. if(tracks[idx].enabled)
  560. return false;
  561. }
  562. return true;
  563. };
  564. LocalStream.prototype.getId = function () {
  565. return this.stream.getTracks()[0].id;
  566. };
  567. module.exports = LocalStream;
  568. },{"../../service/RTC/RTCEvents":160,"../../service/RTC/StreamEventTypes.js":162,"./RTCBrowserType":8}],6:[function(require,module,exports){
  569. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  570. /**
  571. * Creates a MediaStream object for the given data, session id and ssrc.
  572. * It is a wrapper class for the MediaStream.
  573. *
  574. * @param data the data object from which we obtain the stream,
  575. * the peerjid, etc.
  576. * @param sid the session id
  577. * @param ssrc the ssrc corresponding to this MediaStream
  578. *
  579. * @constructor
  580. */
  581. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  582. // XXX(gp) to minimize headaches in the future, we should build our
  583. // abstractions around tracks and not streams. ORTC is track based API.
  584. // Mozilla expects m-lines to represent media tracks.
  585. //
  586. // Practically, what I'm saying is that we should have a MediaTrack class
  587. // and not a MediaStream class.
  588. //
  589. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  590. // a track might have an associated RTX and FEC sources.
  591. this.sid = sid;
  592. this.stream = data.stream;
  593. this.peerjid = data.peerjid;
  594. this.videoType = data.videoType;
  595. this.ssrc = ssrc;
  596. this.type = (this.stream.getVideoTracks().length > 0)?
  597. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  598. this.muted = false;
  599. this.eventEmitter = eventEmitter;
  600. }
  601. MediaStream.prototype.getOriginalStream = function() {
  602. return this.stream;
  603. };
  604. MediaStream.prototype.setMute = function (value) {
  605. this.stream.muted = value;
  606. this.muted = value;
  607. };
  608. module.exports = MediaStream;
  609. },{"../../service/RTC/MediaStreamTypes":159}],7:[function(require,module,exports){
  610. /* global APP */
  611. var EventEmitter = require("events");
  612. var RTCBrowserType = require("./RTCBrowserType");
  613. var RTCUtils = require("./RTCUtils.js");
  614. var LocalStream = require("./LocalStream.js");
  615. var DataChannels = require("./DataChannels");
  616. var MediaStream = require("./MediaStream.js");
  617. var DesktopSharingEventTypes
  618. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  619. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  620. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  621. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  622. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  623. var UIEvents = require("../../service/UI/UIEvents");
  624. var eventEmitter = new EventEmitter();
  625. function getMediaStreamUsage()
  626. {
  627. var result = {
  628. audio: true,
  629. video: true
  630. };
  631. /** There are some issues with the desktop sharing
  632. * when this property is enabled.
  633. * WARNING: We must change the implementation to start video/audio if we
  634. * receive from the focus that the peer is not muted.
  635. var isSecureConnection = window.location.protocol == "https:";
  636. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  637. {
  638. result = {
  639. audio: false,
  640. video: false
  641. };
  642. }
  643. **/
  644. return result;
  645. }
  646. var RTC = {
  647. rtcUtils: null,
  648. devices: {
  649. audio: true,
  650. video: true
  651. },
  652. localStreams: [],
  653. remoteStreams: {},
  654. localAudio: null,
  655. localVideo: null,
  656. addStreamListener: function (listener, eventType) {
  657. eventEmitter.on(eventType, listener);
  658. },
  659. addListener: function (type, listener) {
  660. eventEmitter.on(type, listener);
  661. },
  662. removeStreamListener: function (listener, eventType) {
  663. if(!(eventType instanceof StreamEventTypes))
  664. throw "Illegal argument";
  665. eventEmitter.removeListener(eventType, listener);
  666. },
  667. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  668. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  669. //in firefox we have only one stream object
  670. if(this.localStreams.length == 0 ||
  671. this.localStreams[0].getOriginalStream() != stream)
  672. this.localStreams.push(localStream);
  673. if(isMuted === true)
  674. localStream.setMute(true);
  675. if(type == "audio") {
  676. this.localAudio = localStream;
  677. } else {
  678. this.localVideo = localStream;
  679. }
  680. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  681. if(change)
  682. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  683. eventEmitter.emit(eventType, localStream, isMuted);
  684. return localStream;
  685. },
  686. removeLocalStream: function (stream) {
  687. for(var i = 0; i < this.localStreams.length; i++) {
  688. if(this.localStreams[i].getOriginalStream() === stream) {
  689. delete this.localStreams[i];
  690. return;
  691. }
  692. }
  693. },
  694. createRemoteStream: function (data, sid, thessrc) {
  695. var remoteStream = new MediaStream(data, sid, thessrc,
  696. RTCBrowserType.getBrowserType(), eventEmitter);
  697. var jid = data.peerjid || APP.xmpp.myJid();
  698. if(!this.remoteStreams[jid]) {
  699. this.remoteStreams[jid] = {};
  700. }
  701. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  702. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  703. return remoteStream;
  704. },
  705. getPCConstraints: function () {
  706. return this.rtcUtils.pc_constraints;
  707. },
  708. getUserMediaWithConstraints:function(um, success_callback,
  709. failure_callback, resolution,
  710. bandwidth, fps, desktopStream)
  711. {
  712. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  713. failure_callback, resolution, bandwidth, fps, desktopStream);
  714. },
  715. attachMediaStream: function (elSelector, stream) {
  716. this.rtcUtils.attachMediaStream(elSelector, stream);
  717. },
  718. getStreamID: function (stream) {
  719. return this.rtcUtils.getStreamID(stream);
  720. },
  721. getVideoSrc: function (element) {
  722. return this.rtcUtils.getVideoSrc(element);
  723. },
  724. setVideoSrc: function (element, src) {
  725. this.rtcUtils.setVideoSrc(element, src);
  726. },
  727. getVideoElementName: function () {
  728. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  729. },
  730. dispose: function() {
  731. if (this.rtcUtils) {
  732. this.rtcUtils = null;
  733. }
  734. },
  735. stop: function () {
  736. this.dispose();
  737. },
  738. start: function () {
  739. var self = this;
  740. APP.desktopsharing.addListener(
  741. function (stream, isUsingScreenStream, callback) {
  742. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  743. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  744. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  745. DataChannels.init(event.peerconnection, eventEmitter);
  746. });
  747. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  748. DataChannels.handleSelectedEndpointEvent);
  749. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  750. DataChannels.handlePinnedEndpointEvent);
  751. // In case of IE we continue from 'onReady' callback
  752. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  753. // once it is initialized.
  754. var onReady = function () {
  755. eventEmitter.emit(RTCEvents.RTC_READY, true);
  756. self.rtcUtils.obtainAudioAndVideoPermissions(
  757. null, null, getMediaStreamUsage());
  758. };
  759. this.rtcUtils = new RTCUtils(this, onReady);
  760. // Call onReady() if Temasys plugin is not used
  761. if (!RTCBrowserType.isTemasysPluginUsed()) {
  762. onReady();
  763. }
  764. },
  765. muteRemoteVideoStream: function (jid, value) {
  766. var stream;
  767. if(this.remoteStreams[jid] &&
  768. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  769. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  770. }
  771. if(!stream)
  772. return true;
  773. if (value != stream.muted) {
  774. stream.setMute(value);
  775. return true;
  776. }
  777. return false;
  778. },
  779. switchVideoStreams: function (new_stream) {
  780. this.localVideo.stream = new_stream;
  781. this.localStreams = [];
  782. //in firefox we have only one stream object
  783. if (this.localAudio.getOriginalStream() != new_stream)
  784. this.localStreams.push(this.localAudio);
  785. this.localStreams.push(this.localVideo);
  786. },
  787. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  788. var oldStream = this.localVideo.getOriginalStream();
  789. var type = (isUsingScreenStream ? "screen" : "camera");
  790. var localCallback = callback;
  791. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  792. localCallback = function() {
  793. APP.xmpp.setVideoMute(false, function(mute) {
  794. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  795. });
  796. callback();
  797. };
  798. }
  799. // FIXME: Workaround for FF/IE/Safari
  800. if (stream && stream.videoStream) {
  801. stream = stream.videoStream;
  802. }
  803. var videoStream = this.rtcUtils.createStream(stream, true);
  804. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  805. // Stop the stream to trigger onended event for old stream
  806. oldStream.stop();
  807. this.switchVideoStreams(videoStream, oldStream);
  808. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  809. },
  810. changeLocalAudio: function (stream, callback) {
  811. var oldStream = this.localAudio.getOriginalStream();
  812. var newStream = this.rtcUtils.createStream(stream);
  813. this.localAudio = this.createLocalStream(newStream, "audio", true);
  814. // Stop the stream to trigger onended event for old stream
  815. oldStream.stop();
  816. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  817. },
  818. isVideoMuted: function (jid) {
  819. if (jid === APP.xmpp.myJid()) {
  820. var localVideo = APP.RTC.localVideo;
  821. return (!localVideo || localVideo.isMuted());
  822. } else {
  823. if (!APP.RTC.remoteStreams[jid] ||
  824. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  825. return null;
  826. }
  827. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  828. }
  829. },
  830. setVideoMute: function (mute, callback, options) {
  831. if (!this.localVideo)
  832. return;
  833. if (mute == APP.RTC.localVideo.isMuted())
  834. {
  835. APP.xmpp.sendVideoInfoPresence(mute);
  836. if (callback)
  837. callback(mute);
  838. }
  839. else
  840. {
  841. APP.RTC.localVideo.setMute(mute);
  842. APP.xmpp.setVideoMute(
  843. mute,
  844. callback,
  845. options);
  846. }
  847. },
  848. setDeviceAvailability: function (devices) {
  849. if(!devices)
  850. return;
  851. if(devices.audio === true || devices.audio === false)
  852. this.devices.audio = devices.audio;
  853. if(devices.video === true || devices.video === false)
  854. this.devices.video = devices.video;
  855. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  856. }
  857. };
  858. module.exports = RTC;
  859. },{"../../service/RTC/MediaStreamTypes":159,"../../service/RTC/RTCEvents.js":160,"../../service/RTC/StreamEventTypes.js":162,"../../service/UI/UIEvents":163,"../../service/desktopsharing/DesktopSharingEventTypes":166,"../../service/xmpp/XMPPEvents":169,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":170}],8:[function(require,module,exports){
  860. var currentBrowser;
  861. var browserVersion;
  862. var isAndroid;
  863. var RTCBrowserType = {
  864. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  865. RTC_BROWSER_OPERA: "rtc_browser.opera",
  866. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  867. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  868. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  869. getBrowserType: function () {
  870. return currentBrowser;
  871. },
  872. isChrome: function () {
  873. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  874. },
  875. isOpera: function () {
  876. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  877. },
  878. isFirefox: function () {
  879. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  880. },
  881. isIExplorer: function () {
  882. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  883. },
  884. isSafari: function () {
  885. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  886. },
  887. isTemasysPluginUsed: function () {
  888. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  889. },
  890. getFirefoxVersion: function () {
  891. return RTCBrowserType.isFirefox() ? browserVersion : null;
  892. },
  893. getChromeVersion: function () {
  894. return RTCBrowserType.isChrome() ? browserVersion : null;
  895. },
  896. usesPlanB: function() {
  897. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  898. RTCBrowserType.isTemasysPluginUsed();
  899. },
  900. usesUnifiedPlan: function() {
  901. return RTCBrowserType.isFirefox();
  902. },
  903. /**
  904. * Whether the browser is running on an android device.
  905. */
  906. isAndroid: function() {
  907. return isAndroid;
  908. }
  909. // Add version getters for other browsers when needed
  910. };
  911. // detectOpera() must be called before detectChrome() !!!
  912. // otherwise Opera wil be detected as Chrome
  913. function detectChrome() {
  914. if (navigator.webkitGetUserMedia) {
  915. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  916. var userAgent = navigator.userAgent.toLowerCase();
  917. // We can assume that user agent is chrome, because it's
  918. // enforced when 'ext' streaming method is set
  919. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  920. console.log("This appears to be Chrome, ver: " + ver);
  921. return ver;
  922. }
  923. return null;
  924. }
  925. function detectOpera() {
  926. var userAgent = navigator.userAgent;
  927. if (userAgent.match(/Opera|OPR/)) {
  928. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  929. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  930. console.info("This appears to be Opera, ver: " + version);
  931. return version;
  932. }
  933. return null;
  934. }
  935. function detectFirefox() {
  936. if (navigator.mozGetUserMedia) {
  937. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  938. var version = parseInt(
  939. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  940. console.log('This appears to be Firefox, ver: ' + version);
  941. return version;
  942. }
  943. return null;
  944. }
  945. function detectSafari() {
  946. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  947. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  948. console.info("This appears to be Safari");
  949. // FIXME detect Safari version when needed
  950. return 1;
  951. }
  952. return null;
  953. }
  954. function detectIE() {
  955. var version;
  956. var ua = window.navigator.userAgent;
  957. var msie = ua.indexOf('MSIE ');
  958. if (msie > 0) {
  959. // IE 10 or older => return version number
  960. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  961. }
  962. var trident = ua.indexOf('Trident/');
  963. if (!version && trident > 0) {
  964. // IE 11 => return version number
  965. var rv = ua.indexOf('rv:');
  966. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  967. }
  968. var edge = ua.indexOf('Edge/');
  969. if (!version && edge > 0) {
  970. // IE 12 => return version number
  971. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  972. }
  973. if (version) {
  974. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  975. console.info("This appears to be IExplorer, ver: " + version);
  976. }
  977. return version;
  978. }
  979. function detectBrowser() {
  980. var version;
  981. var detectors = [
  982. detectOpera,
  983. detectChrome,
  984. detectFirefox,
  985. detectIE,
  986. detectSafari
  987. ];
  988. // Try all browser detectors
  989. for (var i = 0; i < detectors.length; i++) {
  990. version = detectors[i]();
  991. if (version)
  992. return version;
  993. }
  994. console.error("Failed to detect browser type");
  995. return undefined;
  996. }
  997. browserVersion = detectBrowser();
  998. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  999. module.exports = RTCBrowserType;
  1000. },{}],9:[function(require,module,exports){
  1001. /* global config, require, attachMediaStream, getUserMedia */
  1002. var RTCBrowserType = require("./RTCBrowserType");
  1003. var Resolutions = require("../../service/RTC/Resolutions");
  1004. var AdapterJS = require("./adapter.screenshare");
  1005. var SDPUtil = require("../xmpp/SDPUtil");
  1006. var currentResolution = null;
  1007. function getPreviousResolution(resolution) {
  1008. if(!Resolutions[resolution])
  1009. return null;
  1010. var order = Resolutions[resolution].order;
  1011. var res = null;
  1012. var resName = null;
  1013. for(var i in Resolutions) {
  1014. var tmp = Resolutions[i];
  1015. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1016. resName = i;
  1017. res = tmp;
  1018. }
  1019. }
  1020. return resName;
  1021. }
  1022. function setResolutionConstraints(constraints, resolution) {
  1023. var isAndroid = RTCBrowserType.isAndroid();
  1024. if (Resolutions[resolution]) {
  1025. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1026. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1027. }
  1028. else if (isAndroid) {
  1029. // FIXME can't remember if the purpose of this was to always request
  1030. // low resolution on Android ? if yes it should be moved up front
  1031. constraints.video.mandatory.minWidth = 320;
  1032. constraints.video.mandatory.minHeight = 240;
  1033. constraints.video.mandatory.maxFrameRate = 15;
  1034. }
  1035. if (constraints.video.mandatory.minWidth)
  1036. constraints.video.mandatory.maxWidth =
  1037. constraints.video.mandatory.minWidth;
  1038. if (constraints.video.mandatory.minHeight)
  1039. constraints.video.mandatory.maxHeight =
  1040. constraints.video.mandatory.minHeight;
  1041. }
  1042. function getConstraints(um, resolution, bandwidth, fps, desktopStream) {
  1043. var constraints = {audio: false, video: false};
  1044. if (um.indexOf('video') >= 0) {
  1045. // same behaviour as true
  1046. constraints.video = { mandatory: {}, optional: [] };
  1047. constraints.video.optional.push({ googLeakyBucket: true });
  1048. setResolutionConstraints(constraints, resolution);
  1049. }
  1050. if (um.indexOf('audio') >= 0) {
  1051. if (!RTCBrowserType.isFirefox()) {
  1052. // same behaviour as true
  1053. constraints.audio = { mandatory: {}, optional: []};
  1054. // if it is good enough for hangouts...
  1055. constraints.audio.optional.push(
  1056. {googEchoCancellation: true},
  1057. {googAutoGainControl: true},
  1058. {googNoiseSupression: true},
  1059. {googHighpassFilter: true},
  1060. {googNoisesuppression2: true},
  1061. {googEchoCancellation2: true},
  1062. {googAutoGainControl2: true}
  1063. );
  1064. } else {
  1065. constraints.audio = true;
  1066. }
  1067. }
  1068. if (um.indexOf('screen') >= 0) {
  1069. if (RTCBrowserType.isChrome()) {
  1070. constraints.video = {
  1071. mandatory: {
  1072. chromeMediaSource: "screen",
  1073. googLeakyBucket: true,
  1074. maxWidth: window.screen.width,
  1075. maxHeight: window.screen.height,
  1076. maxFrameRate: 3
  1077. },
  1078. optional: []
  1079. };
  1080. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1081. constraints.video = {
  1082. optional: [
  1083. {
  1084. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1085. }
  1086. ]
  1087. };
  1088. } else {
  1089. console.error(
  1090. "'screen' WebRTC media source is supported only in Chrome" +
  1091. " and with Temasys plugin");
  1092. }
  1093. }
  1094. if (um.indexOf('desktop') >= 0) {
  1095. constraints.video = {
  1096. mandatory: {
  1097. chromeMediaSource: "desktop",
  1098. chromeMediaSourceId: desktopStream,
  1099. googLeakyBucket: true,
  1100. maxWidth: window.screen.width,
  1101. maxHeight: window.screen.height,
  1102. maxFrameRate: 3
  1103. },
  1104. optional: []
  1105. };
  1106. }
  1107. if (bandwidth) {
  1108. if (!constraints.video) {
  1109. //same behaviour as true
  1110. constraints.video = {mandatory: {}, optional: []};
  1111. }
  1112. constraints.video.optional.push({bandwidth: bandwidth});
  1113. }
  1114. if (fps) {
  1115. // for some cameras it might be necessary to request 30fps
  1116. // so they choose 30fps mjpg over 10fps yuy2
  1117. if (!constraints.video) {
  1118. // same behaviour as true;
  1119. constraints.video = {mandatory: {}, optional: []};
  1120. }
  1121. constraints.video.mandatory.minFrameRate = fps;
  1122. }
  1123. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  1124. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  1125. // this later can be a problem with some of the tests
  1126. if(RTCBrowserType.isFirefox() && config.firefox_fake_device)
  1127. {
  1128. constraints.audio = true;
  1129. constraints.fake = true;
  1130. }
  1131. return constraints;
  1132. }
  1133. function RTCUtils(RTCService, onTemasysPluginReady)
  1134. {
  1135. var self = this;
  1136. this.service = RTCService;
  1137. if (RTCBrowserType.isFirefox()) {
  1138. var FFversion = RTCBrowserType.getFirefoxVersion();
  1139. if (FFversion >= 40) {
  1140. this.peerconnection = mozRTCPeerConnection;
  1141. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1142. this.pc_constraints = {};
  1143. this.attachMediaStream = function (element, stream) {
  1144. // srcObject is being standardized and FF will eventually
  1145. // support that unprefixed. FF also supports the
  1146. // "element.src = URL.createObjectURL(...)" combo, but that
  1147. // will be deprecated in favour of srcObject.
  1148. //
  1149. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1150. // https://github.com/webrtc/samples/issues/302
  1151. if(!element[0])
  1152. return;
  1153. element[0].mozSrcObject = stream;
  1154. element[0].play();
  1155. };
  1156. this.getStreamID = function (stream) {
  1157. var id = stream.id;
  1158. if (!id) {
  1159. var tracks = stream.getVideoTracks();
  1160. if (!tracks || tracks.length === 0) {
  1161. tracks = stream.getAudioTracks();
  1162. }
  1163. id = tracks[0].id;
  1164. }
  1165. return SDPUtil.filter_special_chars(id);
  1166. };
  1167. this.getVideoSrc = function (element) {
  1168. if(!element)
  1169. return null;
  1170. return element.mozSrcObject;
  1171. };
  1172. this.setVideoSrc = function (element, src) {
  1173. if(element)
  1174. element.mozSrcObject = src;
  1175. };
  1176. RTCSessionDescription = mozRTCSessionDescription;
  1177. RTCIceCandidate = mozRTCIceCandidate;
  1178. } else {
  1179. console.error(
  1180. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1181. window.location.href = 'unsupported_browser.html';
  1182. return;
  1183. }
  1184. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1185. this.peerconnection = webkitRTCPeerConnection;
  1186. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1187. this.attachMediaStream = function (element, stream) {
  1188. element.attr('src', webkitURL.createObjectURL(stream));
  1189. };
  1190. this.getStreamID = function (stream) {
  1191. // streams from FF endpoints have the characters '{' and '}'
  1192. // that make jQuery choke.
  1193. return SDPUtil.filter_special_chars(stream.id);
  1194. };
  1195. this.getVideoSrc = function (element) {
  1196. if(!element)
  1197. return null;
  1198. return element.getAttribute("src");
  1199. };
  1200. this.setVideoSrc = function (element, src) {
  1201. if(element)
  1202. element.setAttribute("src", src);
  1203. };
  1204. // DTLS should now be enabled by default but..
  1205. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1206. if (RTCBrowserType.isAndroid()) {
  1207. this.pc_constraints = {}; // disable DTLS on Android
  1208. }
  1209. if (!webkitMediaStream.prototype.getVideoTracks) {
  1210. webkitMediaStream.prototype.getVideoTracks = function () {
  1211. return this.videoTracks;
  1212. };
  1213. }
  1214. if (!webkitMediaStream.prototype.getAudioTracks) {
  1215. webkitMediaStream.prototype.getAudioTracks = function () {
  1216. return this.audioTracks;
  1217. };
  1218. }
  1219. }
  1220. // Detect IE/Safari
  1221. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1222. //AdapterJS.WebRTCPlugin.setLogLevel(
  1223. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1224. AdapterJS.webRTCReady(function (isPlugin) {
  1225. self.peerconnection = RTCPeerConnection;
  1226. self.getUserMedia = getUserMedia;
  1227. self.attachMediaStream = function (elSel, stream) {
  1228. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1229. return;
  1230. }
  1231. attachMediaStream(elSel[0], stream);
  1232. };
  1233. self.getStreamID = function (stream) {
  1234. var id = SDPUtil.filter_special_chars(stream.label);
  1235. return id;
  1236. };
  1237. self.getVideoSrc = function (element) {
  1238. if (!element) {
  1239. console.warn("Attempt to get video SRC of null element");
  1240. return null;
  1241. }
  1242. var children = element.children;
  1243. for (var i = 0; i !== children.length; ++i) {
  1244. if (children[i].name === 'streamId') {
  1245. return children[i].value;
  1246. }
  1247. }
  1248. //console.info(element.id + " SRC: " + src);
  1249. return null;
  1250. };
  1251. self.setVideoSrc = function (element, src) {
  1252. //console.info("Set video src: ", element, src);
  1253. if (!src) {
  1254. console.warn("Not attaching video stream, 'src' is null");
  1255. return;
  1256. }
  1257. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1258. var stream = AdapterJS.WebRTCPlugin.plugin
  1259. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1260. attachMediaStream(element, stream);
  1261. };
  1262. onTemasysPluginReady(isPlugin);
  1263. });
  1264. } else {
  1265. try {
  1266. console.log('Browser does not appear to be WebRTC-capable');
  1267. } catch (e) { }
  1268. window.location.href = 'unsupported_browser.html';
  1269. }
  1270. }
  1271. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1272. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1273. desktopStream) {
  1274. currentResolution = resolution;
  1275. var constraints = getConstraints(
  1276. um, resolution, bandwidth, fps, desktopStream);
  1277. console.info("Get media constraints", constraints);
  1278. var self = this;
  1279. try {
  1280. this.getUserMedia(constraints,
  1281. function (stream) {
  1282. console.log('onUserMediaSuccess');
  1283. self.setAvailableDevices(um, true);
  1284. success_callback(stream);
  1285. },
  1286. function (error) {
  1287. self.setAvailableDevices(um, false);
  1288. console.warn('Failed to get access to local media. Error ',
  1289. error, constraints);
  1290. if (failure_callback) {
  1291. failure_callback(error);
  1292. }
  1293. });
  1294. } catch (e) {
  1295. console.error('GUM failed: ', e);
  1296. if(failure_callback) {
  1297. failure_callback(e);
  1298. }
  1299. }
  1300. };
  1301. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1302. var devices = {};
  1303. if(um.indexOf("video") != -1) {
  1304. devices.video = available;
  1305. }
  1306. if(um.indexOf("audio") != -1) {
  1307. devices.audio = available;
  1308. }
  1309. this.service.setDeviceAvailability(devices);
  1310. };
  1311. /**
  1312. * We ask for audio and video combined stream in order to get permissions and
  1313. * not to ask twice.
  1314. */
  1315. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1316. function(devices, callback, usageOptions)
  1317. {
  1318. var self = this;
  1319. // Get AV
  1320. var successCallback = function (stream) {
  1321. if(callback)
  1322. callback(stream, usageOptions);
  1323. else
  1324. self.successCallback(stream, usageOptions);
  1325. };
  1326. if(!devices)
  1327. devices = ['audio', 'video'];
  1328. var newDevices = [];
  1329. if(usageOptions)
  1330. for(var i = 0; i < devices.length; i++) {
  1331. var device = devices[i];
  1332. if(usageOptions[device] === true)
  1333. newDevices.push(device);
  1334. }
  1335. else
  1336. newDevices = devices;
  1337. if(newDevices.length === 0) {
  1338. successCallback();
  1339. return;
  1340. }
  1341. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1342. // With FF/IE we can't split the stream into audio and video because FF
  1343. // doesn't support media stream constructors. So, we need to get the
  1344. // audio stream separately from the video stream using two distinct GUM
  1345. // calls. Not very user friendly :-( but we don't have many other
  1346. // options neither.
  1347. //
  1348. // Note that we pack those 2 streams in a single object and pass it to
  1349. // the successCallback method.
  1350. var obtainVideo = function (audioStream) {
  1351. self.getUserMediaWithConstraints(
  1352. ['video'],
  1353. function (videoStream) {
  1354. return successCallback({
  1355. audioStream: audioStream,
  1356. videoStream: videoStream
  1357. });
  1358. },
  1359. function (error) {
  1360. console.error(
  1361. 'failed to obtain video stream - stop', error);
  1362. self.errorCallback(error);
  1363. },
  1364. config.resolution || '360');
  1365. };
  1366. var obtainAudio = function () {
  1367. self.getUserMediaWithConstraints(
  1368. ['audio'],
  1369. function (audioStream) {
  1370. if (newDevices.indexOf('video') !== -1)
  1371. obtainVideo(audioStream);
  1372. },
  1373. function (error) {
  1374. console.error(
  1375. 'failed to obtain audio stream - stop', error);
  1376. self.errorCallback(error);
  1377. }
  1378. );
  1379. };
  1380. if (newDevices.indexOf('audio') !== -1) {
  1381. obtainAudio();
  1382. } else {
  1383. obtainVideo(null);
  1384. }
  1385. } else {
  1386. this.getUserMediaWithConstraints(
  1387. newDevices,
  1388. function (stream) {
  1389. successCallback(stream);
  1390. },
  1391. function (error) {
  1392. self.errorCallback(error);
  1393. },
  1394. config.resolution || '360');
  1395. }
  1396. };
  1397. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1398. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1399. // it's an object with two properties: audioStream, videoStream.
  1400. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1401. console.log('got', stream, stream.getAudioTracks().length,
  1402. stream.getVideoTracks().length);
  1403. this.handleLocalStream(stream, usageOptions);
  1404. };
  1405. RTCUtils.prototype.errorCallback = function (error) {
  1406. var self = this;
  1407. console.error('failed to obtain audio/video stream - trying audio only', error);
  1408. var resolution = getPreviousResolution(currentResolution);
  1409. if(typeof error == "object" && error.constraintName && error.name
  1410. && (error.name == "ConstraintNotSatisfiedError" ||
  1411. error.name == "OverconstrainedError") &&
  1412. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1413. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1414. && resolution != null)
  1415. {
  1416. self.getUserMediaWithConstraints(['audio', 'video'],
  1417. function (stream) {
  1418. return self.successCallback(stream);
  1419. }, function (error) {
  1420. return self.errorCallback(error);
  1421. }, resolution);
  1422. }
  1423. else {
  1424. self.getUserMediaWithConstraints(
  1425. ['audio'],
  1426. function (stream) {
  1427. return self.successCallback(stream);
  1428. },
  1429. function (error) {
  1430. console.error('failed to obtain audio/video stream - stop',
  1431. error);
  1432. return self.successCallback(null);
  1433. }
  1434. );
  1435. }
  1436. };
  1437. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1438. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1439. // an object with two properties: audioStream, videoStream.
  1440. var audioStream, videoStream;
  1441. if(window.webkitMediaStream)
  1442. {
  1443. audioStream = new webkitMediaStream();
  1444. videoStream = new webkitMediaStream();
  1445. if(stream) {
  1446. var audioTracks = stream.getAudioTracks();
  1447. for (var i = 0; i < audioTracks.length; i++) {
  1448. audioStream.addTrack(audioTracks[i]);
  1449. }
  1450. var videoTracks = stream.getVideoTracks();
  1451. for (i = 0; i < videoTracks.length; i++) {
  1452. videoStream.addTrack(videoTracks[i]);
  1453. }
  1454. }
  1455. }
  1456. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1457. { // Firefox and Temasys plugin
  1458. if (stream && stream.audioStream)
  1459. audioStream = stream.audioStream;
  1460. else
  1461. audioStream = new DummyMediaStream("dummyAudio");
  1462. if (stream && stream.videoStream)
  1463. videoStream = stream.videoStream;
  1464. else
  1465. videoStream = new DummyMediaStream("dummyVideo");
  1466. }
  1467. var audioMuted = (usageOptions && usageOptions.audio === false),
  1468. videoMuted = (usageOptions && usageOptions.video === false);
  1469. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1470. videoGUM = (!usageOptions || usageOptions.video !== false);
  1471. this.service.createLocalStream(audioStream, "audio", null, null,
  1472. audioMuted, audioGUM);
  1473. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1474. videoMuted, videoGUM);
  1475. };
  1476. function DummyMediaStream(id) {
  1477. this.id = id;
  1478. this.label = id;
  1479. this.stop = function() { };
  1480. this.getAudioTracks = function() { return []; };
  1481. this.getVideoTracks = function() { return []; };
  1482. }
  1483. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1484. var newStream = null;
  1485. if (window.webkitMediaStream) {
  1486. newStream = new webkitMediaStream();
  1487. if (newStream) {
  1488. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1489. for (var i = 0; i < tracks.length; i++) {
  1490. newStream.addTrack(tracks[i]);
  1491. }
  1492. }
  1493. }
  1494. else {
  1495. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1496. if (stream) {
  1497. newStream = stream;
  1498. } else {
  1499. newStream =
  1500. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1501. }
  1502. }
  1503. return newStream;
  1504. };
  1505. module.exports = RTCUtils;
  1506. },{"../../service/RTC/Resolutions":161,"../xmpp/SDPUtil":58,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1507. /*! adapterjs - custom version from - 2015-08-18 */
  1508. // Adapter's interface.
  1509. var AdapterJS = AdapterJS || {};
  1510. // Browserify compatibility
  1511. if(typeof exports !== 'undefined') {
  1512. module.exports = AdapterJS;
  1513. }
  1514. AdapterJS.options = AdapterJS.options || {};
  1515. // uncomment to get virtual webcams
  1516. // AdapterJS.options.getAllCams = true;
  1517. // uncomment to prevent the install prompt when the plugin in not yet installed
  1518. // AdapterJS.options.hidePluginInstallPrompt = true;
  1519. // AdapterJS version
  1520. AdapterJS.VERSION = '0.12.0';
  1521. // This function will be called when the WebRTC API is ready to be used
  1522. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1523. // the plugin
  1524. // You may Override this function to synchronise the start of your application
  1525. // with the WebRTC API being ready.
  1526. // If you decide not to override use this synchronisation, it may result in
  1527. // an extensive CPU usage on the plugin start (once per tab loaded)
  1528. // Params:
  1529. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1530. //
  1531. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1532. // The WebRTC API is ready.
  1533. // Override me and do whatever you want here
  1534. };
  1535. // Sets a callback function to be called when the WebRTC interface is ready.
  1536. // The first argument is the function to callback.\
  1537. // Throws an error if the first argument is not a function
  1538. AdapterJS.webRTCReady = function (callback) {
  1539. if (typeof callback !== 'function') {
  1540. throw new Error('Callback provided is not a function');
  1541. }
  1542. if (true === AdapterJS.onwebrtcreadyDone) {
  1543. // All WebRTC interfaces are ready, just call the callback
  1544. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1545. } else {
  1546. // will be triggered automatically when your browser/plugin is ready.
  1547. AdapterJS.onwebrtcready = callback;
  1548. }
  1549. };
  1550. // Plugin namespace
  1551. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1552. // The object to store plugin information
  1553. AdapterJS.WebRTCPlugin.pluginInfo = {
  1554. prefix : 'Tem',
  1555. plugName : 'TemWebRTCPlugin',
  1556. pluginId : 'plugin0',
  1557. type : 'application/x-temwebrtcplugin',
  1558. onload : '__TemWebRTCReady0',
  1559. portalLink : 'http://skylink.io/plugin/',
  1560. downloadLink : null, //set below
  1561. companyName: 'Temasys'
  1562. };
  1563. if(!!navigator.platform.match(/^Mac/i)) {
  1564. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1565. }
  1566. else if(!!navigator.platform.match(/^Win/i)) {
  1567. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1568. }
  1569. AdapterJS.WebRTCPlugin.TAGS = {
  1570. NONE : 'none',
  1571. AUDIO : 'audio',
  1572. VIDEO : 'video'
  1573. };
  1574. // Unique identifier of each opened page
  1575. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1576. // Use this whenever you want to call the plugin.
  1577. AdapterJS.WebRTCPlugin.plugin = null;
  1578. // Set log level for the plugin once it is ready.
  1579. // The different values are
  1580. // This is an asynchronous function that will run when the plugin is ready
  1581. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1582. // Defines webrtc's JS interface according to the plugin's implementation.
  1583. // Define plugin Browsers as WebRTC Interface.
  1584. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1585. // This function detects whether or not a plugin is installed.
  1586. // Checks if Not IE (firefox, for example), else if it's IE,
  1587. // we're running IE and do something. If not it is not supported.
  1588. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1589. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1590. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1591. // Inject the HTML DOM object element into the page.
  1592. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1593. // States of readiness that the plugin goes through when
  1594. // being injected and stated
  1595. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1596. NONE : 0, // no plugin use
  1597. INITIALIZING : 1, // Detected need for plugin
  1598. INJECTING : 2, // Injecting plugin
  1599. INJECTED: 3, // Plugin element injected but not usable yet
  1600. READY: 4 // Plugin ready to be used
  1601. };
  1602. // Current state of the plugin. You cannot use the plugin before this is
  1603. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1604. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1605. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1606. // Used to make sure AdapterJS.onwebrtcready is only called once
  1607. AdapterJS.onwebrtcreadyDone = false;
  1608. // Log levels for the plugin.
  1609. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1610. /*
  1611. Log outputs are prefixed in some cases.
  1612. INFO: Information reported by the plugin.
  1613. ERROR: Errors originating from within the plugin.
  1614. WEBRTC: Error originating from within the libWebRTC library
  1615. */
  1616. // From the least verbose to the most verbose
  1617. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1618. NONE : 'NONE',
  1619. ERROR : 'ERROR',
  1620. WARNING : 'WARNING',
  1621. INFO: 'INFO',
  1622. VERBOSE: 'VERBOSE',
  1623. SENSITIVE: 'SENSITIVE'
  1624. };
  1625. // Does a waiting check before proceeding to load the plugin.
  1626. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1627. // This methid will use an interval to wait for the plugin to be ready.
  1628. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1629. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1630. // This function will be called when plugin is ready. It sends necessary
  1631. // details to the plugin.
  1632. // The function will wait for the document to be ready and the set the
  1633. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1634. // indicating that it can start being requested.
  1635. // This function is not in the IE/Safari condition brackets so that
  1636. // TemPluginLoaded function might be called on Chrome/Firefox.
  1637. // This function is the only private function that is not encapsulated to
  1638. // allow the plugin method to be called.
  1639. __TemWebRTCReady0 = function () {
  1640. if (document.readyState === 'complete') {
  1641. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1642. AdapterJS.maybeThroughWebRTCReady();
  1643. } else {
  1644. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1645. if (document.readyState === 'complete') {
  1646. // TODO: update comments, we wait for the document to be ready
  1647. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1648. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1649. AdapterJS.maybeThroughWebRTCReady();
  1650. }
  1651. }, 100);
  1652. }
  1653. };
  1654. AdapterJS.maybeThroughWebRTCReady = function() {
  1655. if (!AdapterJS.onwebrtcreadyDone) {
  1656. AdapterJS.onwebrtcreadyDone = true;
  1657. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1658. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1659. }
  1660. }
  1661. };
  1662. // Text namespace
  1663. AdapterJS.TEXT = {
  1664. PLUGIN: {
  1665. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1666. 'to work on this browser.',
  1667. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1668. BUTTON: 'Install Now'
  1669. },
  1670. REFRESH: {
  1671. REQUIRE_REFRESH: 'Please refresh page',
  1672. BUTTON: 'Refresh Page'
  1673. }
  1674. };
  1675. // The result of ice connection states.
  1676. // - starting: Ice connection is starting.
  1677. // - checking: Ice connection is checking.
  1678. // - connected Ice connection is connected.
  1679. // - completed Ice connection is connected.
  1680. // - done Ice connection has been completed.
  1681. // - disconnected Ice connection has been disconnected.
  1682. // - failed Ice connection has failed.
  1683. // - closed Ice connection is closed.
  1684. AdapterJS._iceConnectionStates = {
  1685. starting : 'starting',
  1686. checking : 'checking',
  1687. connected : 'connected',
  1688. completed : 'connected',
  1689. done : 'completed',
  1690. disconnected : 'disconnected',
  1691. failed : 'failed',
  1692. closed : 'closed'
  1693. };
  1694. //The IceConnection states that has been fired for each peer.
  1695. AdapterJS._iceConnectionFiredStates = [];
  1696. // Check if WebRTC Interface is defined.
  1697. AdapterJS.isDefined = null;
  1698. // This function helps to retrieve the webrtc detected browser information.
  1699. // This sets:
  1700. // - webrtcDetectedBrowser: The browser agent name.
  1701. // - webrtcDetectedVersion: The browser version.
  1702. // - webrtcDetectedType: The types of webRTC support.
  1703. // - 'moz': Mozilla implementation of webRTC.
  1704. // - 'webkit': WebKit implementation of webRTC.
  1705. // - 'plugin': Using the plugin implementation.
  1706. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1707. var hasMatch, checkMatch = navigator.userAgent.match(
  1708. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1709. if (/trident/i.test(checkMatch[1])) {
  1710. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1711. webrtcDetectedBrowser = 'IE';
  1712. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1713. } else if (checkMatch[1] === 'Chrome') {
  1714. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1715. if (hasMatch !== null) {
  1716. webrtcDetectedBrowser = 'opera';
  1717. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1718. }
  1719. }
  1720. if (navigator.userAgent.indexOf('Safari')) {
  1721. if (typeof InstallTrigger !== 'undefined') {
  1722. webrtcDetectedBrowser = 'firefox';
  1723. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1724. webrtcDetectedBrowser = 'IE';
  1725. } else if (
  1726. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1727. webrtcDetectedBrowser = 'safari';
  1728. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1729. webrtcDetectedBrowser = 'opera';
  1730. } else if (!!window.chrome) {
  1731. webrtcDetectedBrowser = 'chrome';
  1732. }
  1733. }
  1734. if (!webrtcDetectedBrowser) {
  1735. webrtcDetectedVersion = checkMatch[1];
  1736. }
  1737. if (!webrtcDetectedVersion) {
  1738. try {
  1739. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1740. [navigator.appName, navigator.appVersion, '-?'];
  1741. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1742. checkMatch.splice(1, 1, hasMatch[1]);
  1743. }
  1744. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1745. } catch (error) { }
  1746. }
  1747. };
  1748. // To fix configuration as some browsers does not support
  1749. // the 'urls' attribute.
  1750. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1751. if (pcConfig === null) {
  1752. return;
  1753. }
  1754. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1755. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1756. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1757. delete pcConfig.iceServers[i].urls;
  1758. }
  1759. }
  1760. };
  1761. AdapterJS.addEvent = function(elem, evnt, func) {
  1762. if (elem.addEventListener) { // W3C DOM
  1763. elem.addEventListener(evnt, func, false);
  1764. } else if (elem.attachEvent) {// OLD IE DOM
  1765. elem.attachEvent('on'+evnt, func);
  1766. } else { // No much to do
  1767. elem[evnt] = func;
  1768. }
  1769. };
  1770. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1771. // only inject once the page is ready
  1772. if (document.readyState !== 'complete') {
  1773. return;
  1774. }
  1775. var w = window;
  1776. var i = document.createElement('iframe');
  1777. i.style.position = 'fixed';
  1778. i.style.top = '-41px';
  1779. i.style.left = 0;
  1780. i.style.right = 0;
  1781. i.style.width = '100%';
  1782. i.style.height = '40px';
  1783. i.style.backgroundColor = '#ffffe1';
  1784. i.style.border = 'none';
  1785. i.style.borderBottom = '1px solid #888888';
  1786. i.style.zIndex = '9999999';
  1787. if(typeof i.style.webkitTransition === 'string') {
  1788. i.style.webkitTransition = 'all .5s ease-out';
  1789. } else if(typeof i.style.transition === 'string') {
  1790. i.style.transition = 'all .5s ease-out';
  1791. }
  1792. document.body.appendChild(i);
  1793. c = (i.contentWindow) ? i.contentWindow :
  1794. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1795. c.document.open();
  1796. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1797. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1798. 'middle; cursor: default;">' + text + '</span>');
  1799. if(buttonText && buttonLink) {
  1800. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1801. c.document.close();
  1802. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1803. if (!!displayRefreshBar) {
  1804. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1805. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1806. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1807. }
  1808. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1809. e.preventDefault();
  1810. try {
  1811. event.cancelBubble = true;
  1812. } catch(error) { }
  1813. var pluginInstallInterval = setInterval(function(){
  1814. if(! isIE) {
  1815. navigator.plugins.refresh(false);
  1816. }
  1817. AdapterJS.WebRTCPlugin.isPluginInstalled(
  1818. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  1819. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  1820. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  1821. function() {
  1822. clearInterval(pluginInstallInterval);
  1823. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  1824. },
  1825. function() {
  1826. //Does nothing because not used here
  1827. });
  1828. } , 500);
  1829. });
  1830. } else {
  1831. c.document.close();
  1832. }
  1833. AdapterJS.addEvent(c.document, 'click', function() {
  1834. w.document.body.removeChild(i);
  1835. });
  1836. setTimeout(function() {
  1837. if(typeof i.style.webkitTransform === 'string') {
  1838. i.style.webkitTransform = 'translateY(40px)';
  1839. } else if(typeof i.style.transform === 'string') {
  1840. i.style.transform = 'translateY(40px)';
  1841. } else {
  1842. i.style.top = '0px';
  1843. }
  1844. }, 300);
  1845. };
  1846. // -----------------------------------------------------------
  1847. // Detected webrtc implementation. Types are:
  1848. // - 'moz': Mozilla implementation of webRTC.
  1849. // - 'webkit': WebKit implementation of webRTC.
  1850. // - 'plugin': Using the plugin implementation.
  1851. webrtcDetectedType = null;
  1852. // Detected webrtc datachannel support. Types are:
  1853. // - 'SCTP': SCTP datachannel support.
  1854. // - 'RTP': RTP datachannel support.
  1855. webrtcDetectedDCSupport = null;
  1856. // Set the settings for creating DataChannels, MediaStream for
  1857. // Cross-browser compability.
  1858. // - This is only for SCTP based support browsers.
  1859. // the 'urls' attribute.
  1860. checkMediaDataChannelSettings =
  1861. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1862. if (typeof callback !== 'function') {
  1863. return;
  1864. }
  1865. var beOfferer = true;
  1866. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1867. // Nightly version does not require MozDontOfferDataChannel for interop
  1868. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1869. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1870. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1871. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1872. // Resends an updated version of constraints for MozDataChannel to work
  1873. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1874. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1875. try {
  1876. delete constraints.mandatory.MozDontOfferDataChannel;
  1877. } catch (error) {
  1878. console.error('Failed deleting MozDontOfferDataChannel');
  1879. console.error(error);
  1880. }
  1881. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1882. constraints.mandatory.MozDontOfferDataChannel = true;
  1883. }
  1884. if (!isLocalFirefox) {
  1885. // temporary measure to remove Moz* constraints in non Firefox browsers
  1886. for (var prop in constraints.mandatory) {
  1887. if (constraints.mandatory.hasOwnProperty(prop)) {
  1888. if (prop.indexOf('Moz') !== -1) {
  1889. delete constraints.mandatory[prop];
  1890. }
  1891. }
  1892. }
  1893. }
  1894. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1895. // interopability of the media stream
  1896. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1897. beOfferer = false;
  1898. }
  1899. callback(beOfferer, constraints);
  1900. };
  1901. // Handles the differences for all browsers ice connection state output.
  1902. // - Tested outcomes are:
  1903. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1904. // - Chrome (answerer) : 'checking' > 'connected'
  1905. // - Firefox (offerer) : 'checking' > 'connected'
  1906. // - Firefox (answerer): 'checking' > 'connected'
  1907. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1908. if (typeof callback !== 'function') {
  1909. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1910. return;
  1911. }
  1912. peerId = (peerId) ? peerId : 'peer';
  1913. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1914. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1915. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1916. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1917. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1918. }
  1919. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1920. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1921. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1922. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1923. setTimeout(function () {
  1924. AdapterJS._iceConnectionFiredStates[peerId]
  1925. .push(AdapterJS._iceConnectionStates.done);
  1926. callback(AdapterJS._iceConnectionStates.done);
  1927. }, 1000);
  1928. }
  1929. callback(iceConnectionState);
  1930. }
  1931. return;
  1932. };
  1933. // Firefox:
  1934. // - Creates iceServer from the url for Firefox.
  1935. // - Create iceServer with stun url.
  1936. // - Create iceServer with turn url.
  1937. // - Ignore the transport parameter from TURN url for FF version <=27.
  1938. // - Return null for createIceServer if transport=tcp.
  1939. // - FF 27 and above supports transport parameters in TURN url,
  1940. // - So passing in the full url to create iceServer.
  1941. // Chrome:
  1942. // - Creates iceServer from the url for Chrome M33 and earlier.
  1943. // - Create iceServer with stun url.
  1944. // - Chrome M28 & above uses below TURN format.
  1945. // Plugin:
  1946. // - Creates Ice Server for Plugin Browsers
  1947. // - If Stun - Create iceServer with stun url.
  1948. // - Else - Create iceServer with turn url
  1949. // - This is a WebRTC Function
  1950. createIceServer = null;
  1951. // Firefox:
  1952. // - Creates IceServers for Firefox
  1953. // - Use .url for FireFox.
  1954. // - Multiple Urls support
  1955. // Chrome:
  1956. // - Creates iceServers from the urls for Chrome M34 and above.
  1957. // - .urls is supported since Chrome M34.
  1958. // - Multiple Urls support
  1959. // Plugin:
  1960. // - Creates Ice Servers for Plugin Browsers
  1961. // - Multiple Urls support
  1962. // - This is a WebRTC Function
  1963. createIceServers = null;
  1964. //------------------------------------------------------------
  1965. //The RTCPeerConnection object.
  1966. RTCPeerConnection = null;
  1967. // Creates RTCSessionDescription object for Plugin Browsers
  1968. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  1969. RTCSessionDescription : null;
  1970. // Creates RTCIceCandidate object for Plugin Browsers
  1971. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  1972. RTCIceCandidate : null;
  1973. // Get UserMedia (only difference is the prefix).
  1974. // Code from Adam Barth.
  1975. getUserMedia = null;
  1976. // Attach a media stream to an element.
  1977. attachMediaStream = null;
  1978. // Re-attach a media stream to an element.
  1979. reattachMediaStream = null;
  1980. // Detected browser agent name. Types are:
  1981. // - 'firefox': Firefox browser.
  1982. // - 'chrome': Chrome browser.
  1983. // - 'opera': Opera browser.
  1984. // - 'safari': Safari browser.
  1985. // - 'IE' - Internet Explorer browser.
  1986. webrtcDetectedBrowser = null;
  1987. // Detected browser version.
  1988. webrtcDetectedVersion = null;
  1989. // Check for browser types and react accordingly
  1990. if (navigator.mozGetUserMedia) {
  1991. webrtcDetectedBrowser = 'firefox';
  1992. webrtcDetectedVersion = parseInt(navigator
  1993. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1994. webrtcDetectedType = 'moz';
  1995. webrtcDetectedDCSupport = 'SCTP';
  1996. RTCPeerConnection = function (pcConfig, pcConstraints) {
  1997. AdapterJS.maybeFixConfiguration(pcConfig);
  1998. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  1999. };
  2000. // The RTCSessionDescription object.
  2001. RTCSessionDescription = mozRTCSessionDescription;
  2002. window.RTCSessionDescription = RTCSessionDescription;
  2003. // The RTCIceCandidate object.
  2004. RTCIceCandidate = mozRTCIceCandidate;
  2005. window.RTCIceCandidate = RTCIceCandidate;
  2006. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2007. navigator.getUserMedia = window.getUserMedia;
  2008. // Shim for MediaStreamTrack.getSources.
  2009. MediaStreamTrack.getSources = function(successCb) {
  2010. setTimeout(function() {
  2011. var infos = [
  2012. { kind: 'audio', id: 'default', label:'', facing:'' },
  2013. { kind: 'video', id: 'default', label:'', facing:'' }
  2014. ];
  2015. successCb(infos);
  2016. }, 0);
  2017. };
  2018. createIceServer = function (url, username, password) {
  2019. var iceServer = null;
  2020. var url_parts = url.split(':');
  2021. if (url_parts[0].indexOf('stun') === 0) {
  2022. iceServer = { url : url };
  2023. } else if (url_parts[0].indexOf('turn') === 0) {
  2024. if (webrtcDetectedVersion < 27) {
  2025. var turn_url_parts = url.split('?');
  2026. if (turn_url_parts.length === 1 ||
  2027. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2028. iceServer = {
  2029. url : turn_url_parts[0],
  2030. credential : password,
  2031. username : username
  2032. };
  2033. }
  2034. } else {
  2035. iceServer = {
  2036. url : url,
  2037. credential : password,
  2038. username : username
  2039. };
  2040. }
  2041. }
  2042. return iceServer;
  2043. };
  2044. createIceServers = function (urls, username, password) {
  2045. var iceServers = [];
  2046. for (i = 0; i < urls.length; i++) {
  2047. var iceServer = createIceServer(urls[i], username, password);
  2048. if (iceServer !== null) {
  2049. iceServers.push(iceServer);
  2050. }
  2051. }
  2052. return iceServers;
  2053. };
  2054. attachMediaStream = function (element, stream) {
  2055. element.mozSrcObject = stream;
  2056. if (stream !== null)
  2057. element.play();
  2058. return element;
  2059. };
  2060. reattachMediaStream = function (to, from) {
  2061. to.mozSrcObject = from.mozSrcObject;
  2062. to.play();
  2063. return to;
  2064. };
  2065. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2066. if (!callback) {
  2067. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2068. ': 1 argument required, but only 0 present.');
  2069. }
  2070. return callback([]);
  2071. };
  2072. // Fake get{Video,Audio}Tracks
  2073. if (!MediaStream.prototype.getVideoTracks) {
  2074. MediaStream.prototype.getVideoTracks = function () {
  2075. return [];
  2076. };
  2077. }
  2078. if (!MediaStream.prototype.getAudioTracks) {
  2079. MediaStream.prototype.getAudioTracks = function () {
  2080. return [];
  2081. };
  2082. }
  2083. AdapterJS.maybeThroughWebRTCReady();
  2084. } else if (navigator.webkitGetUserMedia) {
  2085. webrtcDetectedBrowser = 'chrome';
  2086. webrtcDetectedType = 'webkit';
  2087. webrtcDetectedVersion = parseInt(navigator
  2088. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2089. // check if browser is opera 20+
  2090. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2091. if (checkIfOpera !== null) {
  2092. webrtcDetectedBrowser = 'opera';
  2093. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2094. }
  2095. // check browser datachannel support
  2096. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2097. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2098. webrtcDetectedDCSupport = 'SCTP';
  2099. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2100. webrtcDetectedVersion > 24) {
  2101. webrtcDetectedDCSupport = 'RTP';
  2102. } else {
  2103. webrtcDetectedDCSupport = '';
  2104. }
  2105. createIceServer = function (url, username, password) {
  2106. var iceServer = null;
  2107. var url_parts = url.split(':');
  2108. if (url_parts[0].indexOf('stun') === 0) {
  2109. iceServer = { 'url' : url };
  2110. } else if (url_parts[0].indexOf('turn') === 0) {
  2111. iceServer = {
  2112. 'url' : url,
  2113. 'credential' : password,
  2114. 'username' : username
  2115. };
  2116. }
  2117. return iceServer;
  2118. };
  2119. createIceServers = function (urls, username, password) {
  2120. var iceServers = [];
  2121. if (webrtcDetectedVersion >= 34) {
  2122. iceServers = {
  2123. 'urls' : urls,
  2124. 'credential' : password,
  2125. 'username' : username
  2126. };
  2127. } else {
  2128. for (i = 0; i < urls.length; i++) {
  2129. var iceServer = createIceServer(urls[i], username, password);
  2130. if (iceServer !== null) {
  2131. iceServers.push(iceServer);
  2132. }
  2133. }
  2134. }
  2135. return iceServers;
  2136. };
  2137. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2138. if (webrtcDetectedVersion < 34) {
  2139. AdapterJS.maybeFixConfiguration(pcConfig);
  2140. }
  2141. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2142. };
  2143. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2144. navigator.getUserMedia = window.getUserMedia;
  2145. attachMediaStream = function (element, stream) {
  2146. if (typeof element.srcObject !== 'undefined') {
  2147. element.srcObject = stream;
  2148. } else if (typeof element.mozSrcObject !== 'undefined') {
  2149. element.mozSrcObject = stream;
  2150. } else if (typeof element.src !== 'undefined') {
  2151. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2152. } else {
  2153. console.log('Error attaching stream to element.');
  2154. }
  2155. return element;
  2156. };
  2157. reattachMediaStream = function (to, from) {
  2158. to.src = from.src;
  2159. return to;
  2160. };
  2161. AdapterJS.maybeThroughWebRTCReady();
  2162. } else { // TRY TO USE PLUGIN
  2163. // IE 9 is not offering an implementation of console.log until you open a console
  2164. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2165. /* jshint -W020 */
  2166. console = {} || console;
  2167. // Implemented based on console specs from MDN
  2168. // You may override these functions
  2169. console.log = function (arg) {};
  2170. console.info = function (arg) {};
  2171. console.error = function (arg) {};
  2172. console.dir = function (arg) {};
  2173. console.exception = function (arg) {};
  2174. console.trace = function (arg) {};
  2175. console.warn = function (arg) {};
  2176. console.count = function (arg) {};
  2177. console.debug = function (arg) {};
  2178. console.count = function (arg) {};
  2179. console.time = function (arg) {};
  2180. console.timeEnd = function (arg) {};
  2181. console.group = function (arg) {};
  2182. console.groupCollapsed = function (arg) {};
  2183. console.groupEnd = function (arg) {};
  2184. /* jshint +W020 */
  2185. }
  2186. webrtcDetectedType = 'plugin';
  2187. webrtcDetectedDCSupport = 'plugin';
  2188. AdapterJS.parseWebrtcDetectedBrowser();
  2189. isIE = webrtcDetectedBrowser === 'IE';
  2190. /* jshint -W035 */
  2191. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2192. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2193. /* empty because it needs to prevent the function from running. */
  2194. }
  2195. };
  2196. /* jshint +W035 */
  2197. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2198. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2199. // Call immediately if possible
  2200. // Once the plugin is set, the code will always take this path
  2201. callback();
  2202. } else {
  2203. // otherwise start a 100ms interval
  2204. var checkPluginReadyState = setInterval(function () {
  2205. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2206. clearInterval(checkPluginReadyState);
  2207. callback();
  2208. }
  2209. }, 100);
  2210. }
  2211. };
  2212. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2213. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2214. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2215. });
  2216. };
  2217. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2218. // only inject once the page is ready
  2219. if (document.readyState !== 'complete') {
  2220. return;
  2221. }
  2222. // Prevent multiple injections
  2223. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2224. return;
  2225. }
  2226. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2227. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2228. var frag = document.createDocumentFragment();
  2229. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2230. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2231. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2232. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2233. '<param name="pluginId" value="' +
  2234. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2235. '<param name="windowless" value="false" /> ' +
  2236. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2237. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  2238. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  2239. // uncomment to be able to use virtual cams
  2240. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2241. '</object>';
  2242. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2243. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2244. }
  2245. document.body.appendChild(frag);
  2246. // Need to re-fetch the plugin
  2247. AdapterJS.WebRTCPlugin.plugin =
  2248. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2249. } else {
  2250. // Load Plugin
  2251. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2252. AdapterJS.WebRTCPlugin.plugin.id =
  2253. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2254. // IE will only start the plugin if it's ACTUALLY visible
  2255. if (isIE) {
  2256. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2257. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2258. } else { // The size of the plugin on Safari should be 0x0px
  2259. // so that the autorisation prompt is at the top
  2260. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2261. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2262. }
  2263. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2264. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2265. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2266. '<param name="pluginId" value="' +
  2267. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2268. '<param name="windowless" value="false" /> ' +
  2269. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2270. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  2271. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  2272. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2273. }
  2274. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2275. };
  2276. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2277. function (comName, plugName, installedCb, notInstalledCb) {
  2278. if (!isIE) {
  2279. var pluginArray = navigator.plugins;
  2280. for (var i = 0; i < pluginArray.length; i++) {
  2281. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2282. installedCb();
  2283. return;
  2284. }
  2285. }
  2286. notInstalledCb();
  2287. } else {
  2288. try {
  2289. var axo = new ActiveXObject(comName + '.' + plugName);
  2290. } catch (e) {
  2291. notInstalledCb();
  2292. return;
  2293. }
  2294. installedCb();
  2295. }
  2296. };
  2297. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2298. if (AdapterJS.WebRTCPlugin.pluginState ===
  2299. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2300. console.error("WebRTC interface has been defined already");
  2301. return;
  2302. }
  2303. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2304. AdapterJS.isDefined = function (variable) {
  2305. return variable !== null && variable !== undefined;
  2306. };
  2307. createIceServer = function (url, username, password) {
  2308. var iceServer = null;
  2309. var url_parts = url.split(':');
  2310. if (url_parts[0].indexOf('stun') === 0) {
  2311. iceServer = {
  2312. 'url' : url,
  2313. 'hasCredentials' : false
  2314. };
  2315. } else if (url_parts[0].indexOf('turn') === 0) {
  2316. iceServer = {
  2317. 'url' : url,
  2318. 'hasCredentials' : true,
  2319. 'credential' : password,
  2320. 'username' : username
  2321. };
  2322. }
  2323. return iceServer;
  2324. };
  2325. createIceServers = function (urls, username, password) {
  2326. var iceServers = [];
  2327. for (var i = 0; i < urls.length; ++i) {
  2328. iceServers.push(createIceServer(urls[i], username, password));
  2329. }
  2330. return iceServers;
  2331. };
  2332. RTCSessionDescription = function (info) {
  2333. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2334. return AdapterJS.WebRTCPlugin.plugin.
  2335. ConstructSessionDescription(info.type, info.sdp);
  2336. };
  2337. RTCPeerConnection = function (servers, constraints) {
  2338. var iceServers = null;
  2339. if (servers) {
  2340. iceServers = servers.iceServers;
  2341. for (var i = 0; i < iceServers.length; i++) {
  2342. if (iceServers[i].urls && !iceServers[i].url) {
  2343. iceServers[i].url = iceServers[i].urls;
  2344. }
  2345. iceServers[i].hasCredentials = AdapterJS.
  2346. isDefined(iceServers[i].username) &&
  2347. AdapterJS.isDefined(iceServers[i].credential);
  2348. }
  2349. }
  2350. var mandatory = (constraints && constraints.mandatory) ?
  2351. constraints.mandatory : null;
  2352. var optional = (constraints && constraints.optional) ?
  2353. constraints.optional : null;
  2354. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2355. return AdapterJS.WebRTCPlugin.plugin.
  2356. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2357. iceServers, mandatory, optional);
  2358. };
  2359. MediaStreamTrack = {};
  2360. MediaStreamTrack.getSources = function (callback) {
  2361. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2362. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2363. });
  2364. };
  2365. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2366. constraints.audio = constraints.audio || false;
  2367. constraints.video = constraints.video || false;
  2368. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2369. AdapterJS.WebRTCPlugin.plugin.
  2370. getUserMedia(constraints, successCallback, failureCallback);
  2371. });
  2372. };
  2373. window.navigator.getUserMedia = window.getUserMedia;
  2374. attachMediaStream = function (element, stream) {
  2375. if (!element || !element.parentNode) {
  2376. return;
  2377. }
  2378. var streamId
  2379. if (stream === null) {
  2380. streamId = '';
  2381. }
  2382. else {
  2383. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  2384. streamId = stream.id;
  2385. }
  2386. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2387. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2388. var tag;
  2389. switch(element.nodeName.toLowerCase()) {
  2390. case 'audio':
  2391. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  2392. break;
  2393. case 'video':
  2394. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  2395. break;
  2396. default:
  2397. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  2398. }
  2399. var frag = document.createDocumentFragment();
  2400. var temp = document.createElement('div');
  2401. var classHTML = '';
  2402. if (element.className) {
  2403. classHTML = 'class="' + element.className + '" ';
  2404. } else if (element.attributes && element.attributes['class']) {
  2405. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2406. }
  2407. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2408. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2409. '<param name="pluginId" value="' + elementId + '" /> ' +
  2410. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2411. '<param name="windowless" value="true" /> ' +
  2412. '<param name="streamId" value="' + streamId + '" /> ' +
  2413. '<param name="tag" value="' + tag + '" /> ' +
  2414. '</object>';
  2415. while (temp.firstChild) {
  2416. frag.appendChild(temp.firstChild);
  2417. }
  2418. var height = '';
  2419. var width = '';
  2420. if (element.getBoundingClientRect) {
  2421. var rectObject = element.getBoundingClientRect();
  2422. width = rectObject.width + 'px';
  2423. height = rectObject.height + 'px';
  2424. }
  2425. else if (element.width) {
  2426. width = element.width;
  2427. height = element.height;
  2428. } else {
  2429. // TODO: What scenario could bring us here?
  2430. }
  2431. element.parentNode.insertBefore(frag, element);
  2432. frag = document.getElementById(elementId);
  2433. frag.width = width;
  2434. frag.height = height;
  2435. element.parentNode.removeChild(element);
  2436. } else {
  2437. var children = element.children;
  2438. for (var i = 0; i !== children.length; ++i) {
  2439. if (children[i].name === 'streamId') {
  2440. children[i].value = streamId;
  2441. break;
  2442. }
  2443. }
  2444. element.setStreamId(streamId);
  2445. }
  2446. var newElement = document.getElementById(elementId);
  2447. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2448. if (isIE) { // on IE the event needs to be plugged manually
  2449. newElement.attachEvent('onplaying', newElement.onplaying);
  2450. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2451. newElement._TemOnClick = function (id) {
  2452. var arg = {
  2453. srcElement : document.getElementById(id)
  2454. };
  2455. newElement.onclick(arg);
  2456. };
  2457. }
  2458. return newElement;
  2459. };
  2460. reattachMediaStream = function (to, from) {
  2461. var stream = null;
  2462. var children = from.children;
  2463. for (var i = 0; i !== children.length; ++i) {
  2464. if (children[i].name === 'streamId') {
  2465. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2466. stream = AdapterJS.WebRTCPlugin.plugin
  2467. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2468. break;
  2469. }
  2470. }
  2471. if (stream !== null) {
  2472. return attachMediaStream(to, stream);
  2473. } else {
  2474. console.log('Could not find the stream associated with this element');
  2475. }
  2476. };
  2477. RTCIceCandidate = function (candidate) {
  2478. if (!candidate.sdpMid) {
  2479. candidate.sdpMid = '';
  2480. }
  2481. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2482. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2483. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2484. );
  2485. };
  2486. // inject plugin
  2487. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2488. AdapterJS.WebRTCPlugin.injectPlugin();
  2489. };
  2490. // This function will be called if the plugin is needed (browser different
  2491. // from Chrome or Firefox), but the plugin is not installed.
  2492. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2493. function() {
  2494. AdapterJS.addEvent(document,
  2495. 'readystatechange',
  2496. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2497. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2498. };
  2499. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2500. if (AdapterJS.options.hidePluginInstallPrompt) {
  2501. return;
  2502. }
  2503. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2504. if(downloadLink) { // if download link
  2505. var popupString;
  2506. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2507. popupString = 'This website requires you to install the ' +
  2508. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2509. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2510. ' WebRTC Plugin</a>' +
  2511. ' to work on this browser.';
  2512. } else { // no portal link, just print a generic explanation
  2513. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2514. }
  2515. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2516. } else { // no download link, just print a generic explanation
  2517. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2518. }
  2519. };
  2520. // Try to detect the plugin and act accordingly
  2521. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2522. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2523. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2524. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2525. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2526. }
  2527. },{}],11:[function(require,module,exports){
  2528. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2529. var UI = {};
  2530. var VideoLayout = require("./videolayout/VideoLayout.js");
  2531. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2532. var Prezi = require("./prezi/Prezi.js");
  2533. var Etherpad = require("./etherpad/Etherpad.js");
  2534. var Chat = require("./side_pannels/chat/Chat.js");
  2535. var Toolbar = require("./toolbars/Toolbar");
  2536. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2537. var BottomToolbar = require("./toolbars/BottomToolbar");
  2538. var ContactList = require("./side_pannels/contactlist/ContactList");
  2539. var Avatar = require("./avatar/Avatar");
  2540. var EventEmitter = require("events");
  2541. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2542. var Settings = require("./../settings/Settings");
  2543. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2544. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2545. UI.messageHandler = require("./util/MessageHandler");
  2546. var messageHandler = UI.messageHandler;
  2547. var Authentication = require("./authentication/Authentication");
  2548. var UIUtil = require("./util/UIUtil");
  2549. var NicknameHandler = require("./util/NicknameHandler");
  2550. var JitsiPopover = require("./util/JitsiPopover");
  2551. var CQEvents = require("../../service/connectionquality/CQEvents");
  2552. var DesktopSharingEventTypes
  2553. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2554. var RTCEvents = require("../../service/RTC/RTCEvents");
  2555. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2556. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2557. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2558. var UIEvents = require("../../service/UI/UIEvents");
  2559. var MemberEvents = require("../../service/members/Events");
  2560. var eventEmitter = new EventEmitter();
  2561. var roomName = null;
  2562. function promptDisplayName() {
  2563. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2564. message += APP.translation.translateString(
  2565. "dialog.displayNameRequired");
  2566. message += '</h2>' +
  2567. '<input name="displayName" type="text" data-i18n=' +
  2568. '"[placeholder]defaultNickname" placeholder="' +
  2569. APP.translation.translateString(
  2570. "defaultNickname", {name: "Jane Pink"}) +
  2571. '" autofocus>';
  2572. var buttonTxt
  2573. = APP.translation.generateTranslationHTML("dialog.Ok");
  2574. var buttons = [];
  2575. buttons.push({title: buttonTxt, value: "ok"});
  2576. messageHandler.openDialog(null, message,
  2577. true,
  2578. buttons,
  2579. function (e, v, m, f) {
  2580. if (v == "ok") {
  2581. var displayName = f.displayName;
  2582. if (displayName) {
  2583. VideoLayout.inputDisplayNameHandler(displayName);
  2584. return true;
  2585. }
  2586. }
  2587. e.preventDefault();
  2588. },
  2589. function () {
  2590. var form = $.prompt.getPrompt();
  2591. var input = form.find("input[name='displayName']");
  2592. input.focus();
  2593. var button = form.find("button");
  2594. button.attr("disabled", "disabled");
  2595. input.keyup(function () {
  2596. if(!input.val())
  2597. button.attr("disabled", "disabled");
  2598. else
  2599. button.removeAttr("disabled");
  2600. });
  2601. }
  2602. );
  2603. }
  2604. function notifyForInitialMute() {
  2605. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2606. "notify.muted", null, {timeOut: 120000});
  2607. }
  2608. function setupPrezi() {
  2609. $("#reloadPresentationLink").click(function() {
  2610. Prezi.reloadPresentation();
  2611. });
  2612. }
  2613. function setupChat() {
  2614. Chat.init();
  2615. $("#toggle_smileys").click(function() {
  2616. Chat.toggleSmileys();
  2617. });
  2618. }
  2619. function setupToolbars() {
  2620. Toolbar.init(UI);
  2621. Toolbar.setupButtonsFromConfig();
  2622. BottomToolbar.init();
  2623. }
  2624. function streamHandler(stream, isMuted) {
  2625. switch (stream.type) {
  2626. case "audio":
  2627. VideoLayout.changeLocalAudio(stream, isMuted);
  2628. break;
  2629. case "video":
  2630. VideoLayout.changeLocalVideo(stream, isMuted);
  2631. break;
  2632. case "stream":
  2633. VideoLayout.changeLocalStream(stream, isMuted);
  2634. break;
  2635. }
  2636. }
  2637. function onXmppConnectionFailed(stropheErrorMsg) {
  2638. var title = APP.translation.generateTranslationHTML(
  2639. "dialog.error");
  2640. var message;
  2641. if (stropheErrorMsg) {
  2642. message = APP.translation.generateTranslationHTML(
  2643. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2644. } else {
  2645. message = APP.translation.generateTranslationHTML(
  2646. "dialog.connectError");
  2647. }
  2648. messageHandler.openDialog(
  2649. title, message, true, {}, function (e, v, m, f) { return false; });
  2650. }
  2651. function onDisposeConference(unload) {
  2652. Toolbar.showAuthenticateButton(false);
  2653. }
  2654. function onDisplayNameChanged(jid, displayName) {
  2655. ContactList.onDisplayNameChange(jid, displayName);
  2656. SettingsMenu.onDisplayNameChange(jid, displayName);
  2657. VideoLayout.onDisplayNameChanged(jid, displayName);
  2658. }
  2659. function registerListeners() {
  2660. APP.RTC.addStreamListener(streamHandler,
  2661. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2662. APP.RTC.addStreamListener(streamHandler,
  2663. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2664. APP.RTC.addStreamListener(function (stream) {
  2665. VideoLayout.onRemoteStreamAdded(stream);
  2666. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2667. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2668. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  2669. function (resourceJid) {
  2670. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2671. });
  2672. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2673. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2674. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2675. endpointsEnteringLastN, stream);
  2676. });
  2677. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2678. function (devices) {
  2679. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2680. });
  2681. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  2682. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function () {
  2683. // when the data channel becomes available, tell the bridge about video
  2684. // selections so that it can do adaptive simulcast,
  2685. // we want the notification to trigger even if userJid is undefined,
  2686. // or null.
  2687. var userResource = APP.UI.getLargeVideoResource();
  2688. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userResource);
  2689. });
  2690. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  2691. var resourceJid;
  2692. if(jid === APP.statistics.LOCAL_JID) {
  2693. resourceJid = AudioLevels.LOCAL_LEVEL;
  2694. if(APP.RTC.localAudio.isMuted()) {
  2695. audioLevel = 0;
  2696. }
  2697. } else {
  2698. resourceJid = Strophe.getResourceFromJid(jid);
  2699. }
  2700. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2701. UI.getLargeVideoResource());
  2702. });
  2703. APP.desktopsharing.addListener(function () {
  2704. ToolbarToggler.showDesktopSharingButton();
  2705. }, DesktopSharingEventTypes.INIT);
  2706. APP.desktopsharing.addListener(
  2707. Toolbar.changeDesktopSharingButtonState,
  2708. DesktopSharingEventTypes.SWITCHING_DONE);
  2709. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2710. VideoLayout.updateLocalConnectionStats);
  2711. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2712. VideoLayout.updateConnectionStats);
  2713. APP.connectionquality.addListener(CQEvents.STOP,
  2714. VideoLayout.onStatsStop);
  2715. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2716. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2717. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2718. messageHandler.openMessageDialog(
  2719. 'dialog.serviceUnavailable',
  2720. 'dialog.gracefulShutdown'
  2721. );
  2722. });
  2723. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2724. var title = APP.translation.generateTranslationHTML(
  2725. "dialog.reservationError");
  2726. var message = APP.translation.generateTranslationHTML(
  2727. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2728. messageHandler.openDialog(
  2729. title,
  2730. message,
  2731. true, {},
  2732. function (event, value, message, formVals) {
  2733. return false;
  2734. }
  2735. );
  2736. });
  2737. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2738. messageHandler.openMessageDialog("dialog.sessTerminated",
  2739. "dialog.kickMessage");
  2740. });
  2741. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2742. //FIXME: use Session Terminated from translation, but
  2743. // 'reason' text comes from XMPP packet and is not translated
  2744. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2745. messageHandler.openDialog(
  2746. title, reason, true, {},
  2747. function (event, value, message, formVals) {
  2748. return false;
  2749. }
  2750. );
  2751. });
  2752. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2753. messageHandler.showError("dialog.error",
  2754. "dialog.bridgeUnavailable");
  2755. });
  2756. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2757. Avatar.setUserAvatar(from, id);
  2758. });
  2759. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2760. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2761. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2762. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2763. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2764. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2765. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2766. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2767. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2768. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2769. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2770. onAuthenticationRequired);
  2771. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_VIDEO_TYPE_CHANGED,
  2772. onPeerVideoTypeChanged);
  2773. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2774. function (resource, devices) {
  2775. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2776. });
  2777. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_AUDIO_MUTED,
  2778. VideoLayout.onAudioMute);
  2779. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_VIDEO_MUTED,
  2780. VideoLayout.onVideoMute);
  2781. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function (doMuteAudio) {
  2782. UI.setAudioMuted(doMuteAudio);
  2783. });
  2784. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2785. onDtmfSupportChanged);
  2786. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  2787. SettingsMenu.setStartMuted(audio, video);
  2788. });
  2789. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  2790. UI.setInitialMuteFromFocus(audio, video);
  2791. });
  2792. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  2793. UI.messageHandler.showError("dialog.sorry",
  2794. "dialog.internalError");
  2795. });
  2796. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function () {
  2797. messageHandler.showError("dialog.error",
  2798. "dialog.SLDFailure");
  2799. });
  2800. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function () {
  2801. messageHandler.showError("dialog.error",
  2802. "dialog.SRDFailure");
  2803. });
  2804. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function () {
  2805. messageHandler.showError();
  2806. });
  2807. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function () {
  2808. // FIXME: re-use LoginDialog which supports retries
  2809. UI.showLoginPopup(connect);
  2810. });
  2811. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focusComponent, retrySec) {
  2812. UI.messageHandler.notify(
  2813. null, "notify.focus",
  2814. 'disconnected', "notify.focusFail",
  2815. {component: focusComponent, ms: retrySec});
  2816. });
  2817. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  2818. UI.messageHandler.openReportDialog(null,
  2819. "dialog.joinError", pres);
  2820. });
  2821. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  2822. UI.messageHandler.openReportDialog(null,
  2823. "dialog.connectError", pres);
  2824. });
  2825. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function () {
  2826. var roomName = UI.generateRoomName();
  2827. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  2828. });
  2829. //NicknameHandler emits this event
  2830. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  2831. APP.xmpp.addToPresence("displayName", nickname);
  2832. });
  2833. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  2834. AudioLevels.init();
  2835. });
  2836. if (!interfaceConfig.filmStripOnly) {
  2837. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2838. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2839. // Listens for video interruption events.
  2840. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  2841. // Listens for video restores events.
  2842. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  2843. }
  2844. }
  2845. /**
  2846. * Mutes/unmutes the local video.
  2847. *
  2848. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  2849. * @param options an object which specifies optional arguments such as the
  2850. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  2851. * specifies whether the method was initiated in response to a user command (in
  2852. * contrast to an automatic decision taken by the application logic)
  2853. */
  2854. function setVideoMute(mute, options) {
  2855. APP.RTC.setVideoMute(mute,
  2856. UI.setVideoMuteButtonsState,
  2857. options);
  2858. }
  2859. function onResize() {
  2860. Chat.resizeChat();
  2861. VideoLayout.resizeLargeVideoContainer();
  2862. }
  2863. function bindEvents() {
  2864. /**
  2865. * Resizes and repositions videos in full screen mode.
  2866. */
  2867. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  2868. onResize);
  2869. $(window).resize(onResize);
  2870. }
  2871. UI.start = function (init) {
  2872. document.title = interfaceConfig.APP_NAME;
  2873. var setupWelcomePage = null;
  2874. if(config.enableWelcomePage && window.location.pathname == "/" &&
  2875. (!window.localStorage.welcomePageDisabled ||
  2876. window.localStorage.welcomePageDisabled == "false")) {
  2877. $("#videoconference_page").hide();
  2878. if (!setupWelcomePage)
  2879. setupWelcomePage = require("./welcome_page/WelcomePage");
  2880. setupWelcomePage();
  2881. return;
  2882. }
  2883. $("#welcome_page").hide();
  2884. // Set the defaults for prompt dialogs.
  2885. $.prompt.setDefaults({persistent: false});
  2886. registerListeners();
  2887. VideoLayout.init(eventEmitter);
  2888. NicknameHandler.init(eventEmitter);
  2889. bindEvents();
  2890. setupPrezi();
  2891. if (!interfaceConfig.filmStripOnly) {
  2892. $("#videospace").mousemove(function () {
  2893. return ToolbarToggler.showToolbar();
  2894. });
  2895. setupToolbars();
  2896. setupChat();
  2897. // Display notice message at the top of the toolbar
  2898. if (config.noticeMessage) {
  2899. $('#noticeText').text(config.noticeMessage);
  2900. $('#notice').css({display: 'block'});
  2901. }
  2902. $("#downloadlog").click(function (event) {
  2903. dump(event.target);
  2904. });
  2905. }
  2906. else
  2907. {
  2908. $("#header").css("display", "none");
  2909. $("#bottomToolbar").css("display", "none");
  2910. $("#downloadlog").css("display", "none");
  2911. $("#remoteVideos").css("padding", "0px 0px 18px 0px");
  2912. $("#remoteVideos").css("right", "0px");
  2913. messageHandler.disableNotifications();
  2914. $('body').popover("disable");
  2915. // $("[data-toggle=popover]").popover("disable");
  2916. JitsiPopover.enabled = false;
  2917. }
  2918. document.title = interfaceConfig.APP_NAME;
  2919. if(config.requireDisplayName) {
  2920. var currentSettings = Settings.getSettings();
  2921. if (!currentSettings.displayName) {
  2922. promptDisplayName();
  2923. }
  2924. }
  2925. init();
  2926. if (!interfaceConfig.filmStripOnly) {
  2927. toastr.options = {
  2928. "closeButton": true,
  2929. "debug": false,
  2930. "positionClass": "notification-bottom-right",
  2931. "onclick": null,
  2932. "showDuration": "300",
  2933. "hideDuration": "1000",
  2934. "timeOut": "2000",
  2935. "extendedTimeOut": "1000",
  2936. "showEasing": "swing",
  2937. "hideEasing": "linear",
  2938. "showMethod": "fadeIn",
  2939. "hideMethod": "fadeOut",
  2940. "reposition": function () {
  2941. if (PanelToggler.isVisible()) {
  2942. $("#toast-container").addClass("notification-bottom-right-center");
  2943. } else {
  2944. $("#toast-container").removeClass("notification-bottom-right-center");
  2945. }
  2946. },
  2947. "newestOnTop": false
  2948. };
  2949. SettingsMenu.init();
  2950. }
  2951. };
  2952. function chatAddError(errorMessage, originalText) {
  2953. return Chat.chatAddError(errorMessage, originalText);
  2954. }
  2955. function chatSetSubject(text) {
  2956. return Chat.chatSetSubject(text);
  2957. }
  2958. function updateChatConversation(from, displayName, message, myjid, stamp) {
  2959. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  2960. }
  2961. function onMucJoined(jid, info) {
  2962. Toolbar.updateRoomUrl(window.location.href);
  2963. var meHTML = APP.translation.generateTranslationHTML("me");
  2964. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  2965. var settings = Settings.getSettings();
  2966. // Make sure we configure our avatar id, before creating avatar for us
  2967. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  2968. // Add myself to the contact list.
  2969. ContactList.addContact(jid);
  2970. // Once we've joined the muc show the toolbar
  2971. ToolbarToggler.showToolbar();
  2972. var displayName =
  2973. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  2974. if (displayName)
  2975. onDisplayNameChanged('localVideoContainer', displayName);
  2976. VideoLayout.mucJoined();
  2977. }
  2978. function initEtherpad(name) {
  2979. Etherpad.init(name);
  2980. }
  2981. function onMucMemberLeft(jid) {
  2982. console.log('left.muc', jid);
  2983. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  2984. '>.displayname').html();
  2985. messageHandler.notify(displayName,'notify.somebody',
  2986. 'disconnected',
  2987. 'notify.disconnected');
  2988. if (!config.startAudioMuted ||
  2989. config.startAudioMuted > APP.members.size()) {
  2990. UIUtil.playSoundNotification('userLeft');
  2991. }
  2992. ContactList.removeContact(jid);
  2993. VideoLayout.participantLeft(jid);
  2994. }
  2995. function onLocalRoleChanged(jid, info, pres, isModerator) {
  2996. console.info("My role changed, new role: " + info.role);
  2997. onModeratorStatusChanged(isModerator);
  2998. VideoLayout.showModeratorIndicator();
  2999. SettingsMenu.onRoleChanged();
  3000. if (isModerator) {
  3001. Authentication.closeAuthenticationWindow();
  3002. messageHandler.notify(null, "notify.me",
  3003. 'connected', "notify.moderator");
  3004. Toolbar.checkAutoRecord();
  3005. }
  3006. }
  3007. function onModeratorStatusChanged(isModerator) {
  3008. Toolbar.showSipCallButton(isModerator);
  3009. Toolbar.showRecordingButton(
  3010. isModerator); //&&
  3011. // FIXME:
  3012. // Recording visible if
  3013. // there are at least 2(+ 1 focus) participants
  3014. //Object.keys(connection.emuc.members).length >= 3);
  3015. }
  3016. function onPasswordRequired(callback) {
  3017. // password is required
  3018. Toolbar.lockLockButton();
  3019. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3020. message += APP.translation.translateString(
  3021. "dialog.passwordRequired");
  3022. message += '</h2>' +
  3023. '<input name="lockKey" type="text" data-i18n=' +
  3024. '"[placeholder]dialog.password" placeholder="' +
  3025. APP.translation.translateString("dialog.password") +
  3026. '" autofocus>';
  3027. messageHandler.openTwoButtonDialog(null, null, null, message,
  3028. true,
  3029. "dialog.Ok",
  3030. function (e, v, m, f) {},
  3031. null,
  3032. function (e, v, m, f) {
  3033. if (v) {
  3034. var lockKey = f.lockKey;
  3035. if (lockKey) {
  3036. Toolbar.setSharedKey(lockKey);
  3037. callback(lockKey);
  3038. }
  3039. }
  3040. },
  3041. ':input:first'
  3042. );
  3043. }
  3044. /**
  3045. * The dialpad button is shown iff there is at least one member that supports
  3046. * DTMF (e.g. jigasi).
  3047. */
  3048. function onDtmfSupportChanged(dtmfSupport) {
  3049. //TODO: enable when the UI is ready
  3050. //Toolbar.showDialPadButton(dtmfSupport);
  3051. }
  3052. function onMucMemberJoined(jid, id, displayName) {
  3053. messageHandler.notify(displayName,'notify.somebody',
  3054. 'connected',
  3055. 'notify.connected');
  3056. if (!config.startAudioMuted ||
  3057. config.startAudioMuted > APP.members.size())
  3058. UIUtil.playSoundNotification('userJoined');
  3059. // Configure avatar
  3060. Avatar.setUserAvatar(jid, id);
  3061. // Add Peer's container
  3062. VideoLayout.ensurePeerContainerExists(jid);
  3063. }
  3064. function onMucPresenceStatus(jid, info) {
  3065. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3066. }
  3067. function onPeerVideoTypeChanged(resourceJid, newVideoType) {
  3068. VideoLayout.onVideoTypeChanged(resourceJid, newVideoType);
  3069. }
  3070. function onMucRoleChanged(role, displayName) {
  3071. VideoLayout.showModeratorIndicator();
  3072. if (role === 'moderator') {
  3073. var messageKey, messageOptions = {};
  3074. if (!displayName) {
  3075. messageKey = "notify.grantedToUnknown";
  3076. }
  3077. else {
  3078. messageKey = "notify.grantedTo";
  3079. messageOptions = {to: displayName};
  3080. }
  3081. messageHandler.notify(
  3082. displayName,'notify.somebody',
  3083. 'connected', messageKey,
  3084. messageOptions);
  3085. }
  3086. }
  3087. function onAuthenticationRequired(intervalCallback) {
  3088. Authentication.openAuthenticationDialog(
  3089. roomName, intervalCallback, function () {
  3090. Toolbar.authenticateClicked();
  3091. });
  3092. }
  3093. function onLastNChanged(oldValue, newValue) {
  3094. if (config.muteLocalVideoIfNotInLastN) {
  3095. setVideoMute(!newValue, { 'byUser': false });
  3096. }
  3097. }
  3098. UI.toggleSmileys = function () {
  3099. Chat.toggleSmileys();
  3100. };
  3101. UI.getSettings = function () {
  3102. return Settings.getSettings();
  3103. };
  3104. UI.toggleFilmStrip = function () {
  3105. return BottomToolbar.toggleFilmStrip();
  3106. };
  3107. UI.toggleChat = function () {
  3108. return BottomToolbar.toggleChat();
  3109. };
  3110. UI.toggleContactList = function () {
  3111. return BottomToolbar.toggleContactList();
  3112. };
  3113. UI.inputDisplayNameHandler = function (value) {
  3114. VideoLayout.inputDisplayNameHandler(value);
  3115. };
  3116. UI.getLargeVideoResource = function () {
  3117. return VideoLayout.getLargeVideoResource();
  3118. };
  3119. UI.generateRoomName = function() {
  3120. if(roomName)
  3121. return roomName;
  3122. var roomnode = null;
  3123. var path = window.location.pathname;
  3124. // determinde the room node from the url
  3125. // TODO: just the roomnode or the whole bare jid?
  3126. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3127. // custom function might be responsible for doing the pushstate
  3128. roomnode = config.getroomnode(path);
  3129. } else {
  3130. /* fall back to default strategy
  3131. * this is making assumptions about how the URL->room mapping happens.
  3132. * It currently assumes deployment at root, with a rewrite like the
  3133. * following one (for nginx):
  3134. location ~ ^/([a-zA-Z0-9]+)$ {
  3135. rewrite ^/(.*)$ / break;
  3136. }
  3137. */
  3138. if (path.length > 1) {
  3139. roomnode = path.substr(1).toLowerCase();
  3140. } else {
  3141. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3142. roomnode = word.toLowerCase();
  3143. window.history.pushState('VideoChat',
  3144. 'Room: ' + word, window.location.pathname + word);
  3145. }
  3146. }
  3147. roomName = roomnode + '@' + config.hosts.muc;
  3148. return roomName;
  3149. };
  3150. UI.connectionIndicatorShowMore = function(jid) {
  3151. return VideoLayout.showMore(jid);
  3152. };
  3153. UI.showLoginPopup = function(callback) {
  3154. console.log('password is required');
  3155. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3156. message += APP.translation.translateString(
  3157. "dialog.passwordRequired");
  3158. message += '</h2>' +
  3159. '<input name="username" type="text" ' +
  3160. 'placeholder="user@domain.net" autofocus>' +
  3161. '<input name="password" ' +
  3162. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3163. ' placeholder="user password">';
  3164. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3165. true,
  3166. "dialog.Ok",
  3167. function (e, v, m, f) {
  3168. if (v) {
  3169. if (f.username !== null && f.password != null) {
  3170. callback(f.username, f.password);
  3171. }
  3172. }
  3173. },
  3174. null, null, ':input:first'
  3175. );
  3176. };
  3177. UI.checkForNicknameAndJoin = function () {
  3178. Authentication.closeAuthenticationDialog();
  3179. Authentication.stopInterval();
  3180. var nick = null;
  3181. if (config.useNicks) {
  3182. nick = window.prompt('Your nickname (optional)');
  3183. }
  3184. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3185. };
  3186. function dump(elem, filename) {
  3187. elem = elem.parentNode;
  3188. elem.download = filename || 'meetlog.json';
  3189. elem.href = 'data:application/json;charset=utf-8,\n';
  3190. var data = APP.xmpp.getJingleLog();
  3191. var metadata = {};
  3192. metadata.time = new Date();
  3193. metadata.url = window.location.href;
  3194. metadata.ua = navigator.userAgent;
  3195. var log = APP.xmpp.getXmppLog();
  3196. if (log) {
  3197. metadata.xmpp = log;
  3198. }
  3199. data.metadata = metadata;
  3200. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3201. return false;
  3202. }
  3203. UI.getRoomName = function () {
  3204. return roomName;
  3205. };
  3206. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3207. if (muteAudio || muteVideo)
  3208. notifyForInitialMute();
  3209. if (muteAudio)
  3210. UI.setAudioMuted(true);
  3211. if (muteVideo)
  3212. UI.setVideoMute(true);
  3213. };
  3214. /**
  3215. * Mutes/unmutes the local video.
  3216. */
  3217. UI.toggleVideo = function () {
  3218. setVideoMute(!APP.RTC.localVideo.isMuted());
  3219. };
  3220. /**
  3221. * Mutes / unmutes audio for the local participant.
  3222. */
  3223. UI.toggleAudio = function() {
  3224. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3225. };
  3226. /**
  3227. * Sets muted audio state for the local participant.
  3228. */
  3229. UI.setAudioMuted = function (mute, earlyMute) {
  3230. var audioMute = null;
  3231. if (earlyMute)
  3232. audioMute = function (mute, cb) {
  3233. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3234. };
  3235. else
  3236. audioMute = function (mute, cb) {
  3237. return APP.xmpp.setAudioMute(mute, cb);
  3238. };
  3239. if (!audioMute(mute, function () {
  3240. VideoLayout.showLocalAudioIndicator(mute);
  3241. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3242. })) {
  3243. // We still click the button.
  3244. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3245. return;
  3246. }
  3247. };
  3248. UI.addListener = function (type, listener) {
  3249. eventEmitter.on(type, listener);
  3250. };
  3251. UI.clickOnVideo = function (videoNumber) {
  3252. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3253. if (remoteVideos.length > videoNumber) {
  3254. remoteVideos[videoNumber].click();
  3255. }
  3256. };
  3257. //Used by torture
  3258. UI.showToolbar = function () {
  3259. return ToolbarToggler.showToolbar();
  3260. };
  3261. //Used by torture
  3262. UI.dockToolbar = function (isDock) {
  3263. return ToolbarToggler.dockToolbar(isDock);
  3264. };
  3265. UI.setVideoMuteButtonsState = function (mute) {
  3266. var video = $('#toolbar_button_camera');
  3267. var communicativeClass = "icon-camera";
  3268. var muteClass = "icon-camera icon-camera-disabled";
  3269. if (mute) {
  3270. video.removeClass(communicativeClass);
  3271. video.addClass(muteClass);
  3272. } else {
  3273. video.removeClass(muteClass);
  3274. video.addClass(communicativeClass);
  3275. }
  3276. };
  3277. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3278. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3279. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3280. if(resourceJid === APP.xmpp.myResource())
  3281. SettingsMenu.changeAvatar(thumbUrl);
  3282. };
  3283. UI.setVideoMute = setVideoMute;
  3284. module.exports = UI;
  3285. },{"../../service/RTC/RTCEvents":160,"../../service/RTC/StreamEventTypes":162,"../../service/UI/UIEvents":163,"../../service/connectionquality/CQEvents":165,"../../service/desktopsharing/DesktopSharingEventTypes":166,"../../service/members/Events":167,"../../service/xmpp/XMPPEvents":169,"../RTC/RTCBrowserType":8,"./../settings/Settings":47,"./audio_levels/AudioLevels.js":12,"./authentication/Authentication":14,"./avatar/Avatar":16,"./etherpad/Etherpad.js":17,"./prezi/Prezi.js":18,"./side_pannels/SidePanelToggler":20,"./side_pannels/chat/Chat.js":21,"./side_pannels/contactlist/ContactList":25,"./side_pannels/settings/SettingsMenu":26,"./toolbars/BottomToolbar":27,"./toolbars/Toolbar":28,"./toolbars/ToolbarToggler":29,"./util/JitsiPopover":30,"./util/MessageHandler":31,"./util/NicknameHandler":32,"./util/UIUtil":33,"./videolayout/VideoLayout.js":39,"./welcome_page/RoomnameGenerator":40,"./welcome_page/WelcomePage":41,"events":170}],12:[function(require,module,exports){
  3286. /* global APP, interfaceConfig, $, Strophe */
  3287. var CanvasUtil = require("./CanvasUtils");
  3288. var ASDrawContext = null;
  3289. function initActiveSpeakerAudioLevels() {
  3290. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3291. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3292. // Draw a circle.
  3293. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3294. // Add a shadow around the circle
  3295. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3296. ASDrawContext.shadowOffsetX = 0;
  3297. ASDrawContext.shadowOffsetY = 0;
  3298. }
  3299. /**
  3300. * The audio Levels plugin.
  3301. */
  3302. var AudioLevels = (function(my) {
  3303. var audioLevelCanvasCache = {};
  3304. my.LOCAL_LEVEL = 'local';
  3305. my.init = function () {
  3306. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3307. initActiveSpeakerAudioLevels();
  3308. };
  3309. /**
  3310. * Updates the audio level canvas for the given peerJid. If the canvas
  3311. * didn't exist we create it.
  3312. */
  3313. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3314. var resourceJid = null;
  3315. var videoSpanId = null;
  3316. if (!peerJid)
  3317. videoSpanId = 'localVideoContainer';
  3318. else {
  3319. resourceJid = Strophe.getResourceFromJid(peerJid);
  3320. videoSpanId = 'participant_' + resourceJid;
  3321. }
  3322. var videoSpan = document.getElementById(videoSpanId);
  3323. if (!videoSpan) {
  3324. if (resourceJid)
  3325. console.error("No video element for jid", resourceJid);
  3326. else
  3327. console.error("No video element for local video.");
  3328. return;
  3329. }
  3330. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3331. var videoSpaceWidth = $('#remoteVideos').width();
  3332. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3333. var thumbnailWidth = thumbnailSize[0];
  3334. var thumbnailHeight = thumbnailSize[1];
  3335. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3336. audioLevelCanvas = document.createElement('canvas');
  3337. audioLevelCanvas.className = "audiolevel";
  3338. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3339. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3340. resizeAudioLevelCanvas( audioLevelCanvas,
  3341. thumbnailWidth,
  3342. thumbnailHeight);
  3343. videoSpan.appendChild(audioLevelCanvas);
  3344. } else {
  3345. audioLevelCanvas = audioLevelCanvas.get(0);
  3346. resizeAudioLevelCanvas( audioLevelCanvas,
  3347. thumbnailWidth,
  3348. thumbnailHeight);
  3349. }
  3350. };
  3351. /**
  3352. * Updates the audio level UI for the given resourceJid.
  3353. *
  3354. * @param resourceJid the resource jid indicating the video element for
  3355. * which we draw the audio level
  3356. * @param audioLevel the newAudio level to render
  3357. */
  3358. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3359. drawAudioLevelCanvas(resourceJid, audioLevel);
  3360. var videoSpanId = getVideoSpanId(resourceJid);
  3361. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3362. if (!audioLevelCanvas)
  3363. return;
  3364. var drawContext = audioLevelCanvas.getContext('2d');
  3365. var canvasCache = audioLevelCanvasCache[resourceJid];
  3366. drawContext.clearRect (0, 0,
  3367. audioLevelCanvas.width, audioLevelCanvas.height);
  3368. drawContext.drawImage(canvasCache, 0, 0);
  3369. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3370. if(!APP.xmpp.myJid()) {
  3371. return;
  3372. }
  3373. resourceJid = APP.xmpp.myResource();
  3374. }
  3375. if(resourceJid === largeVideoResourceJid) {
  3376. window.requestAnimationFrame(function () {
  3377. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3378. });
  3379. }
  3380. };
  3381. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3382. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3383. return;
  3384. ASDrawContext.clearRect(0, 0, 300, 300);
  3385. if(audioLevel == 0)
  3386. return;
  3387. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3388. // Fill the shape.
  3389. ASDrawContext.fill();
  3390. };
  3391. /**
  3392. * Resizes the given audio level canvas to match the given thumbnail size.
  3393. */
  3394. function resizeAudioLevelCanvas(audioLevelCanvas,
  3395. thumbnailWidth,
  3396. thumbnailHeight) {
  3397. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3398. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3399. }
  3400. /**
  3401. * Draws the audio level canvas into the cached canvas object.
  3402. *
  3403. * @param resourceJid the resource jid indicating the video element for
  3404. * which we draw the audio level
  3405. * @param audioLevel the newAudio level to render
  3406. */
  3407. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3408. if (!audioLevelCanvasCache[resourceJid]) {
  3409. var videoSpanId = getVideoSpanId(resourceJid);
  3410. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3411. /*
  3412. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3413. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3414. * error. Since audio levels are frequently updated, the errors have
  3415. * been observed to pile into the console, strain the CPU.
  3416. */
  3417. if (audioLevelCanvasOrig) {
  3418. audioLevelCanvasCache[resourceJid] =
  3419. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3420. }
  3421. }
  3422. var canvas = audioLevelCanvasCache[resourceJid];
  3423. if (!canvas)
  3424. return;
  3425. var drawContext = canvas.getContext('2d');
  3426. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3427. var shadowLevel = getShadowLevel(audioLevel);
  3428. if (shadowLevel > 0) {
  3429. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3430. CanvasUtil.drawRoundRectGlow(drawContext,
  3431. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3432. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3433. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3434. interfaceConfig.CANVAS_RADIUS,
  3435. interfaceConfig.SHADOW_COLOR,
  3436. shadowLevel);
  3437. }
  3438. }
  3439. /**
  3440. * Returns the shadow/glow level for the given audio level.
  3441. *
  3442. * @param audioLevel the audio level from which we determine the shadow
  3443. * level
  3444. */
  3445. function getShadowLevel (audioLevel) {
  3446. var shadowLevel = 0;
  3447. if (audioLevel <= 0.3) {
  3448. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3449. }
  3450. else if (audioLevel <= 0.6) {
  3451. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3452. }
  3453. else {
  3454. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3455. }
  3456. return shadowLevel;
  3457. }
  3458. /**
  3459. * Returns the video span id corresponding to the given resourceJid or local
  3460. * user.
  3461. */
  3462. function getVideoSpanId(resourceJid) {
  3463. var videoSpanId = null;
  3464. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3465. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3466. videoSpanId = 'localVideoContainer';
  3467. else
  3468. videoSpanId = 'participant_' + resourceJid;
  3469. return videoSpanId;
  3470. }
  3471. /**
  3472. * Indicates that the remote video has been resized.
  3473. */
  3474. $(document).bind('remotevideo.resized', function (event, width, height) {
  3475. var resized = false;
  3476. $('#remoteVideos>span>canvas').each(function() {
  3477. var canvas = $(this).get(0);
  3478. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3479. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3480. resized = true;
  3481. }
  3482. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3483. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3484. resized = true;
  3485. }
  3486. });
  3487. if (resized)
  3488. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3489. audioLevelCanvasCache[resourceJid].width =
  3490. width + interfaceConfig.CANVAS_EXTRA;
  3491. audioLevelCanvasCache[resourceJid].height =
  3492. height + interfaceConfig.CANVAS_EXTRA;
  3493. });
  3494. });
  3495. return my;
  3496. })(AudioLevels || {});
  3497. module.exports = AudioLevels;
  3498. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3499. /**
  3500. * Utility class for drawing canvas shapes.
  3501. */
  3502. var CanvasUtil = (function(my) {
  3503. /**
  3504. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3505. * of the glow.
  3506. *
  3507. * @param drawContext the context of the canvas to draw to
  3508. * @param x the x coordinate of the round rectangle
  3509. * @param y the y coordinate of the round rectangle
  3510. * @param w the width of the round rectangle
  3511. * @param h the height of the round rectangle
  3512. * @param glowColor the color of the glow
  3513. * @param glowWidth the width of the glow
  3514. */
  3515. my.drawRoundRectGlow
  3516. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3517. // Save the previous state of the context.
  3518. drawContext.save();
  3519. if (w < 2 * r) r = w / 2;
  3520. if (h < 2 * r) r = h / 2;
  3521. // Draw a round rectangle.
  3522. drawContext.beginPath();
  3523. drawContext.moveTo(x+r, y);
  3524. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3525. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3526. drawContext.arcTo(x, y+h, x, y, r);
  3527. drawContext.arcTo(x, y, x+w, y, r);
  3528. drawContext.closePath();
  3529. // Add a shadow around the rectangle
  3530. drawContext.shadowColor = glowColor;
  3531. drawContext.shadowBlur = glowWidth;
  3532. drawContext.shadowOffsetX = 0;
  3533. drawContext.shadowOffsetY = 0;
  3534. // Fill the shape.
  3535. drawContext.fill();
  3536. drawContext.save();
  3537. drawContext.restore();
  3538. // 1) Uncomment this line to use Composite Operation, which is doing the
  3539. // same as the clip function below and is also antialiasing the round
  3540. // border, but is said to be less fast performance wise.
  3541. // drawContext.globalCompositeOperation='destination-out';
  3542. drawContext.beginPath();
  3543. drawContext.moveTo(x+r, y);
  3544. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3545. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3546. drawContext.arcTo(x, y+h, x, y, r);
  3547. drawContext.arcTo(x, y, x+w, y, r);
  3548. drawContext.closePath();
  3549. // 2) Uncomment this line to use Composite Operation, which is doing the
  3550. // same as the clip function below and is also antialiasing the round
  3551. // border, but is said to be less fast performance wise.
  3552. // drawContext.fill();
  3553. // Comment these two lines if choosing to do the same with composite
  3554. // operation above 1 and 2.
  3555. drawContext.clip();
  3556. drawContext.clearRect(0, 0, 277, 200);
  3557. // Restore the previous context state.
  3558. drawContext.restore();
  3559. };
  3560. /**
  3561. * Clones the given canvas.
  3562. *
  3563. * @return the new cloned canvas.
  3564. */
  3565. my.cloneCanvas = function (oldCanvas) {
  3566. /*
  3567. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3568. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3569. * levels are frequently updated, the errors have been observed to pile
  3570. * into the console, strain the CPU.
  3571. */
  3572. if (!oldCanvas)
  3573. return oldCanvas;
  3574. //create a new canvas
  3575. var newCanvas = document.createElement('canvas');
  3576. var context = newCanvas.getContext('2d');
  3577. //set dimensions
  3578. newCanvas.width = oldCanvas.width;
  3579. newCanvas.height = oldCanvas.height;
  3580. //apply the old canvas to the new one
  3581. context.drawImage(oldCanvas, 0, 0);
  3582. //return the new canvas
  3583. return newCanvas;
  3584. };
  3585. return my;
  3586. })(CanvasUtil || {});
  3587. module.exports = CanvasUtil;
  3588. },{}],14:[function(require,module,exports){
  3589. /* global $, APP*/
  3590. var LoginDialog = require('./LoginDialog');
  3591. var Moderator = require('../../xmpp/moderator');
  3592. /* Initial "authentication required" dialog */
  3593. var authDialog = null;
  3594. /* Loop retry ID that wits for other user to create the room */
  3595. var authRetryId = null;
  3596. var authenticationWindow = null;
  3597. var Authentication = {
  3598. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3599. // This is the loop that will wait for the room to be created by
  3600. // someone else. 'auth_required.moderator' will bring us back here.
  3601. authRetryId = window.setTimeout(intervalCallback, 5000);
  3602. // Show prompt only if it's not open
  3603. if (authDialog !== null) {
  3604. return;
  3605. }
  3606. // extract room name from 'room@muc.server.net'
  3607. var room = roomName.substr(0, roomName.indexOf('@'));
  3608. var title
  3609. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3610. var msg
  3611. = APP.translation.generateTranslationHTML(
  3612. "dialog.WaitForHostMsg", {room: room});
  3613. var buttonTxt
  3614. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3615. var buttons = [];
  3616. buttons.push({title: buttonTxt, value: "authNow"});
  3617. authDialog = APP.UI.messageHandler.openDialog(
  3618. title,
  3619. msg,
  3620. true,
  3621. buttons,
  3622. function (onSubmitEvent, submitValue) {
  3623. // Do not close the dialog yet
  3624. onSubmitEvent.preventDefault();
  3625. // Open login popup
  3626. if (submitValue === 'authNow') {
  3627. callback();
  3628. }
  3629. }
  3630. );
  3631. },
  3632. closeAuthenticationWindow: function () {
  3633. if (authenticationWindow) {
  3634. authenticationWindow.close();
  3635. authenticationWindow = null;
  3636. }
  3637. },
  3638. xmppAuthenticate: function () {
  3639. var loginDialog = LoginDialog.show(
  3640. function (connection, state) {
  3641. if (!state) {
  3642. // User cancelled
  3643. loginDialog.close();
  3644. return;
  3645. } else if (state == APP.xmpp.Status.CONNECTED) {
  3646. loginDialog.close();
  3647. Authentication.stopInterval();
  3648. Authentication.closeAuthenticationDialog();
  3649. // Close the connection as anonymous one will be used
  3650. // to create the conference. Session-id will authorize
  3651. // the request.
  3652. connection.disconnect();
  3653. var roomName = APP.UI.generateRoomName();
  3654. Moderator.allocateConferenceFocus(roomName, function () {
  3655. // If it's not "on the fly" authentication now join
  3656. // the conference room
  3657. if (!APP.xmpp.isMUCJoined()) {
  3658. APP.UI.checkForNicknameAndJoin();
  3659. }
  3660. });
  3661. }
  3662. }, true);
  3663. },
  3664. focusAuthenticationWindow: function () {
  3665. // If auth window exists just bring it to the front
  3666. if (authenticationWindow) {
  3667. authenticationWindow.focus();
  3668. return;
  3669. }
  3670. },
  3671. closeAuthenticationDialog: function () {
  3672. // Close authentication dialog if opened
  3673. if (authDialog) {
  3674. authDialog.close();
  3675. authDialog = null;
  3676. }
  3677. },
  3678. createAuthenticationWindow: function (callback, url) {
  3679. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3680. url, 910, 660,
  3681. // On closed
  3682. function () {
  3683. // Close authentication dialog if opened
  3684. Authentication.closeAuthenticationDialog();
  3685. callback();
  3686. authenticationWindow = null;
  3687. });
  3688. return authenticationWindow;
  3689. },
  3690. stopInterval: function () {
  3691. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3692. if (authRetryId) {
  3693. window.clearTimeout(authRetryId);
  3694. authRetryId = null;
  3695. }
  3696. }
  3697. };
  3698. module.exports = Authentication;
  3699. },{"../../xmpp/moderator":60,"./LoginDialog":15}],15:[function(require,module,exports){
  3700. /* global $, APP, config*/
  3701. var XMPP = require('../../xmpp/xmpp');
  3702. var Moderator = require('../../xmpp/moderator');
  3703. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3704. // anonymous domain is not enabled
  3705. /**
  3706. * Creates new <tt>Dialog</tt> instance.
  3707. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3708. * when we either fail to connect or succeed(check Strophe.Status).
  3709. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3710. * in order to create session-id after the connection is established.
  3711. * @constructor
  3712. */
  3713. function Dialog(callback, obtainSession) {
  3714. var self = this;
  3715. var stop = false;
  3716. var connection = APP.xmpp.createConnection();
  3717. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3718. message += APP.translation.translateString("dialog.passwordRequired");
  3719. message += '</h2>' +
  3720. '<input name="username" type="text" ' +
  3721. 'placeholder="user@domain.net" autofocus>' +
  3722. '<input name="password" ' +
  3723. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3724. ' placeholder="user password">';
  3725. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3726. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3727. var states = {
  3728. login: {
  3729. html: message,
  3730. buttons: [
  3731. { title: okButton, value: true},
  3732. { title: cancelButton, value: false}
  3733. ],
  3734. focus: ':input:first',
  3735. submit: function (e, v, m, f) {
  3736. e.preventDefault();
  3737. if (v) {
  3738. var jid = f.username;
  3739. var password = f.password;
  3740. if (jid && password) {
  3741. stop = false;
  3742. connection.reset();
  3743. connDialog.goToState('connecting');
  3744. connection.connect(jid, password, stateHandler);
  3745. }
  3746. } else {
  3747. // User cancelled
  3748. stop = true;
  3749. callback();
  3750. }
  3751. }
  3752. },
  3753. connecting: {
  3754. title: APP.translation.translateString('dialog.connecting'),
  3755. html: '<div id="connectionStatus"></div>',
  3756. buttons: [],
  3757. defaultButton: 0
  3758. },
  3759. finished: {
  3760. title: APP.translation.translateString('dialog.error'),
  3761. html: '<div id="errorMessage"></div>',
  3762. buttons: [
  3763. {
  3764. title: APP.translation.translateString('dialog.retry'),
  3765. value: 'retry'
  3766. },
  3767. {
  3768. title: APP.translation.translateString('dialog.Cancel'),
  3769. value: 'cancel'
  3770. },
  3771. ],
  3772. defaultButton: 0,
  3773. submit: function (e, v, m, f) {
  3774. e.preventDefault();
  3775. if (v === 'retry')
  3776. connDialog.goToState('login');
  3777. else
  3778. callback();
  3779. }
  3780. }
  3781. };
  3782. var connDialog
  3783. = APP.UI.messageHandler.openDialogWithStates(states,
  3784. { persistent: true, closeText: '' }, null);
  3785. var stateHandler = function (status, message) {
  3786. if (stop) {
  3787. return;
  3788. }
  3789. var translateKey = "connection." + XMPP.getStatusString(status);
  3790. var statusStr = APP.translation.translateString(translateKey);
  3791. // Display current state
  3792. var connectionStatus =
  3793. connDialog.getState('connecting').find('#connectionStatus');
  3794. connectionStatus.text(statusStr);
  3795. switch (status) {
  3796. case XMPP.Status.CONNECTED:
  3797. stop = true;
  3798. if (!obtainSession) {
  3799. callback(connection, status);
  3800. return;
  3801. }
  3802. // Obtaining session-id status
  3803. connectionStatus.text(
  3804. APP.translation.translateString(
  3805. 'connection.FETCH_SESSION_ID'));
  3806. // Authenticate with Jicofo and obtain session-id
  3807. var roomName = APP.UI.generateRoomName();
  3808. // Jicofo will return new session-id when connected
  3809. // from authenticated domain
  3810. connection.sendIQ(
  3811. Moderator.createConferenceIq(roomName),
  3812. function (result) {
  3813. connectionStatus.text(
  3814. APP.translation.translateString(
  3815. 'connection.GOT_SESSION_ID'));
  3816. stop = true;
  3817. // Parse session-id
  3818. Moderator.parseSessionId(result);
  3819. callback(connection, status);
  3820. },
  3821. function (error) {
  3822. console.error("Auth on the fly failed", error);
  3823. stop = true;
  3824. var errorMsg =
  3825. APP.translation.translateString(
  3826. 'connection.GET_SESSION_ID_ERROR') +
  3827. $(error).find('>error').attr('code');
  3828. self.displayError(errorMsg);
  3829. connection.disconnect();
  3830. });
  3831. break;
  3832. case XMPP.Status.AUTHFAIL:
  3833. case XMPP.Status.CONNFAIL:
  3834. case XMPP.Status.DISCONNECTED:
  3835. stop = true;
  3836. callback(connection, status);
  3837. var errorMessage = statusStr;
  3838. if (message)
  3839. {
  3840. errorMessage += ': ' + message;
  3841. }
  3842. self.displayError(errorMessage);
  3843. break;
  3844. default:
  3845. break;
  3846. }
  3847. };
  3848. /**
  3849. * Displays error message in 'finished' state which allows either to cancel
  3850. * or retry.
  3851. * @param message the final message to be displayed.
  3852. */
  3853. this.displayError = function (message) {
  3854. var finishedState = connDialog.getState('finished');
  3855. var errorMessageElem = finishedState.find('#errorMessage');
  3856. errorMessageElem.text(message);
  3857. connDialog.goToState('finished');
  3858. };
  3859. /**
  3860. * Closes LoginDialog.
  3861. */
  3862. this.close = function () {
  3863. stop = true;
  3864. connDialog.close();
  3865. };
  3866. }
  3867. var LoginDialog = {
  3868. /**
  3869. * Displays login prompt used to establish new XMPP connection. Given
  3870. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  3871. * called when we connect successfully(status === CONNECTED) or when we fail
  3872. * to do so. On connection failure program can call Dialog.close() method in
  3873. * order to cancel or do nothing to let the user retry.
  3874. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  3875. * called when we either fail to connect or succeed(check
  3876. * Strophe.Status).
  3877. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  3878. * Jicofo in order to create session-id after the connection is
  3879. * established.
  3880. * @returns {Dialog}
  3881. */
  3882. show: function (callback, obtainSession) {
  3883. return new Dialog(callback, obtainSession);
  3884. }
  3885. };
  3886. module.exports = LoginDialog;
  3887. },{"../../xmpp/moderator":60,"../../xmpp/xmpp":68}],16:[function(require,module,exports){
  3888. var Settings = require("../../settings/Settings");
  3889. var users = {};
  3890. var Avatar = {
  3891. /**
  3892. * Sets the user's avatar in the settings menu(if local user), contact list
  3893. * and thumbnail
  3894. * @param jid jid of the user
  3895. * @param id email or userID to be used as a hash
  3896. */
  3897. setUserAvatar: function (jid, id) {
  3898. if (id) {
  3899. if (users[jid] === id) {
  3900. return;
  3901. }
  3902. users[jid] = id;
  3903. }
  3904. var thumbUrl = this.getThumbUrl(jid);
  3905. var contactListUrl = this.getContactListUrl(jid);
  3906. var resourceJid = Strophe.getResourceFromJid(jid);
  3907. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  3908. },
  3909. /**
  3910. * Returns image URL for the avatar to be displayed on large video area
  3911. * where current active speaker is presented.
  3912. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  3913. */
  3914. getActiveSpeakerUrl: function (jid) {
  3915. return this.getGravatarUrl(jid, 100);
  3916. },
  3917. /**
  3918. * Returns image URL for the avatar to be displayed on small video thumbnail
  3919. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  3920. */
  3921. getThumbUrl: function (jid) {
  3922. return this.getGravatarUrl(jid, 100);
  3923. },
  3924. /**
  3925. * Returns the URL for the avatar to be displayed as contactlist item
  3926. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  3927. */
  3928. getContactListUrl: function (jid) {
  3929. return this.getGravatarUrl(jid, 30);
  3930. },
  3931. getGravatarUrl: function (jid, size) {
  3932. if (!jid) {
  3933. console.error("Get gravatar - jid is undefined");
  3934. return null;
  3935. }
  3936. var id = users[jid];
  3937. if (!id) {
  3938. console.warn(
  3939. "No avatar stored yet for " + jid + " - using JID as ID");
  3940. id = jid;
  3941. }
  3942. return 'https://www.gravatar.com/avatar/' +
  3943. MD5.hexdigest(id.trim().toLowerCase()) +
  3944. "?d=wavatar&size=" + (size || "30");
  3945. }
  3946. };
  3947. module.exports = Avatar;
  3948. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  3949. /* global $, config,
  3950. setLargeVideoVisible, Util */
  3951. var VideoLayout = require("../videolayout/VideoLayout");
  3952. var Prezi = require("../prezi/Prezi");
  3953. var UIUtil = require("../util/UIUtil");
  3954. var etherpadName = null;
  3955. var etherpadIFrame = null;
  3956. var domain = null;
  3957. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  3958. /**
  3959. * Resizes the etherpad.
  3960. */
  3961. function resize() {
  3962. if ($('#etherpad>iframe').length) {
  3963. var remoteVideos = $('#remoteVideos');
  3964. var availableHeight
  3965. = window.innerHeight - remoteVideos.outerHeight();
  3966. var availableWidth = UIUtil.getAvailableVideoWidth();
  3967. $('#etherpad>iframe').width(availableWidth);
  3968. $('#etherpad>iframe').height(availableHeight);
  3969. }
  3970. }
  3971. /**
  3972. * Creates the Etherpad button and adds it to the toolbar.
  3973. */
  3974. function enableEtherpadButton() {
  3975. if (!$('#toolbar_button_etherpad').is(":visible"))
  3976. $('#toolbar_button_etherpad').css({display: 'inline-block'});
  3977. }
  3978. /**
  3979. * Creates the IFrame for the etherpad.
  3980. */
  3981. function createIFrame() {
  3982. etherpadIFrame = VideoLayout.createEtherpadIframe(
  3983. domain + etherpadName + options, function() {
  3984. document.domain = document.domain;
  3985. bubbleIframeMouseMove(etherpadIFrame);
  3986. setTimeout(function() {
  3987. // the iframes inside of the etherpad are
  3988. // not yet loaded when the etherpad iframe is loaded
  3989. var outer = etherpadIFrame.
  3990. contentDocument.getElementsByName("ace_outer")[0];
  3991. bubbleIframeMouseMove(outer);
  3992. var inner = outer.
  3993. contentDocument.getElementsByName("ace_inner")[0];
  3994. bubbleIframeMouseMove(inner);
  3995. }, 2000);
  3996. });
  3997. }
  3998. function bubbleIframeMouseMove(iframe){
  3999. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4000. iframe.contentWindow.onmousemove = function(e){
  4001. if(existingOnMouseMove) existingOnMouseMove(e);
  4002. var evt = document.createEvent("MouseEvents");
  4003. var boundingClientRect = iframe.getBoundingClientRect();
  4004. evt.initMouseEvent(
  4005. "mousemove",
  4006. true, // bubbles
  4007. false, // not cancelable
  4008. window,
  4009. e.detail,
  4010. e.screenX,
  4011. e.screenY,
  4012. e.clientX + boundingClientRect.left,
  4013. e.clientY + boundingClientRect.top,
  4014. e.ctrlKey,
  4015. e.altKey,
  4016. e.shiftKey,
  4017. e.metaKey,
  4018. e.button,
  4019. null // no related element
  4020. );
  4021. iframe.dispatchEvent(evt);
  4022. };
  4023. }
  4024. var Etherpad = {
  4025. /**
  4026. * Initializes the etherpad.
  4027. */
  4028. init: function (name) {
  4029. if (config.etherpad_base && !etherpadName && name) {
  4030. domain = config.etherpad_base;
  4031. etherpadName = name;
  4032. enableEtherpadButton();
  4033. /**
  4034. * Resizes the etherpad, when the window is resized.
  4035. */
  4036. $(window).resize(function () {
  4037. resize();
  4038. });
  4039. }
  4040. },
  4041. /**
  4042. * Opens/hides the Etherpad.
  4043. */
  4044. toggleEtherpad: function (isPresentation) {
  4045. if (!etherpadIFrame)
  4046. createIFrame();
  4047. if(VideoLayout.getLargeVideoState() === "etherpad")
  4048. {
  4049. VideoLayout.setLargeVideoState("video");
  4050. }
  4051. else
  4052. {
  4053. VideoLayout.setLargeVideoState("etherpad");
  4054. }
  4055. resize();
  4056. }
  4057. };
  4058. module.exports = Etherpad;
  4059. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4060. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4061. var UIUtil = require("../util/UIUtil");
  4062. var VideoLayout = require("../videolayout/VideoLayout");
  4063. var messageHandler = require("../util/MessageHandler");
  4064. var PreziPlayer = require("./PreziPlayer");
  4065. var preziPlayer = null;
  4066. /**
  4067. * Shows/hides a presentation.
  4068. */
  4069. function setPresentationVisible(visible) {
  4070. if (visible) {
  4071. VideoLayout.setLargeVideoState("prezi");
  4072. }
  4073. else {
  4074. VideoLayout.setLargeVideoState("video");
  4075. }
  4076. }
  4077. var Prezi = {
  4078. /**
  4079. * Reloads the current presentation.
  4080. */
  4081. reloadPresentation: function() {
  4082. var iframe = document.getElementById(preziPlayer.options.preziId);
  4083. iframe.src = iframe.src;
  4084. },
  4085. /**
  4086. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4087. * otherwise.
  4088. */
  4089. isPresentationVisible: function () {
  4090. return ($('#presentation>iframe') != null
  4091. && $('#presentation>iframe').css('opacity') == 1);
  4092. },
  4093. /**
  4094. * Opens the Prezi dialog, from which the user could choose a presentation
  4095. * to load.
  4096. */
  4097. openPreziDialog: function() {
  4098. var myprezi = APP.xmpp.getPrezi();
  4099. if (myprezi) {
  4100. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4101. null,
  4102. "dialog.removePreziMsg",
  4103. null,
  4104. false,
  4105. "dialog.Remove",
  4106. function(e,v,m,f) {
  4107. if(v) {
  4108. APP.xmpp.removePreziFromPresence();
  4109. }
  4110. }
  4111. );
  4112. }
  4113. else if (preziPlayer != null) {
  4114. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4115. null, "dialog.sharePreziMsg",
  4116. null,
  4117. false,
  4118. "dialog.Ok",
  4119. function(e,v,m,f) {
  4120. $.prompt.close();
  4121. }
  4122. );
  4123. }
  4124. else {
  4125. var html = APP.translation.generateTranslationHTML(
  4126. "dialog.sharePreziTitle");
  4127. var cancelButton = APP.translation.generateTranslationHTML(
  4128. "dialog.Cancel");
  4129. var shareButton = APP.translation.generateTranslationHTML(
  4130. "dialog.Share");
  4131. var backButton = APP.translation.generateTranslationHTML(
  4132. "dialog.Back");
  4133. var buttons = [];
  4134. var buttons1 = [];
  4135. // Cancel button to both states
  4136. buttons.push({title: cancelButton, value: false});
  4137. buttons1.push({title: cancelButton, value: false});
  4138. // Share button
  4139. buttons.push({title: shareButton, value: true});
  4140. // Back button
  4141. buttons1.push({title: backButton, value: true});
  4142. var linkError = APP.translation.generateTranslationHTML(
  4143. "dialog.preziLinkError");
  4144. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4145. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4146. var openPreziState = {
  4147. state0: {
  4148. html: '<h2>' + html + '</h2>' +
  4149. '<input name="preziUrl" type="text" ' +
  4150. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4151. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4152. '\' placeholder="' + defaultUrl + '" autofocus>',
  4153. persistent: false,
  4154. buttons: buttons,
  4155. focus: ':input:first',
  4156. defaultButton: 0,
  4157. submit: function (e, v, m, f) {
  4158. e.preventDefault();
  4159. if(v)
  4160. {
  4161. var preziUrl = f.preziUrl;
  4162. if (preziUrl)
  4163. {
  4164. var urlValue
  4165. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4166. if (urlValue.indexOf('http://prezi.com/') != 0
  4167. && urlValue.indexOf('https://prezi.com/') != 0)
  4168. {
  4169. $.prompt.goToState('state1');
  4170. return false;
  4171. }
  4172. else {
  4173. var presIdTmp = urlValue.substring(
  4174. urlValue.indexOf("prezi.com/") + 10);
  4175. if (!isAlphanumeric(presIdTmp)
  4176. || presIdTmp.indexOf('/') < 2) {
  4177. $.prompt.goToState('state1');
  4178. return false;
  4179. }
  4180. else {
  4181. APP.xmpp.addToPresence("prezi", urlValue);
  4182. $.prompt.close();
  4183. }
  4184. }
  4185. }
  4186. }
  4187. else
  4188. $.prompt.close();
  4189. }
  4190. },
  4191. state1: {
  4192. html: '<h2>' + html + '</h2>' +
  4193. linkError,
  4194. persistent: false,
  4195. buttons: buttons1,
  4196. focus: ':input:first',
  4197. defaultButton: 1,
  4198. submit: function (e, v, m, f) {
  4199. e.preventDefault();
  4200. if (v === 0)
  4201. $.prompt.close();
  4202. else
  4203. $.prompt.goToState('state0');
  4204. }
  4205. }
  4206. };
  4207. messageHandler.openDialogWithStates(openPreziState);
  4208. }
  4209. }
  4210. };
  4211. /**
  4212. * A new presentation has been added.
  4213. *
  4214. * @param event the event indicating the add of a presentation
  4215. * @param jid the jid from which the presentation was added
  4216. * @param presUrl url of the presentation
  4217. * @param currentSlide the current slide to which we should move
  4218. */
  4219. function presentationAdded(event, jid, presUrl, currentSlide) {
  4220. console.log("presentation added", presUrl);
  4221. var presId = getPresentationId(presUrl);
  4222. var elementId = 'participant_'
  4223. + Strophe.getResourceFromJid(jid)
  4224. + '_' + presId;
  4225. VideoLayout.addPreziContainer(elementId);
  4226. var controlsEnabled = false;
  4227. if (jid === APP.xmpp.myJid())
  4228. controlsEnabled = true;
  4229. setPresentationVisible(true);
  4230. VideoLayout.setLargeVideoHover(
  4231. function (event) {
  4232. if (Prezi.isPresentationVisible()) {
  4233. var reloadButtonRight = window.innerWidth
  4234. - $('#presentation>iframe').offset().left
  4235. - $('#presentation>iframe').width();
  4236. $('#reloadPresentation').css({ right: reloadButtonRight,
  4237. display:'inline-block'});
  4238. }
  4239. },
  4240. function (event) {
  4241. if (!Prezi.isPresentationVisible())
  4242. $('#reloadPresentation').css({display:'none'});
  4243. else {
  4244. var e = event.toElement || event.relatedTarget;
  4245. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4246. $('#reloadPresentation').css({display:'none'});
  4247. }
  4248. });
  4249. preziPlayer = new PreziPlayer(
  4250. 'presentation',
  4251. {preziId: presId,
  4252. width: getPresentationWidth(),
  4253. height: getPresentationHeihgt(),
  4254. controls: controlsEnabled,
  4255. debug: true
  4256. });
  4257. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4258. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4259. console.log("prezi status", event.value);
  4260. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4261. if (jid != APP.xmpp.myJid())
  4262. preziPlayer.flyToStep(currentSlide);
  4263. }
  4264. });
  4265. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4266. console.log("event value", event.value);
  4267. APP.xmpp.addToPresence("preziSlide", event.value);
  4268. });
  4269. $("#" + elementId).css( 'background-image',
  4270. 'url(../images/avatarprezi.png)');
  4271. $("#" + elementId).click(
  4272. function () {
  4273. setPresentationVisible(true);
  4274. }
  4275. );
  4276. };
  4277. /**
  4278. * A presentation has been removed.
  4279. *
  4280. * @param event the event indicating the remove of a presentation
  4281. * @param jid the jid for which the presentation was removed
  4282. * @param the url of the presentation
  4283. */
  4284. function presentationRemoved(event, jid, presUrl) {
  4285. console.log('presentation removed', presUrl);
  4286. var presId = getPresentationId(presUrl);
  4287. setPresentationVisible(false);
  4288. $('#participant_'
  4289. + Strophe.getResourceFromJid(jid)
  4290. + '_' + presId).remove();
  4291. $('#presentation>iframe').remove();
  4292. if (preziPlayer != null) {
  4293. preziPlayer.destroy();
  4294. preziPlayer = null;
  4295. }
  4296. };
  4297. /**
  4298. * Indicates if the given string is an alphanumeric string.
  4299. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4300. * purpose of checking URIs.
  4301. */
  4302. function isAlphanumeric(unsafeText) {
  4303. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4304. return regex.test(unsafeText);
  4305. }
  4306. /**
  4307. * Returns the presentation id from the given url.
  4308. */
  4309. function getPresentationId (presUrl) {
  4310. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4311. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4312. }
  4313. /**
  4314. * Returns the presentation width.
  4315. */
  4316. function getPresentationWidth() {
  4317. var availableWidth = UIUtil.getAvailableVideoWidth();
  4318. var availableHeight = getPresentationHeihgt();
  4319. var aspectRatio = 16.0 / 9.0;
  4320. if (availableHeight < availableWidth / aspectRatio) {
  4321. availableWidth = Math.floor(availableHeight * aspectRatio);
  4322. }
  4323. return availableWidth;
  4324. }
  4325. /**
  4326. * Returns the presentation height.
  4327. */
  4328. function getPresentationHeihgt() {
  4329. var remoteVideos = $('#remoteVideos');
  4330. return window.innerHeight - remoteVideos.outerHeight();
  4331. }
  4332. /**
  4333. * Resizes the presentation iframe.
  4334. */
  4335. function resize() {
  4336. if ($('#presentation>iframe')) {
  4337. $('#presentation>iframe').width(getPresentationWidth());
  4338. $('#presentation>iframe').height(getPresentationHeihgt());
  4339. }
  4340. }
  4341. /**
  4342. * Presentation has been removed.
  4343. */
  4344. $(document).bind('presentationremoved.muc', presentationRemoved);
  4345. /**
  4346. * Presentation has been added.
  4347. */
  4348. $(document).bind('presentationadded.muc', presentationAdded);
  4349. /*
  4350. * Indicates presentation slide change.
  4351. */
  4352. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4353. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4354. preziPlayer.flyToStep(current);
  4355. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4356. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4357. preziPlayer.flyToStep(current, i);
  4358. }
  4359. }
  4360. });
  4361. $(window).resize(function () {
  4362. resize();
  4363. });
  4364. module.exports = Prezi;
  4365. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4366. (function() {
  4367. "use strict";
  4368. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4369. window.PreziPlayer = (function() {
  4370. PreziPlayer.API_VERSION = 1;
  4371. PreziPlayer.CURRENT_STEP = 'currentStep';
  4372. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4373. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4374. PreziPlayer.STATUS_LOADING = 'loading';
  4375. PreziPlayer.STATUS_READY = 'ready';
  4376. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4377. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4378. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4379. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4380. PreziPlayer.EVENT_STATUS = "statusChange";
  4381. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4382. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4383. PreziPlayer.domain = "https://prezi.com";
  4384. PreziPlayer.path = "/player/";
  4385. PreziPlayer.players = {};
  4386. PreziPlayer.binded_methods = ['changesHandler'];
  4387. PreziPlayer.createMultiplePlayers = function(optionArray){
  4388. for(var i=0; i<optionArray.length; i++) {
  4389. var optionSet = optionArray[i];
  4390. new PreziPlayer(optionSet.id, optionSet);
  4391. };
  4392. };
  4393. PreziPlayer.messageReceived = function(event){
  4394. var message, item, player;
  4395. try {
  4396. message = JSON.parse(event.data);
  4397. if (message.id && (player = PreziPlayer.players[message.id])) {
  4398. if (player.options.debug === true) {
  4399. if (console && console.log)
  4400. console.log('received', message);
  4401. }
  4402. if (message.type === "changes") {
  4403. player.changesHandler(message);
  4404. }
  4405. for (var i = 0; i < player.callbacks.length; i++) {
  4406. item = player.callbacks[i];
  4407. if (item && message.type === item.event) {
  4408. item.callback(message);
  4409. }
  4410. }
  4411. }
  4412. } catch (e) { }
  4413. };
  4414. function PreziPlayer(id, options) {
  4415. var params, paramString = "", _this = this;
  4416. if (PreziPlayer.players[id]){
  4417. PreziPlayer.players[id].destroy();
  4418. }
  4419. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4420. var method_name = PreziPlayer.binded_methods[i];
  4421. _this[method_name] = __bind(_this[method_name], _this);
  4422. };
  4423. options = options || {};
  4424. this.options = options;
  4425. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4426. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4427. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4428. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4429. this.callbacks = [];
  4430. this.id = id;
  4431. this.embedTo = document.getElementById(id);
  4432. if (!this.embedTo) {
  4433. throw "The element id is not available.";
  4434. }
  4435. this.iframe = document.createElement('iframe');
  4436. params = [
  4437. { name: 'oid', value: options.preziId },
  4438. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4439. { name: 'controls', value: options.controls ? 1 : 0 }
  4440. ];
  4441. for(var i=0; i<params.length; i++) {
  4442. var param = params[i];
  4443. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4444. };
  4445. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4446. this.iframe.frameBorder = 0;
  4447. this.iframe.scrolling = "no";
  4448. this.iframe.width = options.width || 640;
  4449. this.iframe.height = options.height || 480;
  4450. this.embedTo.innerHTML = '';
  4451. // JITSI: IN CASE SOMETHING GOES WRONG.
  4452. try {
  4453. this.embedTo.appendChild(this.iframe);
  4454. }
  4455. catch (err) {
  4456. console.log("CATCH ERROR");
  4457. }
  4458. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4459. // crashes for us.
  4460. this.initPollInterval = setInterval(function(){
  4461. _this.sendMessage({'action': 'init'});
  4462. }, 500);
  4463. PreziPlayer.players[id] = this;
  4464. }
  4465. PreziPlayer.prototype.changesHandler = function(message) {
  4466. var key, value, j, item;
  4467. if (this.initPollInterval) {
  4468. clearInterval(this.initPollInterval);
  4469. this.initPollInterval = false;
  4470. }
  4471. for (key in message.data) {
  4472. if (message.data.hasOwnProperty(key)){
  4473. value = message.data[key];
  4474. this.values[key] = value;
  4475. for (j=0; j<this.callbacks.length; j++) {
  4476. item = this.callbacks[j];
  4477. if (item && item.event === key + "Change"){
  4478. item.callback({type: item.event, value: value});
  4479. }
  4480. }
  4481. }
  4482. }
  4483. };
  4484. PreziPlayer.prototype.destroy = function() {
  4485. if (this.initPollInterval) {
  4486. clearInterval(this.initPollInterval);
  4487. this.initPollInterval = false;
  4488. }
  4489. this.embedTo.innerHTML = '';
  4490. };
  4491. PreziPlayer.prototype.sendMessage = function(message) {
  4492. if (this.options.debug === true) {
  4493. if (console && console.log) console.log('sent', message);
  4494. }
  4495. message.version = PreziPlayer.API_VERSION;
  4496. message.id = this.id;
  4497. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4498. };
  4499. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4500. PreziPlayer.prototype.flyToNextStep = function() {
  4501. return this.sendMessage({
  4502. 'action': 'present',
  4503. 'data': ['moveToNextStep']
  4504. });
  4505. };
  4506. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4507. PreziPlayer.prototype.flyToPreviousStep = function() {
  4508. return this.sendMessage({
  4509. 'action': 'present',
  4510. 'data': ['moveToPrevStep']
  4511. });
  4512. };
  4513. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4514. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4515. var obj = this;
  4516. // check animation_step
  4517. if (animation_step > 0 &&
  4518. obj.values.animationCountOnSteps &&
  4519. obj.values.animationCountOnSteps[step] <= animation_step) {
  4520. animation_step = obj.values.animationCountOnSteps[step];
  4521. }
  4522. // jump to animation steps by calling flyToNextStep()
  4523. function doAnimationSteps() {
  4524. if (obj.values.isMoving == true) {
  4525. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4526. return;
  4527. }
  4528. while (animation_step-- > 0) {
  4529. obj.flyToNextStep(); // do the animation steps
  4530. }
  4531. }
  4532. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4533. // jump to the step
  4534. return this.sendMessage({
  4535. 'action': 'present',
  4536. 'data': ['moveToStep', step]
  4537. });
  4538. };
  4539. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4540. PreziPlayer.prototype.flyToObject = function(objectId) {
  4541. return this.sendMessage({
  4542. 'action': 'present',
  4543. 'data': ['moveToObject', objectId]
  4544. });
  4545. };
  4546. PreziPlayer.prototype.play = function(defaultDelay) {
  4547. return this.sendMessage({
  4548. 'action': 'present',
  4549. 'data': ['startAutoPlay', defaultDelay]
  4550. });
  4551. };
  4552. PreziPlayer.prototype.stop = function() {
  4553. return this.sendMessage({
  4554. 'action': 'present',
  4555. 'data': ['stopAutoPlay']
  4556. });
  4557. };
  4558. PreziPlayer.prototype.pause = function(defaultDelay) {
  4559. return this.sendMessage({
  4560. 'action': 'present',
  4561. 'data': ['pauseAutoPlay', defaultDelay]
  4562. });
  4563. };
  4564. PreziPlayer.prototype.getCurrentStep = function() {
  4565. return this.values.currentStep;
  4566. };
  4567. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4568. return this.values.currentAnimationStep;
  4569. };
  4570. PreziPlayer.prototype.getCurrentObject = function() {
  4571. return this.values.currentObject;
  4572. };
  4573. PreziPlayer.prototype.getStatus = function() {
  4574. return this.values.status;
  4575. };
  4576. PreziPlayer.prototype.isPlaying = function() {
  4577. return this.values.isAutoPlaying;
  4578. };
  4579. PreziPlayer.prototype.getStepCount = function() {
  4580. return this.values.stepCount;
  4581. };
  4582. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4583. return this.values.animationCountOnSteps;
  4584. };
  4585. PreziPlayer.prototype.getTitle = function() {
  4586. return this.values.title;
  4587. };
  4588. PreziPlayer.prototype.setDimensions = function(dims) {
  4589. for (var parameter in dims) {
  4590. this.iframe[parameter] = dims[parameter];
  4591. }
  4592. }
  4593. PreziPlayer.prototype.getDimensions = function() {
  4594. return {
  4595. width: parseInt(this.iframe.width, 10),
  4596. height: parseInt(this.iframe.height, 10)
  4597. }
  4598. }
  4599. PreziPlayer.prototype.on = function(event, callback) {
  4600. this.callbacks.push({
  4601. event: event,
  4602. callback: callback
  4603. });
  4604. };
  4605. PreziPlayer.prototype.off = function(event, callback) {
  4606. var j, item;
  4607. if (event === undefined) {
  4608. this.callbacks = [];
  4609. }
  4610. j = this.callbacks.length;
  4611. while (j--) {
  4612. item = this.callbacks[j];
  4613. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4614. this.callbacks.splice(j, 1);
  4615. }
  4616. }
  4617. };
  4618. if (window.addEventListener) {
  4619. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4620. } else {
  4621. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4622. }
  4623. return PreziPlayer;
  4624. })();
  4625. })();
  4626. module.exports = PreziPlayer;
  4627. },{}],20:[function(require,module,exports){
  4628. /* global require, $ */
  4629. var Chat = require("./chat/Chat");
  4630. var ContactList = require("./contactlist/ContactList");
  4631. var Settings = require("./../../settings/Settings");
  4632. var SettingsMenu = require("./settings/SettingsMenu");
  4633. var VideoLayout = require("../videolayout/VideoLayout");
  4634. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4635. var UIUtil = require("../util/UIUtil");
  4636. var LargeVideo = require("../videolayout/LargeVideo");
  4637. /**
  4638. * Toggler for the chat, contact list, settings menu, etc..
  4639. */
  4640. var PanelToggler = (function(my) {
  4641. var currentlyOpen = null;
  4642. var buttons = {
  4643. '#chatspace': '#chatBottomButton',
  4644. '#contactlist': '#contactListButton',
  4645. '#settingsmenu': '#toolbar_button_settings'
  4646. };
  4647. /**
  4648. * Toggles the windows in the side panel
  4649. * @param object the window that should be shown
  4650. * @param selector the selector for the element containing the panel
  4651. * @param onOpenComplete function to be called when the panel is opened
  4652. * @param onOpen function to be called if the window is going to be opened
  4653. * @param onClose function to be called if the window is going to be closed
  4654. */
  4655. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4656. UIUtil.buttonClick(buttons[selector], "active");
  4657. if (object.isVisible()) {
  4658. $("#toast-container").animate({
  4659. right: '5px'
  4660. },
  4661. {
  4662. queue: false,
  4663. duration: 500
  4664. });
  4665. $(selector).hide("slide", {
  4666. direction: "right",
  4667. queue: false,
  4668. duration: 500
  4669. });
  4670. if(typeof onClose === "function") {
  4671. onClose();
  4672. }
  4673. currentlyOpen = null;
  4674. }
  4675. else {
  4676. // Undock the toolbar when the chat is shown and if we're in a
  4677. // video mode.
  4678. if (LargeVideo.isLargeVideoVisible()) {
  4679. ToolbarToggler.dockToolbar(false);
  4680. }
  4681. if(currentlyOpen) {
  4682. var current = $(currentlyOpen);
  4683. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4684. current.css('z-index', 4);
  4685. setTimeout(function () {
  4686. current.css('display', 'none');
  4687. current.css('z-index', 5);
  4688. }, 500);
  4689. }
  4690. $("#toast-container").animate({
  4691. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4692. },
  4693. {
  4694. queue: false,
  4695. duration: 500
  4696. });
  4697. $(selector).show("slide", {
  4698. direction: "right",
  4699. queue: false,
  4700. duration: 500,
  4701. complete: onOpenComplete
  4702. });
  4703. if(typeof onOpen === "function") {
  4704. onOpen();
  4705. }
  4706. currentlyOpen = selector;
  4707. }
  4708. };
  4709. /**
  4710. * Opens / closes the chat area.
  4711. */
  4712. my.toggleChat = function() {
  4713. var chatCompleteFunction = Chat.isVisible() ?
  4714. function() {} : function () {
  4715. Chat.scrollChatToBottom();
  4716. $('#chatspace').trigger('shown');
  4717. };
  4718. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4719. toggle(Chat,
  4720. '#chatspace',
  4721. function () {
  4722. // Request the focus in the nickname field or the chat input field.
  4723. if ($('#nickname').css('visibility') === 'visible') {
  4724. $('#nickinput').focus();
  4725. } else {
  4726. $('#usermsg').focus();
  4727. }
  4728. },
  4729. null,
  4730. Chat.resizeChat,
  4731. null);
  4732. };
  4733. /**
  4734. * Opens / closes the contact list area.
  4735. */
  4736. my.toggleContactList = function () {
  4737. var completeFunction = ContactList.isVisible() ?
  4738. function() {} : function () { $('#contactlist').trigger('shown');};
  4739. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  4740. toggle(ContactList,
  4741. '#contactlist',
  4742. null,
  4743. function() {
  4744. ContactList.setVisualNotification(false);
  4745. },
  4746. null);
  4747. };
  4748. /**
  4749. * Opens / closes the settings menu
  4750. */
  4751. my.toggleSettingsMenu = function() {
  4752. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  4753. toggle(SettingsMenu,
  4754. '#settingsmenu',
  4755. null,
  4756. function() {
  4757. var settings = Settings.getSettings();
  4758. $('#setDisplayName').get(0).value = settings.displayName;
  4759. $('#setEmail').get(0).value = settings.email;
  4760. },
  4761. null);
  4762. };
  4763. /**
  4764. * Returns the size of the side panel.
  4765. */
  4766. my.getPanelSize = function () {
  4767. var availableHeight = window.innerHeight;
  4768. var availableWidth = window.innerWidth;
  4769. var panelWidth = 200;
  4770. if (availableWidth * 0.2 < 200) {
  4771. panelWidth = availableWidth * 0.2;
  4772. }
  4773. return [panelWidth, availableHeight];
  4774. };
  4775. my.isVisible = function() {
  4776. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  4777. };
  4778. return my;
  4779. }(PanelToggler || {}));
  4780. module.exports = PanelToggler;
  4781. },{"../toolbars/ToolbarToggler":29,"../util/UIUtil":33,"../videolayout/LargeVideo":35,"../videolayout/VideoLayout":39,"./../../settings/Settings":47,"./chat/Chat":21,"./contactlist/ContactList":25,"./settings/SettingsMenu":26}],21:[function(require,module,exports){
  4782. /* global APP, $, Util, nickname:true */
  4783. var Replacement = require("./Replacement");
  4784. var CommandsProcessor = require("./Commands");
  4785. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  4786. var smileys = require("./smileys.json").smileys;
  4787. var NicknameHandler = require("../../util/NicknameHandler");
  4788. var UIUtil = require("../../util/UIUtil");
  4789. var UIEvents = require("../../../../service/UI/UIEvents");
  4790. var notificationInterval = false;
  4791. var unreadMessages = 0;
  4792. /**
  4793. * Shows/hides a visual notification, indicating that a message has arrived.
  4794. */
  4795. function setVisualNotification(show) {
  4796. var unreadMsgElement = document.getElementById('unreadMessages');
  4797. var unreadMsgBottomElement
  4798. = document.getElementById('bottomUnreadMessages');
  4799. var glower = $('#toolbar_button_chat');
  4800. var bottomGlower = $('#chatBottomButton');
  4801. if (unreadMessages) {
  4802. unreadMsgElement.innerHTML = unreadMessages.toString();
  4803. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  4804. ToolbarToggler.dockToolbar(true);
  4805. var chatButtonElement
  4806. = document.getElementById('toolbar_button_chat');
  4807. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  4808. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  4809. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  4810. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  4811. unreadMsgElement.setAttribute(
  4812. 'style',
  4813. 'top:' + topIndent +
  4814. '; left:' + leftIndent + ';');
  4815. var chatBottomButtonElement
  4816. = document.getElementById('chatBottomButton').parentNode;
  4817. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  4818. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  4819. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  4820. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  4821. unreadMsgBottomElement.setAttribute(
  4822. 'style',
  4823. 'top:' + bottomTopIndent +
  4824. '; left:' + bottomLeftIndent + ';');
  4825. if (!glower.hasClass('icon-chat-simple')) {
  4826. glower.removeClass('icon-chat');
  4827. glower.addClass('icon-chat-simple');
  4828. }
  4829. }
  4830. else {
  4831. unreadMsgElement.innerHTML = '';
  4832. unreadMsgBottomElement.innerHTML = '';
  4833. glower.removeClass('icon-chat-simple');
  4834. glower.addClass('icon-chat');
  4835. }
  4836. if (show && !notificationInterval) {
  4837. notificationInterval = window.setInterval(function () {
  4838. glower.toggleClass('active');
  4839. bottomGlower.toggleClass('active glowing');
  4840. }, 800);
  4841. }
  4842. else if (!show && notificationInterval) {
  4843. window.clearInterval(notificationInterval);
  4844. notificationInterval = false;
  4845. glower.removeClass('active');
  4846. bottomGlower.removeClass('glowing');
  4847. bottomGlower.addClass('active');
  4848. }
  4849. }
  4850. /**
  4851. * Returns the current time in the format it is shown to the user
  4852. * @returns {string}
  4853. */
  4854. function getCurrentTime(stamp) {
  4855. var now = (stamp? new Date(stamp): new Date());
  4856. var hour = now.getHours();
  4857. var minute = now.getMinutes();
  4858. var second = now.getSeconds();
  4859. if(hour.toString().length === 1) {
  4860. hour = '0'+hour;
  4861. }
  4862. if(minute.toString().length === 1) {
  4863. minute = '0'+minute;
  4864. }
  4865. if(second.toString().length === 1) {
  4866. second = '0'+second;
  4867. }
  4868. return hour+':'+minute+':'+second;
  4869. }
  4870. function toggleSmileys() {
  4871. var smileys = $('#smileysContainer');
  4872. if(!smileys.is(':visible')) {
  4873. smileys.show("slide", { direction: "down", duration: 300});
  4874. } else {
  4875. smileys.hide("slide", { direction: "down", duration: 300});
  4876. }
  4877. $('#usermsg').focus();
  4878. }
  4879. function addClickFunction(smiley, number) {
  4880. smiley.onclick = function addSmileyToMessage() {
  4881. var usermsg = $('#usermsg');
  4882. var message = usermsg.val();
  4883. message += smileys['smiley' + number];
  4884. usermsg.val(message);
  4885. usermsg.get(0).setSelectionRange(message.length, message.length);
  4886. toggleSmileys();
  4887. usermsg.focus();
  4888. };
  4889. }
  4890. /**
  4891. * Adds the smileys container to the chat
  4892. */
  4893. function addSmileys() {
  4894. var smileysContainer = document.createElement('div');
  4895. smileysContainer.id = 'smileysContainer';
  4896. for(var i = 1; i <= 21; i++) {
  4897. var smileyContainer = document.createElement('div');
  4898. smileyContainer.id = 'smiley' + i;
  4899. smileyContainer.className = 'smileyContainer';
  4900. var smiley = document.createElement('img');
  4901. smiley.src = 'images/smileys/smiley' + i + '.svg';
  4902. smiley.className = 'smiley';
  4903. addClickFunction(smiley, i);
  4904. smileyContainer.appendChild(smiley);
  4905. smileysContainer.appendChild(smileyContainer);
  4906. }
  4907. $("#chatspace").append(smileysContainer);
  4908. }
  4909. /**
  4910. * Resizes the chat conversation.
  4911. */
  4912. function resizeChatConversation() {
  4913. var msgareaHeight = $('#usermsg').outerHeight();
  4914. var chatspace = $('#chatspace');
  4915. var width = chatspace.width();
  4916. var chat = $('#chatconversation');
  4917. var smileys = $('#smileysarea');
  4918. smileys.height(msgareaHeight);
  4919. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  4920. $('#smileysContainer').css('bottom', msgareaHeight);
  4921. chat.width(width - 10);
  4922. chat.height(window.innerHeight - 15 - msgareaHeight);
  4923. }
  4924. /**
  4925. * Chat related user interface.
  4926. */
  4927. var Chat = (function (my) {
  4928. /**
  4929. * Initializes chat related interface.
  4930. */
  4931. my.init = function () {
  4932. if(NicknameHandler.getNickname())
  4933. Chat.setChatConversationMode(true);
  4934. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  4935. function (nickname) {
  4936. Chat.setChatConversationMode(true);
  4937. });
  4938. $('#nickinput').keydown(function (event) {
  4939. if (event.keyCode === 13) {
  4940. event.preventDefault();
  4941. var val = UIUtil.escapeHtml(this.value);
  4942. this.value = '';
  4943. if (!NicknameHandler.getNickname()) {
  4944. NicknameHandler.setNickname(val);
  4945. return;
  4946. }
  4947. }
  4948. });
  4949. var usermsg = $('#usermsg');
  4950. usermsg.keydown(function (event) {
  4951. if (event.keyCode === 13) {
  4952. event.preventDefault();
  4953. var value = this.value;
  4954. usermsg.val('').trigger('autosize.resize');
  4955. this.focus();
  4956. var command = new CommandsProcessor(value);
  4957. if(command.isCommand()) {
  4958. command.processCommand();
  4959. }
  4960. else {
  4961. var message = UIUtil.escapeHtml(value);
  4962. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  4963. }
  4964. }
  4965. });
  4966. var onTextAreaResize = function () {
  4967. resizeChatConversation();
  4968. Chat.scrollChatToBottom();
  4969. };
  4970. usermsg.autosize({callback: onTextAreaResize});
  4971. $("#chatspace").bind("shown",
  4972. function () {
  4973. unreadMessages = 0;
  4974. setVisualNotification(false);
  4975. });
  4976. addSmileys();
  4977. };
  4978. /**
  4979. * Appends the given message to the chat conversation.
  4980. */
  4981. my.updateChatConversation =
  4982. function (from, displayName, message, myjid, stamp) {
  4983. var divClassName = '';
  4984. if (APP.xmpp.myJid() === from) {
  4985. divClassName = "localuser";
  4986. }
  4987. else {
  4988. divClassName = "remoteuser";
  4989. if (!Chat.isVisible()) {
  4990. unreadMessages++;
  4991. UIUtil.playSoundNotification('chatNotification');
  4992. setVisualNotification(true);
  4993. }
  4994. }
  4995. // replace links and smileys
  4996. // Strophe already escapes special symbols on sending,
  4997. // so we escape here only tags to avoid double &amp;
  4998. var escMessage = message.replace(/</g, '&lt;').
  4999. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5000. var escDisplayName = UIUtil.escapeHtml(displayName);
  5001. message = Replacement.processReplacements(escMessage);
  5002. var messageContainer =
  5003. '<div class="chatmessage">'+
  5004. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5005. '<div class="username ' + divClassName +'">' + escDisplayName +
  5006. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5007. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5008. '</div>';
  5009. $('#chatconversation').append(messageContainer);
  5010. $('#chatconversation').animate(
  5011. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5012. };
  5013. /**
  5014. * Appends error message to the conversation
  5015. * @param errorMessage the received error message.
  5016. * @param originalText the original message.
  5017. */
  5018. my.chatAddError = function(errorMessage, originalText) {
  5019. errorMessage = UIUtil.escapeHtml(errorMessage);
  5020. originalText = UIUtil.escapeHtml(originalText);
  5021. $('#chatconversation').append(
  5022. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5023. (originalText? (' \"'+ originalText + '\"') : "") +
  5024. ' was not sent.' +
  5025. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5026. $('#chatconversation').animate(
  5027. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5028. };
  5029. /**
  5030. * Sets the subject to the UI
  5031. * @param subject the subject
  5032. */
  5033. my.chatSetSubject = function(subject) {
  5034. if (subject)
  5035. subject = subject.trim();
  5036. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5037. if(subject === "") {
  5038. $("#subject").css({display: "none"});
  5039. }
  5040. else {
  5041. $("#subject").css({display: "block"});
  5042. }
  5043. };
  5044. /**
  5045. * Sets the chat conversation mode.
  5046. */
  5047. my.setChatConversationMode = function (isConversationMode) {
  5048. if (isConversationMode) {
  5049. $('#nickname').css({visibility: 'hidden'});
  5050. $('#chatconversation').css({visibility: 'visible'});
  5051. $('#usermsg').css({visibility: 'visible'});
  5052. $('#smileysarea').css({visibility: 'visible'});
  5053. $('#usermsg').focus();
  5054. }
  5055. };
  5056. /**
  5057. * Resizes the chat area.
  5058. */
  5059. my.resizeChat = function () {
  5060. var chatSize = require("../SidePanelToggler").getPanelSize();
  5061. $('#chatspace').width(chatSize[0]);
  5062. $('#chatspace').height(chatSize[1]);
  5063. resizeChatConversation();
  5064. };
  5065. /**
  5066. * Indicates if the chat is currently visible.
  5067. */
  5068. my.isVisible = function () {
  5069. return $('#chatspace').is(":visible");
  5070. };
  5071. /**
  5072. * Shows and hides the window with the smileys
  5073. */
  5074. my.toggleSmileys = toggleSmileys;
  5075. /**
  5076. * Scrolls chat to the bottom.
  5077. */
  5078. my.scrollChatToBottom = function() {
  5079. setTimeout(function () {
  5080. $('#chatconversation').scrollTop(
  5081. $('#chatconversation')[0].scrollHeight);
  5082. }, 5);
  5083. };
  5084. return my;
  5085. }(Chat || {}));
  5086. module.exports = Chat;
  5087. },{"../../../../service/UI/UIEvents":163,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5088. /* global APP, require */
  5089. var UIUtil = require("../../util/UIUtil");
  5090. /**
  5091. * List with supported commands. The keys are the names of the commands and
  5092. * the value is the function that processes the message.
  5093. * @type {{String: function}}
  5094. */
  5095. var commands = {
  5096. "topic" : processTopic
  5097. };
  5098. /**
  5099. * Extracts the command from the message.
  5100. * @param message the received message
  5101. * @returns {string} the command
  5102. */
  5103. function getCommand(message) {
  5104. if(message) {
  5105. for(var command in commands) {
  5106. if(message.indexOf("/" + command) == 0)
  5107. return command;
  5108. }
  5109. }
  5110. return "";
  5111. }
  5112. /**
  5113. * Processes the data for topic command.
  5114. * @param commandArguments the arguments of the topic command.
  5115. */
  5116. function processTopic(commandArguments) {
  5117. var topic = UIUtil.escapeHtml(commandArguments);
  5118. APP.xmpp.setSubject(topic);
  5119. }
  5120. /**
  5121. * Constructs a new CommandProccessor instance from a message that
  5122. * handles commands received via chat messages.
  5123. * @param message the message
  5124. * @constructor
  5125. */
  5126. function CommandsProcessor(message) {
  5127. var command = getCommand(message);
  5128. /**
  5129. * Returns the name of the command.
  5130. * @returns {String} the command
  5131. */
  5132. this.getCommand = function() {
  5133. return command;
  5134. };
  5135. var messageArgument = message.substr(command.length + 2);
  5136. /**
  5137. * Returns the arguments of the command.
  5138. * @returns {string}
  5139. */
  5140. this.getArgument = function() {
  5141. return messageArgument;
  5142. };
  5143. }
  5144. /**
  5145. * Checks whether this instance is valid command or not.
  5146. * @returns {boolean}
  5147. */
  5148. CommandsProcessor.prototype.isCommand = function() {
  5149. if (this.getCommand())
  5150. return true;
  5151. return false;
  5152. };
  5153. /**
  5154. * Processes the command.
  5155. */
  5156. CommandsProcessor.prototype.processCommand = function() {
  5157. if(!this.isCommand())
  5158. return;
  5159. commands[this.getCommand()](this.getArgument());
  5160. };
  5161. module.exports = CommandsProcessor;
  5162. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5163. var Smileys = require("./smileys.json");
  5164. /**
  5165. * Processes links and smileys in "body"
  5166. */
  5167. function processReplacements(body)
  5168. {
  5169. //make links clickable
  5170. body = linkify(body);
  5171. //add smileys
  5172. body = smilify(body);
  5173. return body;
  5174. }
  5175. /**
  5176. * Finds and replaces all links in the links in "body"
  5177. * with their <a href=""></a>
  5178. */
  5179. function linkify(inputText)
  5180. {
  5181. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5182. //URLs starting with http://, https://, or ftp://
  5183. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5184. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5185. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5186. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5187. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5188. //Change email addresses to mailto:: links.
  5189. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5190. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5191. return replacedText;
  5192. }
  5193. /**
  5194. * Replaces common smiley strings with images
  5195. */
  5196. function smilify(body)
  5197. {
  5198. if(!body) {
  5199. return body;
  5200. }
  5201. var regexs = Smileys["regexs"];
  5202. for(var smiley in regexs) {
  5203. if(regexs.hasOwnProperty(smiley)) {
  5204. body = body.replace(regexs[smiley],
  5205. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5206. }
  5207. }
  5208. return body;
  5209. }
  5210. module.exports = {
  5211. processReplacements: processReplacements,
  5212. linkify: linkify
  5213. };
  5214. },{"./smileys.json":24}],24:[function(require,module,exports){
  5215. module.exports={
  5216. "smileys": {
  5217. "smiley1": ":)",
  5218. "smiley2": ":(",
  5219. "smiley3": ":D",
  5220. "smiley4": "(y)",
  5221. "smiley5": " :P",
  5222. "smiley6": "(wave)",
  5223. "smiley7": "(blush)",
  5224. "smiley8": "(chuckle)",
  5225. "smiley9": "(shocked)",
  5226. "smiley10": ":*",
  5227. "smiley11": "(n)",
  5228. "smiley12": "(search)",
  5229. "smiley13": " <3",
  5230. "smiley14": "(oops)",
  5231. "smiley15": "(angry)",
  5232. "smiley16": "(angel)",
  5233. "smiley17": "(sick)",
  5234. "smiley18": ";(",
  5235. "smiley19": "(bomb)",
  5236. "smiley20": "(clap)",
  5237. "smiley21": " ;)"
  5238. },
  5239. "regexs": {
  5240. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5241. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5242. "smiley1": /(:-\)|:\))/gi,
  5243. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5244. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5245. "smiley6": /(\(wave\))/gi,
  5246. "smiley7": /(\(blush\))/gi,
  5247. "smiley8": /(\(chuckle\))/gi,
  5248. "smiley9": /(:-0|\(shocked\))/gi,
  5249. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5250. "smiley11": /(\(n\))/gi,
  5251. "smiley12": /(\(search\))/g,
  5252. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5253. "smiley14": /(\(oops\))/gi,
  5254. "smiley15": /(\(angry\))/gi,
  5255. "smiley16": /(\(angel\))/gi,
  5256. "smiley17": /(\(sick\))/gi,
  5257. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5258. "smiley19": /(\(bomb\))/gi,
  5259. "smiley20": /(\(clap\))/gi,
  5260. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5261. }
  5262. }
  5263. },{}],25:[function(require,module,exports){
  5264. /* global $, APP, Strophe */
  5265. var Avatar = require('../../avatar/Avatar');
  5266. var numberOfContacts = 0;
  5267. var notificationInterval;
  5268. /**
  5269. * Updates the number of participants in the contact list button and sets
  5270. * the glow
  5271. * @param delta indicates whether a new user has joined (1) or someone has
  5272. * left(-1)
  5273. */
  5274. function updateNumberOfParticipants(delta) {
  5275. numberOfContacts += delta;
  5276. if (numberOfContacts === 1) {
  5277. // when the user is alone we don't show the number of participants
  5278. $("#numberOfParticipants").text('');
  5279. ContactList.setVisualNotification(false);
  5280. } else if (numberOfContacts > 1) {
  5281. ContactList.setVisualNotification(!ContactList.isVisible());
  5282. $("#numberOfParticipants").text(numberOfContacts);
  5283. } else {
  5284. console.error("Invalid number of participants: " + numberOfContacts);
  5285. }
  5286. }
  5287. /**
  5288. * Creates the avatar element.
  5289. *
  5290. * @return {object} the newly created avatar element
  5291. */
  5292. function createAvatar(jid) {
  5293. var avatar = document.createElement('img');
  5294. avatar.className = "icon-avatar avatar";
  5295. avatar.src = Avatar.getContactListUrl(jid);
  5296. return avatar;
  5297. }
  5298. /**
  5299. * Creates the display name paragraph.
  5300. *
  5301. * @param displayName the display name to set
  5302. */
  5303. function createDisplayNameParagraph(key, displayName) {
  5304. var p = document.createElement('p');
  5305. if(displayName)
  5306. p.innerText = displayName;
  5307. else if(key) {
  5308. p.setAttribute("data-i18n",key);
  5309. p.innerText = APP.translation.translateString(key);
  5310. }
  5311. return p;
  5312. }
  5313. function stopGlowing(glower) {
  5314. window.clearInterval(notificationInterval);
  5315. notificationInterval = false;
  5316. glower.removeClass('glowing');
  5317. if (!ContactList.isVisible()) {
  5318. glower.removeClass('active');
  5319. }
  5320. }
  5321. /**
  5322. * Contact list.
  5323. */
  5324. var ContactList = {
  5325. /**
  5326. * Indicates if the chat is currently visible.
  5327. *
  5328. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5329. * otherwise
  5330. */
  5331. isVisible: function () {
  5332. return $('#contactlist').is(":visible");
  5333. },
  5334. /**
  5335. * Adds a contact for the given peerJid if such doesn't yet exist.
  5336. *
  5337. * @param peerJid the peerJid corresponding to the contact
  5338. */
  5339. ensureAddContact: function (peerJid) {
  5340. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5341. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5342. if (!contact || contact.length <= 0)
  5343. ContactList.addContact(peerJid);
  5344. },
  5345. /**
  5346. * Adds a contact for the given peer jid.
  5347. *
  5348. * @param peerJid the jid of the contact to add
  5349. */
  5350. addContact: function (peerJid) {
  5351. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5352. var contactlist = $('#contacts');
  5353. var newContact = document.createElement('li');
  5354. newContact.id = resourceJid;
  5355. newContact.className = "clickable";
  5356. newContact.onclick = function (event) {
  5357. if (event.currentTarget.className === "clickable") {
  5358. $(ContactList).trigger('contactclicked', [peerJid]);
  5359. }
  5360. };
  5361. newContact.appendChild(createAvatar(peerJid));
  5362. newContact.appendChild(createDisplayNameParagraph("participant"));
  5363. if (resourceJid === APP.xmpp.myResource()) {
  5364. contactlist.prepend(newContact);
  5365. }
  5366. else {
  5367. contactlist.append(newContact);
  5368. }
  5369. updateNumberOfParticipants(1);
  5370. },
  5371. /**
  5372. * Removes a contact for the given peer jid.
  5373. *
  5374. * @param peerJid the peerJid corresponding to the contact to remove
  5375. */
  5376. removeContact: function (peerJid) {
  5377. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5378. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5379. if (contact && contact.length > 0) {
  5380. var contactlist = $('#contactlist>ul');
  5381. contactlist.get(0).removeChild(contact.get(0));
  5382. updateNumberOfParticipants(-1);
  5383. }
  5384. },
  5385. setVisualNotification: function (show, stopGlowingIn) {
  5386. var glower = $('#contactListButton');
  5387. if (show && !notificationInterval) {
  5388. notificationInterval = window.setInterval(function () {
  5389. glower.toggleClass('active glowing');
  5390. }, 800);
  5391. }
  5392. else if (!show && notificationInterval) {
  5393. stopGlowing(glower);
  5394. }
  5395. if (stopGlowingIn) {
  5396. setTimeout(function () {
  5397. stopGlowing(glower);
  5398. }, stopGlowingIn);
  5399. }
  5400. },
  5401. setClickable: function (resourceJid, isClickable) {
  5402. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5403. if (isClickable) {
  5404. contact.addClass('clickable');
  5405. } else {
  5406. contact.removeClass('clickable');
  5407. }
  5408. },
  5409. onDisplayNameChange: function (peerJid, displayName) {
  5410. if (peerJid === 'localVideoContainer')
  5411. peerJid = APP.xmpp.myJid();
  5412. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5413. var contactName = $('#contacts #' + resourceJid + '>p');
  5414. if (contactName && displayName && displayName.length > 0)
  5415. contactName.html(displayName);
  5416. },
  5417. userAvatarChanged: function (resourceJid, contactListUrl) {
  5418. // set the avatar in the contact list
  5419. var contact = $('#' + resourceJid + '>img');
  5420. if (contact && contact.length > 0) {
  5421. contact.get(0).src = contactListUrl;
  5422. }
  5423. }
  5424. };
  5425. module.exports = ContactList;
  5426. },{"../../avatar/Avatar":16}],26:[function(require,module,exports){
  5427. /* global APP, $ */
  5428. var Avatar = require("../../avatar/Avatar");
  5429. var Settings = require("./../../../settings/Settings");
  5430. var UIUtil = require("../../util/UIUtil");
  5431. var languages = require("../../../../service/translation/languages");
  5432. function generateLanguagesSelectBox() {
  5433. var currentLang = APP.translation.getCurrentLanguage();
  5434. var html = "<select id=\"languages_selectbox\">";
  5435. var langArray = languages.getLanguages();
  5436. for(var i = 0; i < langArray.length; i++) {
  5437. var lang = langArray[i];
  5438. html += "<option ";
  5439. if(lang === currentLang)
  5440. html += "selected ";
  5441. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5442. html += "</option>";
  5443. }
  5444. return html + "</select>";
  5445. }
  5446. var SettingsMenu = {
  5447. init: function () {
  5448. var startMutedSelector = $("#startMutedOptions");
  5449. startMutedSelector.before(generateLanguagesSelectBox());
  5450. APP.translation.translateElement($("#languages_selectbox"));
  5451. $('#settingsmenu>input').keyup(function(event){
  5452. if(event.keyCode === 13) {//enter
  5453. SettingsMenu.update();
  5454. }
  5455. });
  5456. if (APP.xmpp.isModerator()) {
  5457. startMutedSelector.css("display", "block");
  5458. }
  5459. else {
  5460. startMutedSelector.css("display", "none");
  5461. }
  5462. $("#updateSettings").click(function () {
  5463. SettingsMenu.update();
  5464. });
  5465. },
  5466. onRoleChanged: function () {
  5467. if(APP.xmpp.isModerator()) {
  5468. $("#startMutedOptions").css("display", "block");
  5469. }
  5470. else {
  5471. $("#startMutedOptions").css("display", "none");
  5472. }
  5473. },
  5474. setStartMuted: function (audio, video) {
  5475. $("#startAudioMuted").attr("checked", audio);
  5476. $("#startVideoMuted").attr("checked", video);
  5477. },
  5478. update: function() {
  5479. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5480. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5481. if(newDisplayName) {
  5482. var displayName = Settings.setDisplayName(newDisplayName);
  5483. APP.xmpp.addToPresence("displayName", displayName, true);
  5484. }
  5485. var language = $("#languages_selectbox").val();
  5486. APP.translation.setLanguage(language);
  5487. Settings.setLanguage(language);
  5488. APP.xmpp.addToPresence("email", newEmail);
  5489. var email = Settings.setEmail(newEmail);
  5490. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5491. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5492. APP.xmpp.addToPresence("startMuted",
  5493. [startAudioMuted, startVideoMuted]);
  5494. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5495. },
  5496. isVisible: function() {
  5497. return $('#settingsmenu').is(':visible');
  5498. },
  5499. setDisplayName: function(newDisplayName) {
  5500. var displayName = Settings.setDisplayName(newDisplayName);
  5501. $('#setDisplayName').get(0).value = displayName;
  5502. },
  5503. onDisplayNameChange: function(peerJid, newDisplayName) {
  5504. if(peerJid === 'localVideoContainer' ||
  5505. peerJid === APP.xmpp.myJid()) {
  5506. this.setDisplayName(newDisplayName);
  5507. }
  5508. },
  5509. changeAvatar: function (thumbUrl) {
  5510. $('#avatar').get(0).src = thumbUrl;
  5511. }
  5512. };
  5513. module.exports = SettingsMenu;
  5514. },{"../../../../service/translation/languages":168,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  5515. /* global $ */
  5516. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5517. var buttonHandlers = {
  5518. "bottom_toolbar_contact_list": function () {
  5519. BottomToolbar.toggleContactList();
  5520. },
  5521. "bottom_toolbar_film_strip": function () {
  5522. BottomToolbar.toggleFilmStrip();
  5523. },
  5524. "bottom_toolbar_chat": function () {
  5525. BottomToolbar.toggleChat();
  5526. }
  5527. };
  5528. var BottomToolbar = (function (my) {
  5529. my.init = function () {
  5530. for(var k in buttonHandlers)
  5531. $("#" + k).click(buttonHandlers[k]);
  5532. };
  5533. my.toggleChat = function() {
  5534. PanelToggler.toggleChat();
  5535. };
  5536. my.toggleContactList = function() {
  5537. PanelToggler.toggleContactList();
  5538. };
  5539. my.toggleFilmStrip = function() {
  5540. var filmstrip = $("#remoteVideos");
  5541. filmstrip.toggleClass("hidden");
  5542. };
  5543. $(document).bind("remotevideo.resized", function (event, width, height) {
  5544. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5545. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5546. });
  5547. return my;
  5548. }(BottomToolbar || {}));
  5549. module.exports = BottomToolbar;
  5550. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5551. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  5552. Util */
  5553. var messageHandler = require("../util/MessageHandler");
  5554. var BottomToolbar = require("./BottomToolbar");
  5555. var Prezi = require("../prezi/Prezi");
  5556. var Etherpad = require("../etherpad/Etherpad");
  5557. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5558. var Authentication = require("../authentication/Authentication");
  5559. var UIUtil = require("../util/UIUtil");
  5560. var AuthenticationEvents
  5561. = require("../../../service/authentication/AuthenticationEvents");
  5562. var roomUrl = null;
  5563. var sharedKey = '';
  5564. var UI = null;
  5565. var recordingToaster = null;
  5566. var buttonHandlers = {
  5567. "toolbar_button_mute": function () {
  5568. return APP.UI.toggleAudio();
  5569. },
  5570. "toolbar_button_camera": function () {
  5571. return APP.UI.toggleVideo();
  5572. },
  5573. /*"toolbar_button_authentication": function () {
  5574. return Toolbar.authenticateClicked();
  5575. },*/
  5576. "toolbar_button_record": function () {
  5577. return toggleRecording();
  5578. },
  5579. "toolbar_button_security": function () {
  5580. return Toolbar.openLockDialog();
  5581. },
  5582. "toolbar_button_link": function () {
  5583. return Toolbar.openLinkDialog();
  5584. },
  5585. "toolbar_button_chat": function () {
  5586. return BottomToolbar.toggleChat();
  5587. },
  5588. "toolbar_button_prezi": function () {
  5589. return Prezi.openPreziDialog();
  5590. },
  5591. "toolbar_button_etherpad": function () {
  5592. return Etherpad.toggleEtherpad(0);
  5593. },
  5594. "toolbar_button_desktopsharing": function () {
  5595. return APP.desktopsharing.toggleScreenSharing();
  5596. },
  5597. "toolbar_button_fullScreen": function() {
  5598. UIUtil.buttonClick("#toolbar_button_fullScreen", "icon-full-screen icon-exit-full-screen");
  5599. return Toolbar.toggleFullScreen();
  5600. },
  5601. "toolbar_button_sip": function () {
  5602. return callSipButtonClicked();
  5603. },
  5604. "toolbar_button_dialpad": function () {
  5605. return dialpadButtonClicked();
  5606. },
  5607. "toolbar_button_settings": function () {
  5608. PanelToggler.toggleSettingsMenu();
  5609. },
  5610. "toolbar_button_hangup": function () {
  5611. return hangup();
  5612. },
  5613. "toolbar_button_login": function () {
  5614. Toolbar.authenticateClicked();
  5615. },
  5616. "toolbar_button_logout": function () {
  5617. // Ask for confirmation
  5618. messageHandler.openTwoButtonDialog(
  5619. "dialog.logoutTitle",
  5620. null,
  5621. "dialog.logoutQuestion",
  5622. null,
  5623. false,
  5624. "dialog.Yes",
  5625. function (evt, yes) {
  5626. if (yes) {
  5627. APP.xmpp.logout(function (url) {
  5628. if (url) {
  5629. window.location.href = url;
  5630. } else {
  5631. hangup();
  5632. }
  5633. });
  5634. }
  5635. });
  5636. }
  5637. };
  5638. function hangup() {
  5639. APP.xmpp.disposeConference();
  5640. if(config.enableWelcomePage) {
  5641. setTimeout(function() {
  5642. window.localStorage.welcomePageDisabled = false;
  5643. window.location.pathname = "/";
  5644. }, 10000);
  5645. }
  5646. var title = APP.translation.generateTranslationHTML(
  5647. "dialog.sessTerminated");
  5648. var msg = APP.translation.generateTranslationHTML(
  5649. "dialog.hungUp");
  5650. var button = APP.translation.generateTranslationHTML(
  5651. "dialog.joinAgain");
  5652. var buttons = [];
  5653. buttons.push({title: button, value: true});
  5654. UI.messageHandler.openDialog(
  5655. title,
  5656. msg,
  5657. true,
  5658. buttons,
  5659. function(event, value, message, formVals) {
  5660. window.location.reload();
  5661. return false;
  5662. }
  5663. );
  5664. }
  5665. /**
  5666. * Starts or stops the recording for the conference.
  5667. */
  5668. function toggleRecording(predefinedToken) {
  5669. APP.xmpp.toggleRecording(function (callback) {
  5670. if (predefinedToken) {
  5671. callback(UIUtil.escapeHtml(predefinedToken));
  5672. return;
  5673. }
  5674. var msg = APP.translation.generateTranslationHTML(
  5675. "dialog.recordingToken");
  5676. var token = APP.translation.translateString("dialog.token");
  5677. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5678. '<h2>' + msg + '</h2>' +
  5679. '<input name="recordingToken" type="text" ' +
  5680. ' data-i18n="[placeholder]dialog.token" ' +
  5681. 'placeholder="' + token + '" autofocus>',
  5682. false,
  5683. "dialog.Save",
  5684. function (e, v, m, f) {
  5685. if (v) {
  5686. var token = f.recordingToken;
  5687. if (token) {
  5688. callback(UIUtil.escapeHtml(token));
  5689. }
  5690. }
  5691. },
  5692. null,
  5693. function () { },
  5694. ':input:first'
  5695. );
  5696. }, Toolbar.setRecordingButtonState);
  5697. }
  5698. /**
  5699. * Locks / unlocks the room.
  5700. */
  5701. function lockRoom(lock) {
  5702. var currentSharedKey = '';
  5703. if (lock)
  5704. currentSharedKey = sharedKey;
  5705. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5706. // password is required
  5707. if (sharedKey) {
  5708. console.log('set room password');
  5709. Toolbar.lockLockButton();
  5710. }
  5711. else {
  5712. console.log('removed room password');
  5713. Toolbar.unlockLockButton();
  5714. }
  5715. }, function (err) {
  5716. console.warn('setting password failed', err);
  5717. messageHandler.showError("dialog.lockTitle",
  5718. "dialog.lockMessage");
  5719. Toolbar.setSharedKey('');
  5720. }, function () {
  5721. console.warn('room passwords not supported');
  5722. messageHandler.showError("dialog.warning",
  5723. "dialog.passwordNotSupported");
  5724. Toolbar.setSharedKey('');
  5725. });
  5726. }
  5727. /**
  5728. * Invite participants to conference.
  5729. */
  5730. function inviteParticipants() {
  5731. if (roomUrl === null)
  5732. return;
  5733. var sharedKeyText = "";
  5734. if (sharedKey && sharedKey.length > 0) {
  5735. sharedKeyText =
  5736. APP.translation.translateString("email.sharedKey",
  5737. {sharedKey: sharedKey});
  5738. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5739. }
  5740. var supportedBrowsers = "Chromium, Google Chrome " +
  5741. APP.translation.translateString("email.and") + " Opera";
  5742. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5743. var subject = APP.translation.translateString("email.subject",
  5744. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5745. var body = APP.translation.translateString("email.body",
  5746. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5747. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5748. body = body.replace(/\n/g, "%0D%0A");
  5749. if (window.localStorage.displayname) {
  5750. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5751. }
  5752. if (interfaceConfig.INVITATION_POWERED_BY) {
  5753. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5754. }
  5755. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  5756. }
  5757. function dialpadButtonClicked() {
  5758. //TODO show the dialpad box
  5759. }
  5760. function callSipButtonClicked() {
  5761. var defaultNumber
  5762. = config.defaultSipNumber ? config.defaultSipNumber : '';
  5763. var sipMsg = APP.translation.generateTranslationHTML(
  5764. "dialog.sipMsg");
  5765. messageHandler.openTwoButtonDialog(null, null, null,
  5766. '<h2>' + sipMsg + '</h2>' +
  5767. '<input name="sipNumber" type="text"' +
  5768. ' value="' + defaultNumber + '" autofocus>',
  5769. false,
  5770. "dialog.Dial",
  5771. function (e, v, m, f) {
  5772. if (v) {
  5773. var numberInput = f.sipNumber;
  5774. if (numberInput) {
  5775. APP.xmpp.dial(
  5776. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  5777. }
  5778. }
  5779. },
  5780. null, null, ':input:first'
  5781. );
  5782. }
  5783. var Toolbar = (function (my) {
  5784. my.init = function (ui) {
  5785. for(var k in buttonHandlers)
  5786. $("#" + k).click(buttonHandlers[k]);
  5787. UI = ui;
  5788. // Update login info
  5789. APP.xmpp.addListener(
  5790. AuthenticationEvents.IDENTITY_UPDATED,
  5791. function (authenticationEnabled, userIdentity) {
  5792. var loggedIn = false;
  5793. if (userIdentity) {
  5794. loggedIn = true;
  5795. }
  5796. Toolbar.showAuthenticateButton(authenticationEnabled);
  5797. if (authenticationEnabled) {
  5798. Toolbar.setAuthenticatedIdentity(userIdentity);
  5799. Toolbar.showLoginButton(!loggedIn);
  5800. Toolbar.showLogoutButton(loggedIn);
  5801. }
  5802. }
  5803. );
  5804. };
  5805. /**
  5806. * Sets shared key
  5807. * @param sKey the shared key
  5808. */
  5809. my.setSharedKey = function (sKey) {
  5810. sharedKey = sKey;
  5811. };
  5812. my.authenticateClicked = function () {
  5813. Authentication.focusAuthenticationWindow();
  5814. if (!APP.xmpp.isExternalAuthEnabled()) {
  5815. Authentication.xmppAuthenticate();
  5816. return;
  5817. }
  5818. // Get authentication URL
  5819. if (!APP.xmpp.isMUCJoined()) {
  5820. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  5821. // If conference has not been started yet - redirect to login page
  5822. window.location.href = url;
  5823. });
  5824. } else {
  5825. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  5826. // Otherwise - open popup with authentication URL
  5827. var authenticationWindow = Authentication.createAuthenticationWindow(
  5828. function () {
  5829. // On popup closed - retry room allocation
  5830. APP.xmpp.allocateConferenceFocus(
  5831. APP.UI.getRoomName(),
  5832. function () { console.info("AUTH DONE"); }
  5833. );
  5834. }, url);
  5835. if (!authenticationWindow) {
  5836. messageHandler.openMessageDialog(
  5837. null, "dialog.popupError");
  5838. }
  5839. });
  5840. }
  5841. };
  5842. /**
  5843. * Updates the room invite url.
  5844. */
  5845. my.updateRoomUrl = function (newRoomUrl) {
  5846. roomUrl = newRoomUrl;
  5847. // If the invite dialog has been already opened we update the information.
  5848. var inviteLink = document.getElementById('inviteLinkRef');
  5849. if (inviteLink) {
  5850. inviteLink.value = roomUrl;
  5851. inviteLink.select();
  5852. $('#inviteLinkRef').parent()
  5853. .find('button[value=true]').prop('disabled', false);
  5854. }
  5855. };
  5856. /**
  5857. * Disables and enables some of the buttons.
  5858. */
  5859. my.setupButtonsFromConfig = function () {
  5860. if (config.disablePrezi) {
  5861. $("#toolbar_button_prezi").css({display: "none"});
  5862. }
  5863. };
  5864. /**
  5865. * Opens the lock room dialog.
  5866. */
  5867. my.openLockDialog = function () {
  5868. // Only the focus is able to set a shared key.
  5869. if (!APP.xmpp.isModerator()) {
  5870. if (sharedKey) {
  5871. messageHandler.openMessageDialog(null,
  5872. "dialog.passwordError");
  5873. } else {
  5874. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  5875. }
  5876. } else {
  5877. if (sharedKey) {
  5878. messageHandler.openTwoButtonDialog(null, null,
  5879. "dialog.passwordCheck",
  5880. null,
  5881. false,
  5882. "dialog.Remove",
  5883. function (e, v) {
  5884. if (v) {
  5885. Toolbar.setSharedKey('');
  5886. lockRoom(false);
  5887. }
  5888. });
  5889. } else {
  5890. var msg = APP.translation.generateTranslationHTML(
  5891. "dialog.passwordMsg");
  5892. var yourPassword = APP.translation.translateString(
  5893. "dialog.yourPassword");
  5894. messageHandler.openTwoButtonDialog(null, null, null,
  5895. '<h2>' + msg + '</h2>' +
  5896. '<input name="lockKey" type="text"' +
  5897. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  5898. 'placeholder="' + yourPassword + '" autofocus>',
  5899. false,
  5900. "dialog.Save",
  5901. function (e, v, m, f) {
  5902. if (v) {
  5903. var lockKey = f.lockKey;
  5904. if (lockKey) {
  5905. Toolbar.setSharedKey(
  5906. UIUtil.escapeHtml(lockKey));
  5907. lockRoom(true);
  5908. }
  5909. }
  5910. },
  5911. null, null, 'input:first'
  5912. );
  5913. }
  5914. }
  5915. };
  5916. /**
  5917. * Opens the invite link dialog.
  5918. */
  5919. my.openLinkDialog = function () {
  5920. var inviteAttreibutes;
  5921. if (roomUrl === null) {
  5922. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  5923. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  5924. } else {
  5925. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  5926. }
  5927. messageHandler.openTwoButtonDialog("dialog.shareLink",
  5928. null, null,
  5929. '<input id="inviteLinkRef" type="text" ' +
  5930. inviteAttreibutes + ' onclick="this.select();" readonly>',
  5931. false,
  5932. "dialog.Invite",
  5933. function (e, v) {
  5934. if (v) {
  5935. if (roomUrl) {
  5936. inviteParticipants();
  5937. }
  5938. }
  5939. },
  5940. function (event) {
  5941. if (roomUrl) {
  5942. document.getElementById('inviteLinkRef').select();
  5943. } else {
  5944. if (event && event.target)
  5945. $(event.target)
  5946. .find('button[value=true]').prop('disabled', true);
  5947. }
  5948. }
  5949. );
  5950. };
  5951. /**
  5952. * Opens the settings dialog.
  5953. * FIXME: not used ?
  5954. */
  5955. my.openSettingsDialog = function () {
  5956. var settings1 = APP.translation.generateTranslationHTML(
  5957. "dialog.settings1");
  5958. var settings2 = APP.translation.generateTranslationHTML(
  5959. "dialog.settings2");
  5960. var settings3 = APP.translation.generateTranslationHTML(
  5961. "dialog.settings3");
  5962. var yourPassword = APP.translation.translateString(
  5963. "dialog.yourPassword");
  5964. messageHandler.openTwoButtonDialog(null,
  5965. '<h2>' + settings1 + '</h2>' +
  5966. '<input type="checkbox" id="initMuted">' +
  5967. settings2 + '<br/>' +
  5968. '<input type="checkbox" id="requireNicknames">' +
  5969. settings3 +
  5970. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  5971. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  5972. null,
  5973. null,
  5974. false,
  5975. "dialog.Save",
  5976. function () {
  5977. document.getElementById('lockKey').focus();
  5978. },
  5979. function (e, v) {
  5980. if (v) {
  5981. if ($('#initMuted').is(":checked")) {
  5982. // it is checked
  5983. }
  5984. if ($('#requireNicknames').is(":checked")) {
  5985. // it is checked
  5986. }
  5987. /*
  5988. var lockKey = document.getElementById('lockKey');
  5989. if (lockKey.value) {
  5990. setSharedKey(lockKey.value);
  5991. lockRoom(true);
  5992. }
  5993. */
  5994. }
  5995. }
  5996. );
  5997. };
  5998. /**
  5999. * Toggles the application in and out of full screen mode
  6000. * (a.k.a. presentation mode in Chrome).
  6001. */
  6002. my.toggleFullScreen = function () {
  6003. var fsElement = document.documentElement;
  6004. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6005. //Enter Full Screen
  6006. if (fsElement.mozRequestFullScreen) {
  6007. fsElement.mozRequestFullScreen();
  6008. }
  6009. else {
  6010. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6011. }
  6012. } else {
  6013. //Exit Full Screen
  6014. if (document.mozCancelFullScreen) {
  6015. document.mozCancelFullScreen();
  6016. } else {
  6017. document.webkitCancelFullScreen();
  6018. }
  6019. }
  6020. };
  6021. /**
  6022. * Unlocks the lock button state.
  6023. */
  6024. my.unlockLockButton = function () {
  6025. if ($("#toolbar_button_security").hasClass("icon-security-locked"))
  6026. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6027. };
  6028. /**
  6029. * Updates the lock button state to locked.
  6030. */
  6031. my.lockLockButton = function () {
  6032. if ($("#toolbar_button_security").hasClass("icon-security"))
  6033. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6034. };
  6035. /**
  6036. * Shows or hides authentication button
  6037. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6038. */
  6039. my.showAuthenticateButton = function (show) {
  6040. if (show) {
  6041. $('#authentication').css({display: "inline"});
  6042. }
  6043. else {
  6044. $('#authentication').css({display: "none"});
  6045. }
  6046. };
  6047. // Shows or hides the 'recording' button.
  6048. my.showRecordingButton = function (show) {
  6049. if (!config.enableRecording) {
  6050. return;
  6051. }
  6052. if (show) {
  6053. $('#toolbar_button_record').css({display: "inline-block"});
  6054. }
  6055. else {
  6056. $('#toolbar_button_record').css({display: "none"});
  6057. }
  6058. };
  6059. // Sets the state of the recording button
  6060. my.setRecordingButtonState = function (recordingState) {
  6061. var selector = $('#toolbar_button_record');
  6062. if (recordingState === 'on') {
  6063. selector.removeClass("icon-recEnable");
  6064. selector.addClass("icon-recEnable active");
  6065. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6066. var recordOnKey = "recording.on";
  6067. $('#videoConnectionMessage').attr("data-i18n", recordOnKey);
  6068. $('#videoConnectionMessage').text(APP.translation.translateString(recordOnKey));
  6069. setTimeout(function(){
  6070. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6071. $('#videoConnectionMessage').css({display: "none"});
  6072. }, 1500);
  6073. recordingToaster = messageHandler.notify(null, "recording.toaster", null,
  6074. null, null, {timeOut: 0, closeButton: null, tapToDismiss: false});
  6075. } else if (recordingState === 'off') {
  6076. selector.removeClass("icon-recEnable active");
  6077. selector.addClass("icon-recEnable");
  6078. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6079. $('#videoConnectionMessage').css({display: "none"});
  6080. if (recordingToaster)
  6081. messageHandler.remove(recordingToaster);
  6082. } else if (recordingState === 'pending') {
  6083. selector.removeClass("icon-recEnable active");
  6084. selector.addClass("icon-recEnable");
  6085. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6086. var recordPendingKey = "recording.pending";
  6087. $('#videoConnectionMessage').attr("data-i18n", recordPendingKey);
  6088. $('#videoConnectionMessage').text(APP.translation.translateString(recordPendingKey));
  6089. $('#videoConnectionMessage').css({display: "block"});
  6090. }
  6091. };
  6092. // checks whether recording is enabled and whether we have params to start automatically recording
  6093. my.checkAutoRecord = function () {
  6094. if (config.enableRecording && config.autoRecord) {
  6095. toggleRecording(config.autoRecordToken);
  6096. }
  6097. }
  6098. // Shows or hides SIP calls button
  6099. my.showSipCallButton = function (show) {
  6100. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6101. $('#toolbar_button_sip').css({display: "inline-block"});
  6102. } else {
  6103. $('#toolbar_button_sip').css({display: "none"});
  6104. }
  6105. };
  6106. // Shows or hides the dialpad button
  6107. my.showDialPadButton = function (show) {
  6108. if (show) {
  6109. $('#toolbar_button_dialpad').css({display: "inline-block"});
  6110. } else {
  6111. $('#toolbar_button_dialpad').css({display: "none"});
  6112. }
  6113. };
  6114. /**
  6115. * Displays user authenticated identity name(login).
  6116. * @param authIdentity identity name to be displayed.
  6117. */
  6118. my.setAuthenticatedIdentity = function (authIdentity) {
  6119. if (authIdentity) {
  6120. var selector = $('#toolbar_auth_identity');
  6121. selector.css({display: "list-item"});
  6122. selector.text(authIdentity);
  6123. } else {
  6124. $('#toolbar_auth_identity').css({display: "none"});
  6125. }
  6126. };
  6127. /**
  6128. * Shows/hides login button.
  6129. * @param show <tt>true</tt> to show
  6130. */
  6131. my.showLoginButton = function (show) {
  6132. if (show) {
  6133. $('#toolbar_button_login').css({display: "list-item"});
  6134. } else {
  6135. $('#toolbar_button_login').css({display: "none"});
  6136. }
  6137. };
  6138. /**
  6139. * Shows/hides logout button.
  6140. * @param show <tt>true</tt> to show
  6141. */
  6142. my.showLogoutButton = function (show) {
  6143. if (show) {
  6144. $('#toolbar_button_logout').css({display: "list-item"});
  6145. } else {
  6146. $('#toolbar_button_logout').css({display: "none"});
  6147. }
  6148. };
  6149. /**
  6150. * Sets the state of the button. The button has blue glow if desktop
  6151. * streaming is active.
  6152. * @param active the state of the desktop streaming.
  6153. */
  6154. my.changeDesktopSharingButtonState = function (active) {
  6155. var button = $("#toolbar_button_desktopsharing");
  6156. if (active) {
  6157. button.addClass("glow");
  6158. } else {
  6159. button.removeClass("glow");
  6160. }
  6161. };
  6162. return my;
  6163. }(Toolbar || {}));
  6164. module.exports = Toolbar;
  6165. },{"../../../service/authentication/AuthenticationEvents":164,"../authentication/Authentication":14,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../side_pannels/SidePanelToggler":20,"../util/MessageHandler":31,"../util/UIUtil":33,"./BottomToolbar":27}],29:[function(require,module,exports){
  6166. /* global APP, config, $, interfaceConfig, Moderator,
  6167. DesktopStreaming.showDesktopSharingButton */
  6168. var toolbarTimeoutObject,
  6169. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6170. function showDesktopSharingButton() {
  6171. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6172. $('#toolbar_button_desktopsharing').css({display: "inline-block"});
  6173. } else {
  6174. $('#toolbar_button_desktopsharing').css({display: "none"});
  6175. }
  6176. }
  6177. /**
  6178. * Hides the toolbar.
  6179. */
  6180. function hideToolbar() {
  6181. if(config.alwaysVisibleToolbar)
  6182. return;
  6183. var header = $("#header"),
  6184. bottomToolbar = $("#bottomToolbar");
  6185. var isToolbarHover = false;
  6186. header.find('*').each(function () {
  6187. var id = $(this).attr('id');
  6188. if ($("#" + id + ":hover").length > 0) {
  6189. isToolbarHover = true;
  6190. }
  6191. });
  6192. if ($("#bottomToolbar:hover").length > 0) {
  6193. isToolbarHover = true;
  6194. }
  6195. clearTimeout(toolbarTimeoutObject);
  6196. toolbarTimeoutObject = null;
  6197. if (!isToolbarHover) {
  6198. header.hide("slide", { direction: "up", duration: 300});
  6199. $('#subject').animate({top: "-=40"}, 300);
  6200. if ($("#remoteVideos").hasClass("hidden")) {
  6201. bottomToolbar.hide(
  6202. "slide", {direction: "right", duration: 300});
  6203. }
  6204. }
  6205. else {
  6206. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6207. }
  6208. }
  6209. var ToolbarToggler = {
  6210. /**
  6211. * Shows the main toolbar.
  6212. */
  6213. showToolbar: function () {
  6214. if (interfaceConfig.filmStripOnly)
  6215. return;
  6216. var header = $("#header"),
  6217. bottomToolbar = $("#bottomToolbar");
  6218. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6219. header.show("slide", { direction: "up", duration: 300});
  6220. $('#subject').animate({top: "+=40"}, 300);
  6221. if (!bottomToolbar.is(":visible")) {
  6222. bottomToolbar.show(
  6223. "slide", {direction: "right", duration: 300});
  6224. }
  6225. if (toolbarTimeoutObject) {
  6226. clearTimeout(toolbarTimeoutObject);
  6227. toolbarTimeoutObject = null;
  6228. }
  6229. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6230. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6231. }
  6232. if (APP.xmpp.isModerator())
  6233. {
  6234. // TODO: Enable settings functionality.
  6235. // Need to uncomment the settings button in index.html.
  6236. // $('#settingsButton').css({visibility:"visible"});
  6237. }
  6238. // Show/hide desktop sharing button
  6239. showDesktopSharingButton();
  6240. },
  6241. /**
  6242. * Docks/undocks the toolbar.
  6243. *
  6244. * @param isDock indicates what operation to perform
  6245. */
  6246. dockToolbar: function (isDock) {
  6247. if (interfaceConfig.filmStripOnly)
  6248. return;
  6249. if (isDock) {
  6250. // First make sure the toolbar is shown.
  6251. if (!$('#header').is(':visible')) {
  6252. this.showToolbar();
  6253. }
  6254. // Then clear the time out, to dock the toolbar.
  6255. if (toolbarTimeoutObject) {
  6256. clearTimeout(toolbarTimeoutObject);
  6257. toolbarTimeoutObject = null;
  6258. }
  6259. }
  6260. else {
  6261. if (!$('#header').is(':visible')) {
  6262. this.showToolbar();
  6263. }
  6264. else {
  6265. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6266. }
  6267. }
  6268. },
  6269. showDesktopSharingButton: showDesktopSharingButton
  6270. };
  6271. module.exports = ToolbarToggler;
  6272. },{}],30:[function(require,module,exports){
  6273. /* global $ */
  6274. var JitsiPopover = (function () {
  6275. /**
  6276. * Constructs new JitsiPopover and attaches it to the element
  6277. * @param element jquery selector
  6278. * @param options the options for the popover.
  6279. * @constructor
  6280. */
  6281. function JitsiPopover(element, options)
  6282. {
  6283. this.options = {
  6284. skin: "white",
  6285. content: ""
  6286. };
  6287. if(options)
  6288. {
  6289. if(options.skin)
  6290. this.options.skin = options.skin;
  6291. if(options.content)
  6292. this.options.content = options.content;
  6293. }
  6294. this.elementIsHovered = false;
  6295. this.popoverIsHovered = false;
  6296. this.popoverShown = false;
  6297. element.data("jitsi_popover", this);
  6298. this.element = element;
  6299. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6300. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6301. '<div class="jitsiPopupmenuPadding"></div></div>';
  6302. var self = this;
  6303. this.element.on("mouseenter", function () {
  6304. self.elementIsHovered = true;
  6305. self.show();
  6306. }).on("mouseleave", function () {
  6307. self.elementIsHovered = false;
  6308. setTimeout(function () {
  6309. self.hide();
  6310. }, 10);
  6311. });
  6312. }
  6313. /**
  6314. * Shows the popover
  6315. */
  6316. JitsiPopover.prototype.show = function () {
  6317. if(!JitsiPopover.enabled)
  6318. return;
  6319. this.createPopover();
  6320. this.popoverShown = true;
  6321. };
  6322. /**
  6323. * Hides the popover
  6324. */
  6325. JitsiPopover.prototype.hide = function () {
  6326. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6327. this.popoverShown) {
  6328. this.forceHide();
  6329. }
  6330. };
  6331. /**
  6332. * Hides the popover.
  6333. */
  6334. JitsiPopover.prototype.forceHide = function () {
  6335. $(".jitsipopover").remove();
  6336. this.popoverShown = false;
  6337. };
  6338. /**
  6339. * Creates the popover html.
  6340. */
  6341. JitsiPopover.prototype.createPopover = function () {
  6342. $("body").append(this.template);
  6343. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6344. var self = this;
  6345. $(".jitsipopover").on("mouseenter", function () {
  6346. self.popoverIsHovered = true;
  6347. }).on("mouseleave", function () {
  6348. self.popoverIsHovered = false;
  6349. self.hide();
  6350. });
  6351. this.refreshPosition();
  6352. };
  6353. /**
  6354. * Refreshes the position of the popover.
  6355. */
  6356. JitsiPopover.prototype.refreshPosition = function () {
  6357. $(".jitsipopover").position({
  6358. my: "bottom",
  6359. at: "top",
  6360. collision: "fit",
  6361. of: this.element,
  6362. using: function (position, elements) {
  6363. var calcLeft = elements.target.left - elements.element.left +
  6364. elements.target.width/2;
  6365. $(".jitsipopover").css(
  6366. {top: position.top, left: position.left, display: "table"});
  6367. $(".jitsipopover > .arrow").css({left: calcLeft});
  6368. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6369. {left: calcLeft - 50});
  6370. }
  6371. });
  6372. };
  6373. /**
  6374. * Updates the content of popover.
  6375. * @param content new content
  6376. */
  6377. JitsiPopover.prototype.updateContent = function (content) {
  6378. this.options.content = content;
  6379. if(!this.popoverShown)
  6380. return;
  6381. $(".jitsipopover").remove();
  6382. this.createPopover();
  6383. };
  6384. JitsiPopover.enabled = true;
  6385. return JitsiPopover;
  6386. })();
  6387. module.exports = JitsiPopover;
  6388. },{}],31:[function(require,module,exports){
  6389. /* global $, APP, jQuery, toastr */
  6390. /**
  6391. * Flag for enable/disable of the notifications.
  6392. * @type {boolean}
  6393. */
  6394. var notificationsEnabled = true;
  6395. var messageHandler = (function(my) {
  6396. /**
  6397. * Shows a message to the user.
  6398. *
  6399. * @param titleKey the title of the message
  6400. * @param messageKey the text of the message
  6401. */
  6402. my.openMessageDialog = function(titleKey, messageKey) {
  6403. var title = null;
  6404. if(titleKey) {
  6405. title = APP.translation.generateTranslationHTML(titleKey);
  6406. }
  6407. var message = APP.translation.generateTranslationHTML(messageKey);
  6408. $.prompt(message,
  6409. {title: title, persistent: false}
  6410. );
  6411. };
  6412. /**
  6413. * Shows a message to the user with two buttons: first is given as a
  6414. * parameter and the second is Cancel.
  6415. *
  6416. * @param titleString the title of the message
  6417. * @param msgString the text of the message
  6418. * @param persistent boolean value which determines whether the message is
  6419. * persistent or not
  6420. * @param leftButton the fist button's text
  6421. * @param submitFunction function to be called on submit
  6422. * @param loadedFunction function to be called after the prompt is fully
  6423. * loaded
  6424. * @param closeFunction function to be called after the prompt is closed
  6425. * @param focus optional focus selector or button index to be focused after
  6426. * the dialog is opened
  6427. * @param defaultButton index of default button which will be activated when
  6428. * the user press 'enter'. Indexed from 0.
  6429. */
  6430. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6431. persistent, leftButtonKey, submitFunction, loadedFunction,
  6432. closeFunction, focus, defaultButton) {
  6433. var buttons = [];
  6434. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6435. buttons.push({ title: leftButton, value: true});
  6436. var cancelButton
  6437. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6438. buttons.push({title: cancelButton, value: false});
  6439. var message = msgString, title = titleString;
  6440. if (titleKey) {
  6441. title = APP.translation.generateTranslationHTML(titleKey);
  6442. }
  6443. if (msgKey) {
  6444. message = APP.translation.generateTranslationHTML(msgKey);
  6445. }
  6446. $.prompt(message, {
  6447. title: title,
  6448. persistent: false,
  6449. buttons: buttons,
  6450. defaultButton: defaultButton,
  6451. focus: focus,
  6452. loaded: loadedFunction,
  6453. submit: submitFunction,
  6454. close: closeFunction
  6455. });
  6456. };
  6457. /**
  6458. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6459. *
  6460. * @param titleString the title of the message
  6461. * @param msgString the text of the message
  6462. * @param persistent boolean value which determines whether the message is
  6463. * persistent or not
  6464. * @param buttons object with the buttons. The keys must be the name of the
  6465. * button and value is the value that will be passed to
  6466. * submitFunction
  6467. * @param submitFunction function to be called on submit
  6468. * @param loadedFunction function to be called after the prompt is fully
  6469. * loaded
  6470. */
  6471. my.openDialog = function (titleString, msgString, persistent, buttons,
  6472. submitFunction, loadedFunction) {
  6473. var args = {
  6474. title: titleString,
  6475. persistent: persistent,
  6476. buttons: buttons,
  6477. defaultButton: 1,
  6478. loaded: loadedFunction,
  6479. submit: submitFunction
  6480. };
  6481. if (persistent) {
  6482. args.closeText = '';
  6483. }
  6484. return new Impromptu(msgString, args);
  6485. };
  6486. /**
  6487. * Closes currently opened dialog.
  6488. */
  6489. my.closeDialog = function () {
  6490. $.prompt.close();
  6491. };
  6492. /**
  6493. * Shows a dialog with different states to the user.
  6494. *
  6495. * @param statesObject object containing all the states of the dialog.
  6496. */
  6497. my.openDialogWithStates = function (statesObject, options) {
  6498. return new Impromptu(statesObject, options);
  6499. };
  6500. /**
  6501. * Opens new popup window for given <tt>url</tt> centered over current
  6502. * window.
  6503. *
  6504. * @param url the URL to be displayed in the popup window
  6505. * @param w the width of the popup window
  6506. * @param h the height of the popup window
  6507. * @param onPopupClosed optional callback function called when popup window
  6508. * has been closed.
  6509. *
  6510. * @returns {object} popup window object if opened successfully or undefined
  6511. * in case we failed to open it(popup blocked)
  6512. */
  6513. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6514. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6515. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6516. var popup = window.open(
  6517. url, '_blank',
  6518. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6519. if (popup && onPopupClosed) {
  6520. var pollTimer = window.setInterval(function () {
  6521. if (popup.closed !== false) {
  6522. window.clearInterval(pollTimer);
  6523. onPopupClosed();
  6524. }
  6525. }, 200);
  6526. }
  6527. return popup;
  6528. };
  6529. /**
  6530. * Shows a dialog prompting the user to send an error report.
  6531. *
  6532. * @param titleKey the title of the message
  6533. * @param msgKey the text of the message
  6534. * @param error the error that is being reported
  6535. */
  6536. my.openReportDialog = function(titleKey, msgKey, error) {
  6537. my.openMessageDialog(titleKey, msgKey);
  6538. console.log(error);
  6539. //FIXME send the error to the server
  6540. };
  6541. /**
  6542. * Shows an error dialog to the user.
  6543. * @param titleKey the title of the message.
  6544. * @param msgKey the text of the message.
  6545. */
  6546. my.showError = function(titleKey, msgKey) {
  6547. if (!titleKey) {
  6548. titleKey = "dialog.oops";
  6549. }
  6550. if (!msgKey) {
  6551. msgKey = "dialog.defaultError";
  6552. }
  6553. messageHandler.openMessageDialog(titleKey, msgKey);
  6554. };
  6555. /**
  6556. * Displayes notification.
  6557. * @param displayName display name of the participant that is associated with the notification.
  6558. * @param displayNameKey the key from the language file for the display name.
  6559. * @param cls css class for the notification
  6560. * @param messageKey the key from the language file for the text of the message.
  6561. * @param messageArguments object with the arguments for the message.
  6562. * @param options object with language options.
  6563. */
  6564. my.notify = function(displayName, displayNameKey,
  6565. cls, messageKey, messageArguments, options) {
  6566. if(!notificationsEnabled)
  6567. return;
  6568. var displayNameSpan = '<span class="nickname" ';
  6569. if (displayName) {
  6570. displayNameSpan += ">" + displayName;
  6571. } else {
  6572. displayNameSpan += "data-i18n='" + displayNameKey +
  6573. "'>" + APP.translation.translateString(displayNameKey);
  6574. }
  6575. displayNameSpan += "</span>";
  6576. return toastr.info(
  6577. displayNameSpan + '<br>' +
  6578. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6579. (messageArguments?
  6580. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6581. : "") + ">" +
  6582. APP.translation.translateString(messageKey,
  6583. messageArguments) +
  6584. '</span>', null, options);
  6585. };
  6586. /**
  6587. * Removes the toaster.
  6588. * @param toasterElement
  6589. */
  6590. my.remove = function(toasterElement) {
  6591. toasterElement.remove();
  6592. };
  6593. /**
  6594. * Disables notifications.
  6595. */
  6596. my.disableNotifications = function () {
  6597. notificationsEnabled = false;
  6598. };
  6599. /**
  6600. * Enables notifications.
  6601. */
  6602. my.enableNotifications = function () {
  6603. notificationsEnabled = true;
  6604. };
  6605. return my;
  6606. }(messageHandler || {}));
  6607. module.exports = messageHandler;
  6608. },{}],32:[function(require,module,exports){
  6609. var UIEvents = require("../../../service/UI/UIEvents");
  6610. var nickname = null;
  6611. var eventEmitter = null;
  6612. var NicknameHandler = {
  6613. init: function (emitter) {
  6614. eventEmitter = emitter;
  6615. var storedDisplayName = window.localStorage.displayname;
  6616. if (storedDisplayName) {
  6617. nickname = storedDisplayName;
  6618. }
  6619. },
  6620. setNickname: function (newNickname) {
  6621. if (!newNickname || nickname === newNickname)
  6622. return;
  6623. nickname = newNickname;
  6624. window.localStorage.displayname = nickname;
  6625. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6626. },
  6627. getNickname: function () {
  6628. return nickname;
  6629. },
  6630. addListener: function (type, listener) {
  6631. eventEmitter.on(type, listener);
  6632. }
  6633. };
  6634. module.exports = NicknameHandler;
  6635. },{"../../../service/UI/UIEvents":163}],33:[function(require,module,exports){
  6636. /* global $ */
  6637. /**
  6638. * Created by hristo on 12/22/14.
  6639. */
  6640. module.exports = {
  6641. /**
  6642. * Returns the available video width.
  6643. */
  6644. getAvailableVideoWidth: function (isVisible) {
  6645. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6646. if(typeof isVisible === "undefined" || isVisible === null)
  6647. isVisible = PanelToggler.isVisible();
  6648. var rightPanelWidth
  6649. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6650. return window.innerWidth - rightPanelWidth;
  6651. },
  6652. /**
  6653. * Changes the style class of the element given by id.
  6654. */
  6655. buttonClick: function(id, classname) {
  6656. $(id).toggleClass(classname); // add the class to the clicked element
  6657. },
  6658. /**
  6659. * Returns the text width for the given element.
  6660. *
  6661. * @param el the element
  6662. */
  6663. getTextWidth: function (el) {
  6664. return (el.clientWidth + 1);
  6665. },
  6666. /**
  6667. * Returns the text height for the given element.
  6668. *
  6669. * @param el the element
  6670. */
  6671. getTextHeight: function (el) {
  6672. return (el.clientHeight + 1);
  6673. },
  6674. /**
  6675. * Plays the sound given by id.
  6676. *
  6677. * @param id the identifier of the audio element.
  6678. */
  6679. playSoundNotification: function (id) {
  6680. document.getElementById(id).play();
  6681. },
  6682. /**
  6683. * Escapes the given text.
  6684. */
  6685. escapeHtml: function (unsafeText) {
  6686. return $('<div/>').text(unsafeText).html();
  6687. },
  6688. imageToGrayScale: function (canvas) {
  6689. var context = canvas.getContext('2d');
  6690. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6691. var pixels = imgData.data;
  6692. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6693. var grayscale
  6694. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  6695. pixels[i ] = grayscale; // red
  6696. pixels[i+1] = grayscale; // green
  6697. pixels[i+2] = grayscale; // blue
  6698. // pixels[i+3] is alpha
  6699. }
  6700. // redraw the image in black & white
  6701. context.putImageData(imgData, 0, 0);
  6702. },
  6703. setTooltip: function (element, key, position) {
  6704. element.setAttribute("data-i18n", "[data-content]" + key);
  6705. element.setAttribute("data-toggle", "popover");
  6706. element.setAttribute("data-placement", position);
  6707. element.setAttribute("data-html", true);
  6708. element.setAttribute("data-container", "body");
  6709. },
  6710. /**
  6711. * Inserts given child element as the first one into the container.
  6712. * @param container the container to which new child element will be added
  6713. * @param newChild the new element that will be inserted into the container
  6714. */
  6715. prependChild: function (container, newChild) {
  6716. var firstChild = container.childNodes[0];
  6717. if (firstChild) {
  6718. container.insertBefore(newChild, firstChild);
  6719. } else {
  6720. container.appendChild(newChild);
  6721. }
  6722. }
  6723. };
  6724. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6725. /* global APP, $ */
  6726. var JitsiPopover = require("../util/JitsiPopover");
  6727. /**
  6728. * Constructs new connection indicator.
  6729. * @param videoContainer the video container associated with the indicator.
  6730. * @constructor
  6731. */
  6732. function ConnectionIndicator(videoContainer, jid) {
  6733. this.videoContainer = videoContainer;
  6734. this.bandwidth = null;
  6735. this.packetLoss = null;
  6736. this.bitrate = null;
  6737. this.showMoreValue = false;
  6738. this.resolution = null;
  6739. this.transport = [];
  6740. this.popover = null;
  6741. this.jid = jid;
  6742. this.create();
  6743. }
  6744. /**
  6745. * Values for the connection quality
  6746. * @type {{98: string,
  6747. * 81: string,
  6748. * 64: string,
  6749. * 47: string,
  6750. * 30: string,
  6751. * 0: string}}
  6752. */
  6753. ConnectionIndicator.connectionQualityValues = {
  6754. 98: "18px", //full
  6755. 81: "15px",//4 bars
  6756. 64: "11px",//3 bars
  6757. 47: "7px",//2 bars
  6758. 30: "3px",//1 bar
  6759. 0: "0px"//empty
  6760. };
  6761. ConnectionIndicator.getIP = function(value) {
  6762. return value.substring(0, value.lastIndexOf(":"));
  6763. };
  6764. ConnectionIndicator.getPort = function(value) {
  6765. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6766. };
  6767. ConnectionIndicator.getStringFromArray = function (array) {
  6768. var res = "";
  6769. for(var i = 0; i < array.length; i++) {
  6770. res += (i === 0? "" : ", ") + array[i];
  6771. }
  6772. return res;
  6773. };
  6774. /**
  6775. * Generates the html content.
  6776. * @returns {string} the html content.
  6777. */
  6778. ConnectionIndicator.prototype.generateText = function () {
  6779. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6780. var translate = APP.translation.translateString;
  6781. if(this.bitrate === null) {
  6782. downloadBitrate = "N/A";
  6783. uploadBitrate = "N/A";
  6784. }
  6785. else {
  6786. downloadBitrate =
  6787. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6788. uploadBitrate =
  6789. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6790. }
  6791. if(this.packetLoss === null) {
  6792. packetLoss = "N/A";
  6793. } else {
  6794. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6795. (this.packetLoss.download !== null ?
  6796. this.packetLoss.download : "N/A") +
  6797. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6798. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  6799. "%";
  6800. }
  6801. var resolutionValue = null;
  6802. if(this.resolution && this.jid != null) {
  6803. var keys = Object.keys(this.resolution);
  6804. for(var ssrc in this.resolution) {
  6805. resolutionValue = this.resolution[ssrc];
  6806. }
  6807. }
  6808. if(this.jid === null) {
  6809. resolution = "";
  6810. if(this.resolution === null || !Object.keys(this.resolution) ||
  6811. Object.keys(this.resolution).length === 0) {
  6812. resolution = "N/A";
  6813. } else {
  6814. for (i in this.resolution) {
  6815. resolutionValue = this.resolution[i];
  6816. if (resolutionValue) {
  6817. if (resolutionValue.height &&
  6818. resolutionValue.width) {
  6819. resolution += (resolution === "" ? "" : ", ") +
  6820. resolutionValue.width + "x" +
  6821. resolutionValue.height;
  6822. }
  6823. }
  6824. }
  6825. }
  6826. } else if(!resolutionValue ||
  6827. !resolutionValue.height ||
  6828. !resolutionValue.width) {
  6829. resolution = "N/A";
  6830. } else {
  6831. resolution = resolutionValue.width + "x" + resolutionValue.height;
  6832. }
  6833. var result = "<table style='width:100%'>" +
  6834. "<tr>" +
  6835. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  6836. translate("connectionindicator.bitrate") + "</span></td>" +
  6837. "<td><span class='jitsipopover_green'>&darr;</span>" +
  6838. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  6839. uploadBitrate + "</td>" +
  6840. "</tr><tr>" +
  6841. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  6842. translate("connectionindicator.packetloss") + "</span></td>" +
  6843. "<td>" + packetLoss + "</td>" +
  6844. "</tr><tr>" +
  6845. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  6846. translate("connectionindicator.resolution") + "</span></td>" +
  6847. "<td>" + resolution + "</td></tr></table>";
  6848. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  6849. result += "<div class=\"jitsipopover_showmore\" " +
  6850. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  6851. // FIXME: we do not know local jid when this text is generated
  6852. //this.jid + "')\" data-i18n='connectionindicator." +
  6853. "local')\" data-i18n='connectionindicator." +
  6854. (this.showMoreValue ? "less" : "more") + "'>" +
  6855. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  6856. "</div><br />";
  6857. }
  6858. if (this.showMoreValue) {
  6859. var downloadBandwidth, uploadBandwidth, transport;
  6860. if (this.bandwidth === null) {
  6861. downloadBandwidth = "N/A";
  6862. uploadBandwidth = "N/A";
  6863. } else {
  6864. downloadBandwidth = this.bandwidth.download?
  6865. this.bandwidth.download + " Kbps" :
  6866. "N/A";
  6867. uploadBandwidth = this.bandwidth.upload?
  6868. this.bandwidth.upload + " Kbps" :
  6869. "N/A";
  6870. }
  6871. if (!this.transport || this.transport.length === 0) {
  6872. transport = "<tr>" +
  6873. "<td><span class='jitsipopover_blue' " +
  6874. "data-i18n='connectionindicator.address'>" +
  6875. translate("connectionindicator.address") + "</span></td>" +
  6876. "<td> N/A</td></tr>";
  6877. } else {
  6878. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  6879. for(i = 0; i < this.transport.length; i++) {
  6880. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  6881. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  6882. var localIP =
  6883. ConnectionIndicator.getIP(this.transport[i].localip);
  6884. var localPort =
  6885. ConnectionIndicator.getPort(this.transport[i].localip);
  6886. if(data.remoteIP.indexOf(ip) == -1) {
  6887. data.remoteIP.push(ip);
  6888. }
  6889. if(data.remotePort.indexOf(port) == -1) {
  6890. data.remotePort.push(port);
  6891. }
  6892. if(data.localIP.indexOf(localIP) == -1) {
  6893. data.localIP.push(localIP);
  6894. }
  6895. if(data.localPort.indexOf(localPort) == -1) {
  6896. data.localPort.push(localPort);
  6897. }
  6898. }
  6899. var local_address_key = "connectionindicator.localaddress";
  6900. var remote_address_key = "connectionindicator.remoteaddress";
  6901. var localTransport =
  6902. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6903. local_address_key +"' data-i18n-options='" +
  6904. JSON.stringify({count: data.localIP.length}) + "'>" +
  6905. translate(local_address_key, {count: data.localIP.length}) +
  6906. "</span></td><td> " +
  6907. ConnectionIndicator.getStringFromArray(data.localIP) +
  6908. "</td></tr>";
  6909. transport =
  6910. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6911. remote_address_key + "' data-i18n-options='" +
  6912. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  6913. translate(remote_address_key,
  6914. {count: data.remoteIP.length}) +
  6915. "</span></td><td> " +
  6916. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  6917. "</td></tr>";
  6918. var key_remote = "connectionindicator.remoteport",
  6919. key_local = "connectionindicator.localport";
  6920. transport += "<tr>" +
  6921. "<td>" +
  6922. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  6923. "' data-i18n-options='" +
  6924. JSON.stringify({count: this.transport.length}) + "'>" +
  6925. translate(key_remote, {count: this.transport.length}) +
  6926. "</span></td><td>";
  6927. localTransport += "<tr>" +
  6928. "<td>" +
  6929. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  6930. "' data-i18n-options='" +
  6931. JSON.stringify({count: this.transport.length}) + "'>" +
  6932. translate(key_local, {count: this.transport.length}) +
  6933. "</span></td><td>";
  6934. transport +=
  6935. ConnectionIndicator.getStringFromArray(data.remotePort);
  6936. localTransport +=
  6937. ConnectionIndicator.getStringFromArray(data.localPort);
  6938. transport += "</td></tr>";
  6939. transport += localTransport + "</td></tr>";
  6940. transport +="<tr>" +
  6941. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  6942. translate("connectionindicator.transport") + "</span></td>" +
  6943. "<td>" + this.transport[0].type + "</td></tr>";
  6944. }
  6945. result += "<table style='width:100%'>" +
  6946. "<tr>" +
  6947. "<td>" +
  6948. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  6949. translate("connectionindicator.bandwidth") + "</span>" +
  6950. "</td><td>" +
  6951. "<span class='jitsipopover_green'>&darr;</span>" +
  6952. downloadBandwidth +
  6953. " <span class='jitsipopover_orange'>&uarr;</span>" +
  6954. uploadBandwidth + "</td></tr>";
  6955. result += transport + "</table>";
  6956. }
  6957. return result;
  6958. };
  6959. /**
  6960. * Shows or hide the additional information.
  6961. */
  6962. ConnectionIndicator.prototype.showMore = function () {
  6963. this.showMoreValue = !this.showMoreValue;
  6964. this.updatePopoverData();
  6965. };
  6966. function createIcon(classes) {
  6967. var icon = document.createElement("span");
  6968. for(var i in classes) {
  6969. icon.classList.add(classes[i]);
  6970. }
  6971. icon.appendChild(
  6972. document.createElement("i")).classList.add("icon-connection");
  6973. return icon;
  6974. }
  6975. /**
  6976. * Creates the indicator
  6977. */
  6978. ConnectionIndicator.prototype.create = function () {
  6979. this.connectionIndicatorContainer = document.createElement("div");
  6980. this.connectionIndicatorContainer.className = "connectionindicator";
  6981. this.connectionIndicatorContainer.style.display = "none";
  6982. this.videoContainer.container.appendChild(
  6983. this.connectionIndicatorContainer);
  6984. this.popover = new JitsiPopover(
  6985. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  6986. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  6987. APP.translation.translateString("connectionindicator.na") + "</div>",
  6988. skin: "black"});
  6989. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  6990. createIcon(["connection", "connection_empty"]));
  6991. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  6992. createIcon(["connection", "connection_full"]));
  6993. };
  6994. /**
  6995. * Removes the indicator
  6996. */
  6997. ConnectionIndicator.prototype.remove = function() {
  6998. if (this.connectionIndicatorContainer.parentNode) {
  6999. this.connectionIndicatorContainer.parentNode.removeChild(
  7000. this.connectionIndicatorContainer);
  7001. }
  7002. this.popover.forceHide();
  7003. };
  7004. /**
  7005. * Updates the data of the indicator
  7006. * @param percent the percent of connection quality
  7007. * @param object the statistics data.
  7008. */
  7009. ConnectionIndicator.prototype.updateConnectionQuality =
  7010. function (percent, object) {
  7011. if (percent === null) {
  7012. this.connectionIndicatorContainer.style.display = "none";
  7013. this.popover.forceHide();
  7014. return;
  7015. } else {
  7016. if(this.connectionIndicatorContainer.style.display == "none") {
  7017. this.connectionIndicatorContainer.style.display = "block";
  7018. this.videoContainer.updateIconPositions();
  7019. }
  7020. }
  7021. this.bandwidth = object.bandwidth;
  7022. this.bitrate = object.bitrate;
  7023. this.packetLoss = object.packetLoss;
  7024. this.transport = object.transport;
  7025. if (object.resolution) {
  7026. this.resolution = object.resolution;
  7027. }
  7028. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7029. if (percent >= quality) {
  7030. this.fullIcon.style.width =
  7031. ConnectionIndicator.connectionQualityValues[quality];
  7032. }
  7033. }
  7034. this.updatePopoverData();
  7035. };
  7036. /**
  7037. * Updates the resolution
  7038. * @param resolution the new resolution
  7039. */
  7040. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7041. this.resolution = resolution;
  7042. this.updatePopoverData();
  7043. };
  7044. /**
  7045. * Updates the content of the popover
  7046. */
  7047. ConnectionIndicator.prototype.updatePopoverData = function () {
  7048. this.popover.updateContent(
  7049. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7050. APP.translation.translateElement($(".connection_info"));
  7051. };
  7052. /**
  7053. * Hides the popover
  7054. */
  7055. ConnectionIndicator.prototype.hide = function () {
  7056. this.popover.forceHide();
  7057. };
  7058. /**
  7059. * Hides the indicator
  7060. */
  7061. ConnectionIndicator.prototype.hideIndicator = function () {
  7062. this.connectionIndicatorContainer.style.display = "none";
  7063. if(this.popover)
  7064. this.popover.forceHide();
  7065. };
  7066. module.exports = ConnectionIndicator;
  7067. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7068. /* global $, APP, Strophe, interfaceConfig */
  7069. var Avatar = require("../avatar/Avatar");
  7070. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7071. var UIUtil = require("../util/UIUtil");
  7072. var UIEvents = require("../../../service/UI/UIEvents");
  7073. var xmpp = require("../../xmpp/xmpp");
  7074. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7075. // FIXME: With Temasys we have to re-select everytime
  7076. //var video = $('#largeVideo');
  7077. var currentVideoWidth = null;
  7078. var currentVideoHeight = null;
  7079. // By default we use camera
  7080. var getVideoSize = getCameraVideoSize;
  7081. var getVideoPosition = getCameraVideoPosition;
  7082. /**
  7083. * The small video instance that is displayed in the large video
  7084. * @type {SmallVideo}
  7085. */
  7086. var currentSmallVideo = null;
  7087. /**
  7088. * Indicates whether the large video is enabled.
  7089. * @type {boolean}
  7090. */
  7091. var isEnabled = true;
  7092. /**
  7093. * Current large video state.
  7094. * Possible values - video, prezi or etherpad.
  7095. * @type {string}
  7096. */
  7097. var state = "video";
  7098. /**
  7099. * Returns the html element associated with the passed state of large video
  7100. * @param state the state.
  7101. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7102. */
  7103. function getContainerByState(state)
  7104. {
  7105. var selector = null;
  7106. switch (state)
  7107. {
  7108. case "video":
  7109. selector = "#largeVideo";
  7110. break;
  7111. case "etherpad":
  7112. selector = "#etherpad>iframe";
  7113. break;
  7114. case "prezi":
  7115. selector = "#presentation>iframe";
  7116. break;
  7117. }
  7118. return (selector !== null)? $(selector) : null;
  7119. }
  7120. /**
  7121. * Sets the size and position of the given video element.
  7122. *
  7123. * @param video the video element to position
  7124. * @param width the desired video width
  7125. * @param height the desired video height
  7126. * @param horizontalIndent the left and right indent
  7127. * @param verticalIndent the top and bottom indent
  7128. */
  7129. function positionVideo(video,
  7130. width,
  7131. height,
  7132. horizontalIndent,
  7133. verticalIndent,
  7134. animate) {
  7135. if (animate) {
  7136. video.animate({
  7137. width: width,
  7138. height: height,
  7139. top: verticalIndent,
  7140. bottom: verticalIndent,
  7141. left: horizontalIndent,
  7142. right: horizontalIndent
  7143. },
  7144. {
  7145. queue: false,
  7146. duration: 500
  7147. });
  7148. } else {
  7149. video.width(width);
  7150. video.height(height);
  7151. video.css({ top: verticalIndent + 'px',
  7152. bottom: verticalIndent + 'px',
  7153. left: horizontalIndent + 'px',
  7154. right: horizontalIndent + 'px'});
  7155. }
  7156. }
  7157. /**
  7158. * Returns an array of the video dimensions, so that it keeps it's aspect
  7159. * ratio and fits available area with it's larger dimension. This method
  7160. * ensures that whole video will be visible and can leave empty areas.
  7161. *
  7162. * @return an array with 2 elements, the video width and the video height
  7163. */
  7164. function getDesktopVideoSize(videoWidth,
  7165. videoHeight,
  7166. videoSpaceWidth,
  7167. videoSpaceHeight) {
  7168. if (!videoWidth)
  7169. videoWidth = currentVideoWidth;
  7170. if (!videoHeight)
  7171. videoHeight = currentVideoHeight;
  7172. var aspectRatio = videoWidth / videoHeight;
  7173. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7174. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7175. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7176. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7177. {
  7178. availableHeight = videoSpaceHeight;
  7179. availableWidth = availableHeight * aspectRatio;
  7180. }
  7181. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7182. {
  7183. availableWidth = videoSpaceWidth;
  7184. availableHeight = availableWidth / aspectRatio;
  7185. }
  7186. return [availableWidth, availableHeight];
  7187. }
  7188. /**
  7189. * Returns an array of the video horizontal and vertical indents,
  7190. * so that if fits its parent.
  7191. *
  7192. * @return an array with 2 elements, the horizontal indent and the vertical
  7193. * indent
  7194. */
  7195. function getCameraVideoPosition(videoWidth,
  7196. videoHeight,
  7197. videoSpaceWidth,
  7198. videoSpaceHeight) {
  7199. // Parent height isn't completely calculated when we position the video in
  7200. // full screen mode and this is why we use the screen height in this case.
  7201. // Need to think it further at some point and implement it properly.
  7202. var isFullScreen = document.fullScreen ||
  7203. document.mozFullScreen ||
  7204. document.webkitIsFullScreen;
  7205. if (isFullScreen)
  7206. videoSpaceHeight = window.innerHeight;
  7207. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7208. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7209. return [horizontalIndent, verticalIndent];
  7210. }
  7211. /**
  7212. * Returns an array of the video horizontal and vertical indents.
  7213. * Centers horizontally and top aligns vertically.
  7214. *
  7215. * @return an array with 2 elements, the horizontal indent and the vertical
  7216. * indent
  7217. */
  7218. function getDesktopVideoPosition(videoWidth,
  7219. videoHeight,
  7220. videoSpaceWidth,
  7221. videoSpaceHeight) {
  7222. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7223. var verticalIndent = 0;// Top aligned
  7224. return [horizontalIndent, verticalIndent];
  7225. }
  7226. /**
  7227. * Returns an array of the video dimensions, so that it covers the screen.
  7228. * It leaves no empty areas, but some parts of the video might not be visible.
  7229. *
  7230. * @return an array with 2 elements, the video width and the video height
  7231. */
  7232. function getCameraVideoSize(videoWidth,
  7233. videoHeight,
  7234. videoSpaceWidth,
  7235. videoSpaceHeight) {
  7236. if (!videoWidth)
  7237. videoWidth = currentVideoWidth;
  7238. if (!videoHeight)
  7239. videoHeight = currentVideoHeight;
  7240. var aspectRatio = videoWidth / videoHeight;
  7241. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7242. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7243. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7244. availableHeight = videoSpaceHeight;
  7245. availableWidth = availableHeight * aspectRatio;
  7246. }
  7247. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7248. availableWidth = videoSpaceWidth;
  7249. availableHeight = availableWidth / aspectRatio;
  7250. }
  7251. return [availableWidth, availableHeight];
  7252. }
  7253. /**
  7254. * Updates the src of the active speaker avatar
  7255. * @param jid of the current active speaker
  7256. */
  7257. function updateActiveSpeakerAvatarSrc() {
  7258. var avatar = $("#activeSpeakerAvatar")[0];
  7259. var jid = currentSmallVideo.peerJid;
  7260. var url = Avatar.getActiveSpeakerUrl(jid);
  7261. if (avatar.src === url)
  7262. return;
  7263. if (jid) {
  7264. avatar.src = url;
  7265. currentSmallVideo.showAvatar();
  7266. }
  7267. }
  7268. /**
  7269. * Change the video source of the large video.
  7270. * @param isVisible
  7271. */
  7272. function changeVideo(isVisible) {
  7273. if (!currentSmallVideo) {
  7274. console.error("Unable to change large video - no 'currentSmallVideo'");
  7275. return;
  7276. }
  7277. updateActiveSpeakerAvatarSrc();
  7278. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7279. var videoTransform = document.getElementById('largeVideo')
  7280. .style.webkitTransform;
  7281. var flipX = currentSmallVideo.flipX;
  7282. if (flipX && videoTransform !== 'scaleX(-1)') {
  7283. document.getElementById('largeVideo').style.webkitTransform =
  7284. "scaleX(-1)";
  7285. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7286. document.getElementById('largeVideo').style.webkitTransform =
  7287. "none";
  7288. }
  7289. var isDesktop = currentSmallVideo.getVideoType() === 'screen';
  7290. // Change the way we'll be measuring and positioning large video
  7291. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7292. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7293. getCameraVideoPosition;
  7294. // Only if the large video is currently visible.
  7295. if (isVisible) {
  7296. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7297. $('#largeVideoWrapper').fadeIn(300);
  7298. }
  7299. }
  7300. /**
  7301. * Creates the html elements for the large video.
  7302. */
  7303. function createLargeVideoHTML()
  7304. {
  7305. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7306. html += '<div id="presentation"></div>' +
  7307. '<div id="etherpad"></div>' +
  7308. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7309. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7310. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7311. '<span data-i18n="poweredby"></span> jitsi.org' +
  7312. '</a>'+
  7313. '<div id="activeSpeaker">' +
  7314. '<img id="activeSpeakerAvatar" src=""/>' +
  7315. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7316. '</div>' +
  7317. '<div id="largeVideoWrapper">' +
  7318. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7319. '</div id="largeVideoWrapper">' +
  7320. '<span id="videoConnectionMessage"></span>';
  7321. html += '</div>';
  7322. $(html).prependTo("#videospace");
  7323. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7324. var leftWatermarkDiv
  7325. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7326. leftWatermarkDiv.css({display: 'block'});
  7327. leftWatermarkDiv.parent().get(0).href
  7328. = interfaceConfig.JITSI_WATERMARK_LINK;
  7329. }
  7330. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7331. var rightWatermarkDiv
  7332. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7333. rightWatermarkDiv.css({display: 'block'});
  7334. rightWatermarkDiv.parent().get(0).href
  7335. = interfaceConfig.BRAND_WATERMARK_LINK;
  7336. rightWatermarkDiv.get(0).style.backgroundImage
  7337. = "url(images/rightwatermark.png)";
  7338. }
  7339. if (interfaceConfig.SHOW_POWERED_BY) {
  7340. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7341. }
  7342. if (!RTCBrowserType.isIExplorer()) {
  7343. $('#largeVideo').volume = 0;
  7344. }
  7345. }
  7346. var LargeVideo = {
  7347. init: function (VideoLayout, emitter) {
  7348. if(!isEnabled)
  7349. return;
  7350. createLargeVideoHTML();
  7351. this.VideoLayout = VideoLayout;
  7352. this.eventEmitter = emitter;
  7353. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7354. var self = this;
  7355. // Listen for large video size updates
  7356. var largeVideo = $('#largeVideo')[0];
  7357. var onplaying = function (arg1, arg2, arg3) {
  7358. // re-select
  7359. if (RTCBrowserType.isTemasysPluginUsed())
  7360. largeVideo = $('#largeVideo')[0];
  7361. currentVideoWidth = largeVideo.videoWidth;
  7362. currentVideoHeight = largeVideo.videoHeight;
  7363. self.position(currentVideoWidth, currentVideoHeight);
  7364. };
  7365. largeVideo.onplaying = onplaying;
  7366. },
  7367. /**
  7368. * Indicates if the large video is currently visible.
  7369. *
  7370. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7371. */
  7372. isLargeVideoVisible: function() {
  7373. return $('#largeVideo').is(':visible');
  7374. },
  7375. /**
  7376. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7377. */
  7378. isCurrentlyOnLarge: function (resourceJid) {
  7379. return currentSmallVideo && resourceJid &&
  7380. currentSmallVideo.getResourceJid() === resourceJid;
  7381. },
  7382. /**
  7383. * Updates the large video with the given new video source.
  7384. */
  7385. updateLargeVideo: function (resourceJid, forceUpdate) {
  7386. if(!isEnabled)
  7387. return;
  7388. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7389. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7390. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7391. $('#activeSpeaker').css('visibility', 'hidden');
  7392. var oldSmallVideo = null;
  7393. if (currentSmallVideo) {
  7394. oldSmallVideo = currentSmallVideo;
  7395. }
  7396. currentSmallVideo = newSmallVideo;
  7397. var oldJid = null;
  7398. if (oldSmallVideo)
  7399. oldJid = oldSmallVideo.peerJid;
  7400. if (oldJid !== resourceJid) {
  7401. // we want the notification to trigger even if userJid is undefined,
  7402. // or null.
  7403. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7404. }
  7405. // We are doing fadeOut/fadeIn animations on parent div which wraps
  7406. // largeVideo, because when Temasys plugin is in use it replaces
  7407. // <video> elements with plugin <object> tag. In Safari jQuery is
  7408. // unable to store values on this plugin object which breaks all
  7409. // animation effects performed on it directly.
  7410. $('#largeVideoWrapper').fadeOut(300,
  7411. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7412. } else {
  7413. if (currentSmallVideo) {
  7414. currentSmallVideo.showAvatar();
  7415. }
  7416. }
  7417. },
  7418. /**
  7419. * Shows/hides the large video.
  7420. */
  7421. setLargeVideoVisible: function(isVisible) {
  7422. if(!isEnabled)
  7423. return;
  7424. if (isVisible) {
  7425. $('#largeVideo').css({visibility: 'visible'});
  7426. $('.watermark').css({visibility: 'visible'});
  7427. if(currentSmallVideo)
  7428. currentSmallVideo.enableDominantSpeaker(true);
  7429. }
  7430. else {
  7431. $('#largeVideo').css({visibility: 'hidden'});
  7432. $('#activeSpeaker').css('visibility', 'hidden');
  7433. $('.watermark').css({visibility: 'hidden'});
  7434. if(currentSmallVideo)
  7435. currentSmallVideo.enableDominantSpeaker(false);
  7436. }
  7437. },
  7438. onVideoTypeChanged: function (resourceJid, newVideoType) {
  7439. if (!isEnabled)
  7440. return;
  7441. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7442. {
  7443. var isDesktop = newVideoType === 'screen';
  7444. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7445. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7446. : getCameraVideoPosition;
  7447. this.position(null, null, null, null, true);
  7448. }
  7449. },
  7450. /**
  7451. * Positions the large video.
  7452. *
  7453. * @param videoWidth the stream video width
  7454. * @param videoHeight the stream video height
  7455. */
  7456. position: function (videoWidth, videoHeight,
  7457. videoSpaceWidth, videoSpaceHeight, animate) {
  7458. if(!isEnabled)
  7459. return;
  7460. if(!videoSpaceWidth)
  7461. videoSpaceWidth = $('#videospace').width();
  7462. if(!videoSpaceHeight)
  7463. videoSpaceHeight = window.innerHeight;
  7464. var videoSize = getVideoSize(videoWidth,
  7465. videoHeight,
  7466. videoSpaceWidth,
  7467. videoSpaceHeight);
  7468. var largeVideoWidth = videoSize[0];
  7469. var largeVideoHeight = videoSize[1];
  7470. var videoPosition = getVideoPosition(largeVideoWidth,
  7471. largeVideoHeight,
  7472. videoSpaceWidth,
  7473. videoSpaceHeight);
  7474. var horizontalIndent = videoPosition[0];
  7475. var verticalIndent = videoPosition[1];
  7476. positionVideo($('#largeVideoWrapper'),
  7477. largeVideoWidth,
  7478. largeVideoHeight,
  7479. horizontalIndent, verticalIndent, animate);
  7480. },
  7481. /**
  7482. * Resizes the large html elements.
  7483. * @param animate boolean property that indicates whether the resize should be animated or not.
  7484. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  7485. * If that parameter is null the method will check the chat pannel visibility.
  7486. * @param completeFunction a function to be called when the video space is resized
  7487. * @returns {*[]} array with the current width and height values of the largeVideo html element.
  7488. */
  7489. resize: function (animate, isVisible, completeFunction) {
  7490. if(!isEnabled)
  7491. return;
  7492. var availableHeight = window.innerHeight;
  7493. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7494. if (availableWidth < 0 || availableHeight < 0) return;
  7495. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7496. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7497. $('#activeSpeaker').css('top', top);
  7498. this.VideoLayout.resizeVideoSpace(animate, isVisible, completeFunction);
  7499. if(animate) {
  7500. $('#largeVideoContainer').animate({
  7501. width: availableWidth,
  7502. height: availableHeight
  7503. },
  7504. {
  7505. queue: false,
  7506. duration: 500
  7507. });
  7508. } else {
  7509. $('#largeVideoContainer').width(availableWidth);
  7510. $('#largeVideoContainer').height(availableHeight);
  7511. }
  7512. return [availableWidth, availableHeight];
  7513. },
  7514. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7515. if(!isEnabled)
  7516. return;
  7517. var size = this.resize(true, isVisible, completeFunction);
  7518. this.position(null, null, size[0], size[1], true);
  7519. },
  7520. getResourceJid: function () {
  7521. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7522. },
  7523. updateAvatar: function (resourceJid) {
  7524. if(!isEnabled)
  7525. return;
  7526. if (resourceJid === this.getResourceJid()) {
  7527. updateActiveSpeakerAvatarSrc();
  7528. }
  7529. },
  7530. showAvatar: function (resourceJid, show) {
  7531. if(!isEnabled)
  7532. return;
  7533. if(this.getResourceJid() === resourceJid && state === "video") {
  7534. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7535. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7536. return true;
  7537. }
  7538. return false;
  7539. },
  7540. /**
  7541. * Disables the large video
  7542. */
  7543. disable: function () {
  7544. isEnabled = false;
  7545. },
  7546. /**
  7547. * Enables the large video
  7548. */
  7549. enable: function () {
  7550. isEnabled = true;
  7551. },
  7552. /**
  7553. * Returns true if the video is enabled.
  7554. */
  7555. isEnabled: function () {
  7556. return isEnabled;
  7557. },
  7558. /**
  7559. * Creates the iframe used by the etherpad
  7560. * @param src the value for src attribute
  7561. * @param onloadHandler handler executed when the iframe loads it content
  7562. * @returns {HTMLElement} the iframe
  7563. */
  7564. createEtherpadIframe: function (src, onloadHandler) {
  7565. if(!isEnabled)
  7566. return;
  7567. var etherpadIFrame = document.createElement('iframe');
  7568. etherpadIFrame.src = src;
  7569. etherpadIFrame.frameBorder = 0;
  7570. etherpadIFrame.scrolling = "no";
  7571. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  7572. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  7573. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  7574. document.getElementById('etherpad').appendChild(etherpadIFrame);
  7575. etherpadIFrame.onload = onloadHandler;
  7576. return etherpadIFrame;
  7577. },
  7578. /**
  7579. * Changes the state of the large video.
  7580. * Possible values - video, prezi, etherpad.
  7581. * @param newState - the new state
  7582. */
  7583. setState: function (newState) {
  7584. if(state === newState)
  7585. return;
  7586. var currentContainer = getContainerByState(state);
  7587. if(!currentContainer)
  7588. return;
  7589. var self = this;
  7590. var oldState = state;
  7591. switch (newState)
  7592. {
  7593. case "etherpad":
  7594. $('#activeSpeaker').css('visibility', 'hidden');
  7595. currentContainer.fadeOut(300, function () {
  7596. if (oldState === "prezi") {
  7597. currentContainer.css({opacity: '0'});
  7598. $('#reloadPresentation').css({display: 'none'});
  7599. }
  7600. else {
  7601. self.setLargeVideoVisible(false);
  7602. }
  7603. });
  7604. $('#etherpad>iframe').fadeIn(300, function () {
  7605. document.body.style.background = '#eeeeee';
  7606. $('#etherpad>iframe').css({visibility: 'visible'});
  7607. $('#etherpad').css({zIndex: 2});
  7608. });
  7609. break;
  7610. case "prezi":
  7611. var prezi = $('#presentation>iframe');
  7612. currentContainer.fadeOut(300, function() {
  7613. document.body.style.background = 'black';
  7614. });
  7615. prezi.fadeIn(300, function() {
  7616. prezi.css({opacity:'1'});
  7617. ToolbarToggler.dockToolbar(true);//fix that
  7618. self.setLargeVideoVisible(false);
  7619. $('#etherpad>iframe').css({visibility: 'hidden'});
  7620. $('#etherpad').css({zIndex: 0});
  7621. });
  7622. $('#activeSpeaker').css('visibility', 'hidden');
  7623. break;
  7624. case "video":
  7625. currentContainer.fadeOut(300, function () {
  7626. $('#presentation>iframe').css({opacity:'0'});
  7627. $('#reloadPresentation').css({display:'none'});
  7628. $('#etherpad>iframe').css({visibility: 'hidden'});
  7629. $('#etherpad').css({zIndex: 0});
  7630. document.body.style.background = 'black';
  7631. ToolbarToggler.dockToolbar(false);//fix that
  7632. });
  7633. $('#largeVideoWrapper').fadeIn(300, function () {
  7634. self.setLargeVideoVisible(true);
  7635. });
  7636. break;
  7637. }
  7638. state = newState;
  7639. },
  7640. /**
  7641. * Returns the current state of the large video.
  7642. * @returns {string} the current state - video, prezi or etherpad.
  7643. */
  7644. getState: function () {
  7645. return state;
  7646. },
  7647. /**
  7648. * Sets hover handlers for the large video container div.
  7649. *
  7650. * @param inHandler
  7651. * @param outHandler
  7652. */
  7653. setHover: function(inHandler, outHandler)
  7654. {
  7655. $('#largeVideoContainer').hover(inHandler, outHandler);
  7656. },
  7657. /**
  7658. * Enables/disables the filter indicating a video problem to the user.
  7659. *
  7660. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  7661. */
  7662. enableVideoProblemFilter: function (enable) {
  7663. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  7664. }
  7665. };
  7666. module.exports = LargeVideo;
  7667. },{"../../../service/UI/UIEvents":163,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":68,"../avatar/Avatar":16,"../toolbars/ToolbarToggler":29,"../util/UIUtil":33}],36:[function(require,module,exports){
  7668. /* global $, interfaceConfig, APP */
  7669. var SmallVideo = require("./SmallVideo");
  7670. var ConnectionIndicator = require("./ConnectionIndicator");
  7671. var NicknameHandler = require("../util/NicknameHandler");
  7672. var UIUtil = require("../util/UIUtil");
  7673. var LargeVideo = require("./LargeVideo");
  7674. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7675. function LocalVideo(VideoLayout) {
  7676. this.videoSpanId = "localVideoContainer";
  7677. this.container = $("#localVideoContainer").get(0);
  7678. this.VideoLayout = VideoLayout;
  7679. this.flipX = true;
  7680. this.isLocal = true;
  7681. this.peerJid = null;
  7682. }
  7683. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7684. LocalVideo.prototype.constructor = LocalVideo;
  7685. /**
  7686. * Creates the edit display name button.
  7687. *
  7688. * @returns {object} the edit button
  7689. */
  7690. function createEditDisplayNameButton() {
  7691. var editButton = document.createElement('a');
  7692. editButton.className = 'displayname';
  7693. UIUtil.setTooltip(editButton,
  7694. "videothumbnail.editnickname",
  7695. "top");
  7696. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7697. return editButton;
  7698. }
  7699. /**
  7700. * Sets the display name for the given video span id.
  7701. */
  7702. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7703. if (!this.container) {
  7704. console.warn(
  7705. "Unable to set displayName - " + this.videoSpanId +
  7706. " does not exist");
  7707. return;
  7708. }
  7709. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7710. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7711. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7712. var meHTML;
  7713. // If we already have a display name for this video.
  7714. if (nameSpan.length > 0) {
  7715. if (nameSpan.text() !== displayName) {
  7716. if (displayName && displayName.length > 0) {
  7717. meHTML = APP.translation.generateTranslationHTML("me");
  7718. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7719. } else {
  7720. $('#localDisplayName').html(defaultLocalDisplayName);
  7721. }
  7722. }
  7723. } else {
  7724. var editButton = createEditDisplayNameButton();
  7725. nameSpan = document.createElement('span');
  7726. nameSpan.className = 'displayname';
  7727. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7728. if (displayName && displayName.length > 0) {
  7729. meHTML = APP.translation.generateTranslationHTML("me");
  7730. nameSpan.innerHTML = displayName + meHTML;
  7731. }
  7732. else {
  7733. nameSpan.innerHTML = defaultLocalDisplayName;
  7734. }
  7735. nameSpan.id = 'localDisplayName';
  7736. this.container.appendChild(editButton);
  7737. //translates popover of edit button
  7738. APP.translation.translateElement($("a.displayname"));
  7739. var editableText = document.createElement('input');
  7740. editableText.className = 'displayname';
  7741. editableText.type = 'text';
  7742. editableText.id = 'editDisplayName';
  7743. if (displayName && displayName.length) {
  7744. editableText.value = displayName;
  7745. }
  7746. var defaultNickname = APP.translation.translateString(
  7747. "defaultNickname", {name: "Jane Pink"});
  7748. editableText.setAttribute('style', 'display:none;');
  7749. editableText.setAttribute('data-18n',
  7750. '[placeholder]defaultNickname');
  7751. editableText.setAttribute("data-i18n-options",
  7752. JSON.stringify({name: "Jane Pink"}));
  7753. editableText.setAttribute("placeholder", defaultNickname);
  7754. this.container.appendChild(editableText);
  7755. var self = this;
  7756. $('#localVideoContainer .displayname')
  7757. .bind("click", function (e) {
  7758. var editDisplayName = $('#editDisplayName');
  7759. e.preventDefault();
  7760. e.stopPropagation();
  7761. $('#localDisplayName').hide();
  7762. editDisplayName.show();
  7763. editDisplayName.focus();
  7764. editDisplayName.select();
  7765. editDisplayName.one("focusout", function (e) {
  7766. self.VideoLayout.inputDisplayNameHandler(this.value);
  7767. });
  7768. editDisplayName.on('keydown', function (e) {
  7769. if (e.keyCode === 13) {
  7770. e.preventDefault();
  7771. self.VideoLayout.inputDisplayNameHandler(this.value);
  7772. }
  7773. });
  7774. });
  7775. }
  7776. };
  7777. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7778. NicknameHandler.setNickname(name);
  7779. var localDisplayName = $('#localDisplayName');
  7780. if (!localDisplayName.is(":visible")) {
  7781. if (NicknameHandler.getNickname()) {
  7782. var meHTML = APP.translation.generateTranslationHTML("me");
  7783. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  7784. meHTML + ")");
  7785. } else {
  7786. var defaultHTML = APP.translation.generateTranslationHTML(
  7787. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7788. localDisplayName .html(defaultHTML);
  7789. }
  7790. localDisplayName.show();
  7791. }
  7792. $('#editDisplayName').hide();
  7793. };
  7794. LocalVideo.prototype.createConnectionIndicator = function() {
  7795. if(this.connectionIndicator)
  7796. return;
  7797. this.connectionIndicator = new ConnectionIndicator(this, null);
  7798. };
  7799. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7800. var self = this;
  7801. function localVideoClick(event) {
  7802. // FIXME: with Temasys plugin event arg is not an event, but
  7803. // the clicked object itself, so we have to skip this call
  7804. if (event.stopPropagation) {
  7805. event.stopPropagation();
  7806. }
  7807. self.VideoLayout.handleVideoThumbClicked(
  7808. false,
  7809. APP.xmpp.myResource());
  7810. }
  7811. var localVideoContainerSelector = $('#localVideoContainer');
  7812. localVideoContainerSelector.off('click');
  7813. localVideoContainerSelector.on('click', localVideoClick);
  7814. // Add hover handler
  7815. localVideoContainerSelector.hover(
  7816. function() {
  7817. self.showDisplayName(true);
  7818. },
  7819. function() {
  7820. if (!LargeVideo.isLargeVideoVisible() ||
  7821. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid())) {
  7822. self.showDisplayName(false);
  7823. }
  7824. }
  7825. );
  7826. if(isMuted) {
  7827. APP.UI.setVideoMute(true);
  7828. return;
  7829. }
  7830. this.flipX = stream.videoType != "screen";
  7831. var localVideo = document.createElement('video');
  7832. localVideo.id = 'localVideo_' +
  7833. APP.RTC.getStreamID(stream.getOriginalStream());
  7834. if (!RTCBrowserType.isIExplorer()) {
  7835. localVideo.autoplay = true;
  7836. localVideo.volume = 0; // is it required if audio is separated ?
  7837. }
  7838. localVideo.oncontextmenu = function () { return false; };
  7839. var localVideoContainer = document.getElementById('localVideoWrapper');
  7840. // Put the new video always in front
  7841. UIUtil.prependChild(localVideoContainer, localVideo);
  7842. var localVideoSelector = $('#' + localVideo.id);
  7843. // Add click handler to both video and video wrapper elements in case
  7844. // there's no video.
  7845. // onclick has to be used with Temasys plugin
  7846. localVideo.onclick = localVideoClick;
  7847. if (this.flipX) {
  7848. localVideoSelector.addClass("flipVideoX");
  7849. }
  7850. // Attach WebRTC stream
  7851. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7852. // Add stream ended handler
  7853. stream.getOriginalStream().onended = function () {
  7854. // We have to re-select after attach when Temasys plugin is used,
  7855. // because <video> element is replaced with <object>
  7856. localVideo = $('#' + localVideo.id)[0];
  7857. localVideoContainer.removeChild(localVideo);
  7858. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7859. };
  7860. };
  7861. LocalVideo.prototype.joined = function (jid) {
  7862. this.peerJid = jid;
  7863. };
  7864. LocalVideo.prototype.getResourceJid = function () {
  7865. var myResource = APP.xmpp.myResource();
  7866. if (!myResource) {
  7867. console.error("Requested local resource before we're in the MUC");
  7868. }
  7869. return myResource;
  7870. };
  7871. module.exports = LocalVideo;
  7872. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  7873. /* global $, APP, require, Strophe, interfaceConfig */
  7874. var ConnectionIndicator = require("./ConnectionIndicator");
  7875. var SmallVideo = require("./SmallVideo");
  7876. var AudioLevels = require("../audio_levels/AudioLevels");
  7877. var LargeVideo = require("./LargeVideo");
  7878. var Avatar = require("../avatar/Avatar");
  7879. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7880. var UIUtils = require("../util/UIUtil");
  7881. function RemoteVideo(peerJid, VideoLayout) {
  7882. this.peerJid = peerJid;
  7883. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  7884. this.videoSpanId = 'participant_' + this.resourceJid;
  7885. this.VideoLayout = VideoLayout;
  7886. this.addRemoteVideoContainer();
  7887. this.connectionIndicator = new ConnectionIndicator(
  7888. this, this.peerJid);
  7889. this.setDisplayName();
  7890. var nickfield = document.createElement('span');
  7891. nickfield.className = "nick";
  7892. nickfield.appendChild(document.createTextNode(this.resourceJid));
  7893. this.container.appendChild(nickfield);
  7894. this.flipX = false;
  7895. this.isLocal = false;
  7896. }
  7897. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  7898. RemoteVideo.prototype.constructor = RemoteVideo;
  7899. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  7900. this.container = RemoteVideo.createContainer(this.videoSpanId);
  7901. if (APP.xmpp.isModerator())
  7902. this.addRemoteVideoMenu();
  7903. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  7904. return this.container;
  7905. };
  7906. /**
  7907. * Adds the remote video menu element for the given <tt>jid</tt> in the
  7908. * given <tt>parentElement</tt>.
  7909. *
  7910. * @param jid the jid indicating the video for which we're adding a menu.
  7911. * @param parentElement the parent element where this menu will be added
  7912. */
  7913. if (!interfaceConfig.filmStripOnly) {
  7914. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  7915. var spanElement = document.createElement('span');
  7916. spanElement.className = 'remotevideomenu';
  7917. this.container.appendChild(spanElement);
  7918. var menuElement = document.createElement('i');
  7919. menuElement.className = 'fa fa-angle-down';
  7920. menuElement.title = 'Remote user controls';
  7921. spanElement.appendChild(menuElement);
  7922. var popupmenuElement = document.createElement('ul');
  7923. popupmenuElement.className = 'popupmenu';
  7924. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  7925. spanElement.appendChild(popupmenuElement);
  7926. var muteMenuItem = document.createElement('li');
  7927. var muteLinkItem = document.createElement('a');
  7928. var mutedIndicator = "<i style='float:left;' " +
  7929. "class='icon-mic-disabled'></i>";
  7930. if (!this.isMuted) {
  7931. muteLinkItem.innerHTML = mutedIndicator +
  7932. " <div style='width: 90px;margin-left: 20px;' " +
  7933. "data-i18n='videothumbnail.domute'></div>";
  7934. muteLinkItem.className = 'mutelink';
  7935. }
  7936. else {
  7937. muteLinkItem.innerHTML = mutedIndicator +
  7938. " <div style='width: 90px;margin-left: 20px;' " +
  7939. "data-i18n='videothumbnail.muted'></div>";
  7940. muteLinkItem.className = 'mutelink disabled';
  7941. }
  7942. var self = this;
  7943. muteLinkItem.onclick = function(){
  7944. if ($(this).attr('disabled') != undefined) {
  7945. event.preventDefault();
  7946. }
  7947. var isMute = self.isMuted == true;
  7948. APP.xmpp.setMute(self.peerJid, !isMute);
  7949. popupmenuElement.setAttribute('style', 'display:none;');
  7950. if (isMute) {
  7951. this.innerHTML = mutedIndicator +
  7952. " <div style='width: 90px;margin-left: 20px;' " +
  7953. "data-i18n='videothumbnail.muted'></div>";
  7954. this.className = 'mutelink disabled';
  7955. }
  7956. else {
  7957. this.innerHTML = mutedIndicator +
  7958. " <div style='width: 90px;margin-left: 20px;' " +
  7959. "data-i18n='videothumbnail.domute'></div>";
  7960. this.className = 'mutelink';
  7961. }
  7962. };
  7963. muteMenuItem.appendChild(muteLinkItem);
  7964. popupmenuElement.appendChild(muteMenuItem);
  7965. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  7966. var ejectMenuItem = document.createElement('li');
  7967. var ejectLinkItem = document.createElement('a');
  7968. var ejectText = "<div style='width: 90px;margin-left: 20px;' " +
  7969. "data-i18n='videothumbnail.kick'>&nbsp;</div>";
  7970. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  7971. ejectLinkItem.onclick = function(){
  7972. APP.xmpp.eject(self.peerJid);
  7973. popupmenuElement.setAttribute('style', 'display:none;');
  7974. };
  7975. ejectMenuItem.appendChild(ejectLinkItem);
  7976. popupmenuElement.appendChild(ejectMenuItem);
  7977. var paddingSpan = document.createElement('span');
  7978. paddingSpan.className = 'popupmenuPadding';
  7979. popupmenuElement.appendChild(paddingSpan);
  7980. APP.translation.translateElement(
  7981. $("#" + popupmenuElement.id + " > li > a > div"));
  7982. };
  7983. } else {
  7984. RemoteVideo.prototype.addRemoteVideoMenu = function() {}
  7985. }
  7986. /**
  7987. * Removes the remote stream element corresponding to the given stream and
  7988. * parent container.
  7989. *
  7990. * @param stream the stream
  7991. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  7992. */
  7993. RemoteVideo.prototype.removeRemoteStreamElement =
  7994. function (stream, isVideo, id) {
  7995. if (!this.container)
  7996. return false;
  7997. var select = null;
  7998. if (isVideo) {
  7999. select = $('#' + id);
  8000. }
  8001. else
  8002. select = $('#' + this.videoSpanId + '>audio');
  8003. select.remove();
  8004. console.info((isVideo ? "Video" : "Audio") +
  8005. " removed " + this.getResourceJid(), select);
  8006. if (isVideo)
  8007. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8008. };
  8009. /**
  8010. * Removes RemoteVideo from the page.
  8011. */
  8012. RemoteVideo.prototype.remove = function () {
  8013. console.log("Remove thumbnail", this.peerJid);
  8014. this.removeConnectionIndicator();
  8015. // Remove whole container
  8016. if (this.container.parentNode)
  8017. this.container.parentNode.removeChild(this.container);
  8018. };
  8019. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8020. var isVideo = stream.getVideoTracks().length > 0;
  8021. if (!isVideo || stream.id === 'mixedmslabel') {
  8022. return;
  8023. }
  8024. var self = this;
  8025. var resourceJid = this.getResourceJid();
  8026. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8027. // when video playback starts
  8028. var onPlayingHandler = function () {
  8029. // FIXME: why do i have to do this for FF?
  8030. if (RTCBrowserType.isFirefox()) {
  8031. APP.RTC.attachMediaStream(sel, stream);
  8032. }
  8033. if (RTCBrowserType.isTemasysPluginUsed()) {
  8034. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8035. }
  8036. self.VideoLayout.videoactive(sel, resourceJid);
  8037. sel[0].onplaying = null;
  8038. if (RTCBrowserType.isTemasysPluginUsed()) {
  8039. // 'currentTime' is used to check if the video has started
  8040. // and the value is not set by the plugin, so we do it
  8041. sel[0].currentTime = 1;
  8042. }
  8043. };
  8044. sel[0].onplaying = onPlayingHandler;
  8045. };
  8046. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8047. if (!this.container)
  8048. return;
  8049. var self = this;
  8050. var isVideo = stream.getVideoTracks().length > 0;
  8051. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8052. var newElementId = streamElement.id;
  8053. // Put new stream element always in front
  8054. UIUtils.prependChild(this.container, streamElement);
  8055. var sel = $('#' + newElementId);
  8056. sel.hide();
  8057. // If the container is currently visible we attach the stream.
  8058. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8059. this.waitForPlayback(sel, stream);
  8060. APP.RTC.attachMediaStream(sel, stream);
  8061. }
  8062. stream.onended = function () {
  8063. console.log('stream ended', this);
  8064. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8065. };
  8066. // Name of video element name is different for IE/Safari
  8067. var videoElem = APP.RTC.getVideoElementName();
  8068. // Add click handler.
  8069. var onClickHandler = function (event) {
  8070. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8071. // On IE we need to populate this handler on video <object>
  8072. // and it does not give event instance as an argument,
  8073. // so we check here for methods.
  8074. if (event.stopPropagation && event.preventDefault) {
  8075. event.stopPropagation();
  8076. event.preventDefault();
  8077. }
  8078. return false;
  8079. };
  8080. this.container.onclick = onClickHandler;
  8081. // reselect
  8082. if (RTCBrowserType.isTemasysPluginUsed())
  8083. sel = $('#' + newElementId);
  8084. sel[0].onclick = onClickHandler;
  8085. //FIXME
  8086. // Add hover handler
  8087. $(this.container).hover(
  8088. function() {
  8089. self.showDisplayName(true);
  8090. },
  8091. function() {
  8092. // If the video has been "pinned" by the user we want to
  8093. // keep the display name on place.
  8094. if (!LargeVideo.isLargeVideoVisible() ||
  8095. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8096. self.showDisplayName(false);
  8097. }
  8098. );
  8099. },
  8100. /**
  8101. * Show/hide peer container for the given resourceJid.
  8102. */
  8103. RemoteVideo.prototype.showPeerContainer = function (state) {
  8104. if (!this.container)
  8105. return;
  8106. var isHide = state === 'hide';
  8107. var resizeThumbnails = false;
  8108. if (!isHide) {
  8109. if (!$(this.container).is(':visible')) {
  8110. resizeThumbnails = true;
  8111. $(this.container).show();
  8112. }
  8113. this.showAvatar(state !== 'show');
  8114. }
  8115. else if ($(this.container).is(':visible') && isHide)
  8116. {
  8117. resizeThumbnails = true;
  8118. $(this.container).hide();
  8119. if(this.connectionIndicator)
  8120. this.connectionIndicator.hide();
  8121. }
  8122. if (resizeThumbnails) {
  8123. this.VideoLayout.resizeThumbnails();
  8124. }
  8125. // We want to be able to pin a participant from the contact list, even
  8126. // if he's not in the lastN set!
  8127. // ContactList.setClickable(resourceJid, !isHide);
  8128. };
  8129. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8130. if (this.connectionIndicator)
  8131. this.connectionIndicator.remove();
  8132. };
  8133. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8134. if (this.connectionIndicator)
  8135. this.connectionIndicator.hide();
  8136. };
  8137. /**
  8138. * Updates the remote video menu.
  8139. *
  8140. * @param jid the jid indicating the video for which we're adding a menu.
  8141. * @param isMuted indicates the current mute state
  8142. */
  8143. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8144. var muteMenuItem
  8145. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8146. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8147. if (muteMenuItem.length) {
  8148. var muteLink = muteMenuItem.get(0);
  8149. if (isMuted === 'true') {
  8150. muteLink.innerHTML = mutedIndicator + ' Muted';
  8151. muteLink.className = 'mutelink disabled';
  8152. }
  8153. else {
  8154. muteLink.innerHTML = mutedIndicator + ' Mute';
  8155. muteLink.className = 'mutelink';
  8156. }
  8157. }
  8158. };
  8159. /**
  8160. * Sets the display name for the given video span id.
  8161. */
  8162. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8163. if (!this.container) {
  8164. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8165. " does not exist");
  8166. return;
  8167. }
  8168. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8169. // If we already have a display name for this video.
  8170. if (nameSpan.length > 0) {
  8171. if (displayName && displayName.length > 0) {
  8172. $('#' + this.videoSpanId + '_name').html(displayName);
  8173. }
  8174. else if (key && key.length > 0) {
  8175. var nameHtml = APP.translation.generateTranslationHTML(key);
  8176. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8177. }
  8178. else
  8179. $('#' + this.videoSpanId + '_name').text(
  8180. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8181. } else {
  8182. nameSpan = document.createElement('span');
  8183. nameSpan.className = 'displayname';
  8184. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8185. if (displayName && displayName.length > 0) {
  8186. nameSpan.innerText = displayName;
  8187. }
  8188. else
  8189. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8190. nameSpan.id = this.videoSpanId + '_name';
  8191. }
  8192. };
  8193. /**
  8194. * Removes remote video menu element from video element identified by
  8195. * given <tt>videoElementId</tt>.
  8196. *
  8197. * @param videoElementId the id of local or remote video element.
  8198. */
  8199. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8200. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8201. if (menuSpan.length) {
  8202. menuSpan.remove();
  8203. }
  8204. };
  8205. RemoteVideo.prototype.getResourceJid = function () {
  8206. if (!this.resourceJid) {
  8207. console.error("Undefined resource jid");
  8208. }
  8209. return this.resourceJid;
  8210. };
  8211. RemoteVideo.createContainer = function (spanId) {
  8212. var container = document.createElement('span');
  8213. container.id = spanId;
  8214. container.className = 'videocontainer';
  8215. var remotes = document.getElementById('remoteVideos');
  8216. return remotes.appendChild(container);
  8217. };
  8218. module.exports = RemoteVideo;
  8219. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8220. /* global $, APP, require */
  8221. var Avatar = require("../avatar/Avatar");
  8222. var UIUtil = require("../util/UIUtil");
  8223. var LargeVideo = require("./LargeVideo");
  8224. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8225. function SmallVideo() {
  8226. this.isMuted = false;
  8227. this.hasAvatar = false;
  8228. }
  8229. function setVisibility(selector, show) {
  8230. if (selector && selector.length > 0) {
  8231. selector.css("visibility", show ? "visible" : "hidden");
  8232. }
  8233. }
  8234. SmallVideo.prototype.showDisplayName = function(isShow) {
  8235. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8236. if (isShow) {
  8237. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8238. nameSpan.setAttribute("style", "display:inline-block;");
  8239. }
  8240. else {
  8241. if (nameSpan)
  8242. nameSpan.setAttribute("style", "display:none;");
  8243. }
  8244. };
  8245. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8246. if(!this.container)
  8247. return;
  8248. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8249. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8250. noMic.remove();
  8251. noVideo.remove();
  8252. if (!devices.audio) {
  8253. this.container.appendChild(
  8254. document.createElement("div")).setAttribute("class", "noMic");
  8255. }
  8256. if (!devices.video) {
  8257. this.container.appendChild(
  8258. document.createElement("div")).setAttribute("class", "noVideo");
  8259. }
  8260. if (!devices.audio && !devices.video) {
  8261. noMic.css("background-position", "75%");
  8262. noVideo.css("background-position", "25%");
  8263. noVideo.css("background-color", "transparent");
  8264. }
  8265. };
  8266. /**
  8267. * Sets the type of the video displayed by this instance.
  8268. * @param videoType 'camera' or 'screen'
  8269. */
  8270. SmallVideo.prototype.setVideoType = function (videoType) {
  8271. this.videoType = videoType;
  8272. };
  8273. /**
  8274. * Returns the type of the video displayed by this instance.
  8275. * @returns {String} 'camera', 'screen' or undefined.
  8276. */
  8277. SmallVideo.prototype.getVideoType = function () {
  8278. return this.videoType;
  8279. };
  8280. /**
  8281. * Shows the presence status message for the given video.
  8282. */
  8283. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8284. if (!this.container) {
  8285. // No container
  8286. return;
  8287. }
  8288. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8289. if (!statusSpan.length) {
  8290. //Add status span
  8291. statusSpan = document.createElement('span');
  8292. statusSpan.className = 'status';
  8293. statusSpan.id = this.videoSpanId + '_status';
  8294. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8295. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8296. }
  8297. // Display status
  8298. if (statusMsg && statusMsg.length) {
  8299. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8300. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8301. }
  8302. else {
  8303. // Hide
  8304. statusSpan.get(0).setAttribute("style", "display:none;");
  8305. }
  8306. };
  8307. /**
  8308. * Creates an audio or video stream element.
  8309. */
  8310. SmallVideo.createStreamElement = function (sid, stream) {
  8311. var isVideo = stream.getVideoTracks().length > 0;
  8312. var element = isVideo ? document.createElement('video')
  8313. : document.createElement('audio');
  8314. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8315. APP.RTC.getStreamID(stream);
  8316. element.id = id;
  8317. if (!RTCBrowserType.isIExplorer()) {
  8318. element.autoplay = true;
  8319. }
  8320. element.oncontextmenu = function () { return false; };
  8321. return element;
  8322. };
  8323. /**
  8324. * Updates the data for the indicator
  8325. * @param id the id of the indicator
  8326. * @param percent the percent for connection quality
  8327. * @param object the data
  8328. */
  8329. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8330. if(this.connectionIndicator)
  8331. this.connectionIndicator.updateConnectionQuality(percent, object);
  8332. };
  8333. SmallVideo.prototype.hideIndicator = function () {
  8334. if(this.connectionIndicator)
  8335. this.connectionIndicator.hideIndicator();
  8336. };
  8337. /**
  8338. * Shows audio muted indicator over small videos.
  8339. * @param {string} isMuted
  8340. */
  8341. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8342. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8343. if (!isMuted) {
  8344. if (audioMutedSpan.length > 0) {
  8345. audioMutedSpan.popover('hide');
  8346. audioMutedSpan.remove();
  8347. }
  8348. }
  8349. else {
  8350. if(audioMutedSpan.length == 0 ) {
  8351. audioMutedSpan = document.createElement('span');
  8352. audioMutedSpan.className = 'audioMuted';
  8353. UIUtil.setTooltip(audioMutedSpan,
  8354. "videothumbnail.mute",
  8355. "top");
  8356. this.container.appendChild(audioMutedSpan);
  8357. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8358. var mutedIndicator = document.createElement('i');
  8359. mutedIndicator.className = 'icon-mic-disabled';
  8360. audioMutedSpan.appendChild(mutedIndicator);
  8361. }
  8362. this.updateIconPositions();
  8363. }
  8364. this.isMuted = isMuted;
  8365. };
  8366. /**
  8367. * Shows video muted indicator over small videos.
  8368. */
  8369. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8370. this.showAvatar(isMuted);
  8371. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8372. if (isMuted === false) {
  8373. if (videoMutedSpan.length > 0) {
  8374. videoMutedSpan.remove();
  8375. }
  8376. }
  8377. else {
  8378. if(videoMutedSpan.length == 0) {
  8379. videoMutedSpan = document.createElement('span');
  8380. videoMutedSpan.className = 'videoMuted';
  8381. this.container.appendChild(videoMutedSpan);
  8382. var mutedIndicator = document.createElement('i');
  8383. mutedIndicator.className = 'icon-camera-disabled';
  8384. UIUtil.setTooltip(mutedIndicator,
  8385. "videothumbnail.videomute",
  8386. "top");
  8387. videoMutedSpan.appendChild(mutedIndicator);
  8388. //translate texts for muted indicator
  8389. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8390. }
  8391. this.updateIconPositions();
  8392. }
  8393. };
  8394. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8395. var resourceJid = this.getResourceJid();
  8396. var displayName = resourceJid;
  8397. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8398. if (nameSpan.length > 0)
  8399. displayName = nameSpan.html();
  8400. console.log("UI enable dominant speaker",
  8401. displayName,
  8402. resourceJid,
  8403. isEnable);
  8404. if (!this.container) {
  8405. return;
  8406. }
  8407. if (isEnable) {
  8408. this.showDisplayName(LargeVideo.getState() === "video");
  8409. if (!this.container.classList.contains("dominantspeaker"))
  8410. this.container.classList.add("dominantspeaker");
  8411. }
  8412. else {
  8413. this.showDisplayName(false);
  8414. if (this.container.classList.contains("dominantspeaker"))
  8415. this.container.classList.remove("dominantspeaker");
  8416. }
  8417. this.showAvatar();
  8418. };
  8419. SmallVideo.prototype.updateIconPositions = function () {
  8420. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8421. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8422. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8423. if(connectionIndicator.length > 0 &&
  8424. connectionIndicator[0].style.display != "none") {
  8425. audioMutedSpan.css({right: "23px"});
  8426. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8427. } else {
  8428. audioMutedSpan.css({right: "0px"});
  8429. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8430. }
  8431. };
  8432. /**
  8433. * Creates the element indicating the moderator(owner) of the conference.
  8434. *
  8435. * @param parentElement the parent element where the owner indicator will
  8436. * be added
  8437. */
  8438. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8439. // Show moderator indicator
  8440. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8441. if (!indicatorSpan || indicatorSpan.length === 0) {
  8442. indicatorSpan = document.createElement('span');
  8443. indicatorSpan.className = 'focusindicator';
  8444. this.container.appendChild(indicatorSpan);
  8445. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8446. }
  8447. if (indicatorSpan.children().length !== 0)
  8448. return;
  8449. var moderatorIndicator = document.createElement('i');
  8450. moderatorIndicator.className = 'fa fa-star';
  8451. indicatorSpan[0].appendChild(moderatorIndicator);
  8452. UIUtil.setTooltip(indicatorSpan[0],
  8453. "videothumbnail.moderator",
  8454. "top");
  8455. //translates text in focus indicators
  8456. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8457. };
  8458. SmallVideo.prototype.getSrc = function () {
  8459. var videoElement = APP.RTC.getVideoElementName();
  8460. return APP.RTC.getVideoSrc(
  8461. $('#' + this.videoSpanId).find(videoElement).get(0));
  8462. };
  8463. SmallVideo.prototype.focus = function(isFocused) {
  8464. if(!isFocused) {
  8465. this.container.classList.remove("videoContainerFocused");
  8466. } else {
  8467. this.container.classList.add("videoContainerFocused");
  8468. }
  8469. };
  8470. SmallVideo.prototype.hasVideo = function () {
  8471. return $("#" + this.videoSpanId).find(
  8472. APP.RTC.getVideoElementName()).length !== 0;
  8473. };
  8474. /**
  8475. * Hides or shows the user's avatar
  8476. * @param show whether we should show the avatar or not
  8477. * video because there is no dominant speaker and no focused speaker
  8478. */
  8479. SmallVideo.prototype.showAvatar = function (show) {
  8480. if (!this.hasAvatar) {
  8481. if (this.peerJid) {
  8482. // Init avatar
  8483. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8484. } else {
  8485. console.error("Unable to init avatar - no peerjid", this);
  8486. return;
  8487. }
  8488. }
  8489. var resourceJid = this.getResourceJid();
  8490. var videoElem = APP.RTC.getVideoElementName();
  8491. var video = $('#' + this.videoSpanId).find(videoElem);
  8492. var avatar = $('#avatar_' + resourceJid);
  8493. if (show === undefined || show === null) {
  8494. if (!this.isLocal &&
  8495. !this.VideoLayout.isInLastN(resourceJid)) {
  8496. show = true;
  8497. } else {
  8498. // We want to show the avatar when the video is muted or not exists
  8499. // that is when 'true' or 'null' is returned
  8500. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8501. }
  8502. }
  8503. if (LargeVideo.showAvatar(resourceJid, show)) {
  8504. setVisibility(avatar, false);
  8505. setVisibility(video, false);
  8506. } else {
  8507. if (video && video.length > 0) {
  8508. setVisibility(video, !show);
  8509. }
  8510. setVisibility(avatar, show);
  8511. }
  8512. };
  8513. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8514. var thumbnail = $('#' + this.videoSpanId);
  8515. var resourceJid = this.getResourceJid();
  8516. var avatar = $('#avatar_' + resourceJid);
  8517. this.hasAvatar = true;
  8518. // set the avatar in the thumbnail
  8519. if (avatar && avatar.length > 0) {
  8520. avatar[0].src = thumbUrl;
  8521. } else {
  8522. if (thumbnail && thumbnail.length > 0) {
  8523. avatar = document.createElement('img');
  8524. avatar.id = 'avatar_' + resourceJid;
  8525. avatar.className = 'userAvatar';
  8526. avatar.src = thumbUrl;
  8527. thumbnail.append(avatar);
  8528. }
  8529. }
  8530. };
  8531. module.exports = SmallVideo;
  8532. },{"../../RTC/RTCBrowserType":8,"../avatar/Avatar":16,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8533. /* global config, APP, $, Strophe, require, interfaceConfig */
  8534. var AudioLevels = require("../audio_levels/AudioLevels");
  8535. var ContactList = require("../side_pannels/contactlist/ContactList");
  8536. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8537. var UIEvents = require("../../../service/UI/UIEvents");
  8538. var UIUtil = require("../util/UIUtil");
  8539. var RTC = require("../../RTC/RTC");
  8540. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8541. var RemoteVideo = require("./RemoteVideo");
  8542. var LargeVideo = require("./LargeVideo");
  8543. var LocalVideo = require("./LocalVideo");
  8544. var remoteVideos = {};
  8545. var remoteVideoTypes = {};
  8546. var localVideoThumbnail = null;
  8547. var currentDominantSpeaker = null;
  8548. var lastNCount = config.channelLastN;
  8549. var localLastNCount = config.channelLastN;
  8550. var localLastNSet = [];
  8551. var lastNEndpointsCache = [];
  8552. var lastNPickupJid = null;
  8553. var eventEmitter = null;
  8554. /**
  8555. * Currently focused video jid
  8556. * @type {String}
  8557. */
  8558. var focusedVideoResourceJid = null;
  8559. var VideoLayout = (function (my) {
  8560. my.init = function (emitter) {
  8561. eventEmitter = emitter;
  8562. localVideoThumbnail = new LocalVideo(VideoLayout);
  8563. if (interfaceConfig.filmStripOnly) {
  8564. LargeVideo.disable();
  8565. } else {
  8566. LargeVideo.init(VideoLayout, emitter);
  8567. }
  8568. VideoLayout.resizeLargeVideoContainer();
  8569. };
  8570. my.isInLastN = function(resource) {
  8571. return lastNCount < 0 || // lastN is disabled
  8572. // lastNEndpoints cache not built yet
  8573. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  8574. (lastNEndpointsCache &&
  8575. lastNEndpointsCache.indexOf(resource) !== -1);
  8576. };
  8577. my.changeLocalStream = function (stream, isMuted) {
  8578. VideoLayout.changeLocalVideo(stream, isMuted);
  8579. };
  8580. my.changeLocalAudio = function(stream, isMuted) {
  8581. if (isMuted)
  8582. APP.UI.setAudioMuted(true, true);
  8583. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8584. var localAudio = document.getElementById('localAudio');
  8585. // Writing volume not allowed in IE
  8586. if (!RTCBrowserType.isIExplorer()) {
  8587. localAudio.autoplay = true;
  8588. localAudio.volume = 0;
  8589. }
  8590. };
  8591. my.changeLocalVideo = function(stream, isMuted) {
  8592. // Set default display name.
  8593. localVideoThumbnail.setDisplayName();
  8594. localVideoThumbnail.createConnectionIndicator();
  8595. this.onVideoTypeChanged(APP.xmpp.myResource(), stream.videoType);
  8596. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8597. localVideoThumbnail.changeVideo(stream, isMuted);
  8598. /* force update if we're currently being displayed */
  8599. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8600. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8601. }
  8602. };
  8603. my.mucJoined = function () {
  8604. var myResourceJid = APP.xmpp.myResource();
  8605. localVideoThumbnail.joined(APP.xmpp.myJid());
  8606. if (!LargeVideo.getResourceJid())
  8607. LargeVideo.updateLargeVideo(myResourceJid, true);
  8608. };
  8609. /**
  8610. * Adds or removes icons for not available camera and microphone.
  8611. * @param resourceJid the jid of user
  8612. * @param devices available devices
  8613. */
  8614. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8615. if(!devices)
  8616. return;
  8617. if(!resourceJid) {
  8618. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8619. } else {
  8620. if(remoteVideos[resourceJid])
  8621. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8622. }
  8623. };
  8624. /**
  8625. * Checks if removed video is currently displayed and tries to display
  8626. * another one instead.
  8627. * @param removedVideoSrc src stream identifier of the video.
  8628. */
  8629. my.updateRemovedVideo = function(resourceJid) {
  8630. if (resourceJid === LargeVideo.getResourceJid()) {
  8631. var newResourceJid;
  8632. // We'll show user's avatar if he is the dominant speaker or if
  8633. // his video thumbnail is pinned
  8634. if (remoteVideos[resourceJid] &&
  8635. resourceJid === focusedVideoResourceJid ||
  8636. resourceJid === currentDominantSpeaker) {
  8637. newResourceJid = resourceJid;
  8638. } else {
  8639. // Otherwise select last visible video
  8640. newResourceJid = this.electLastVisibleVideo();
  8641. }
  8642. LargeVideo.updateLargeVideo(newResourceJid);
  8643. }
  8644. };
  8645. my.electLastVisibleVideo = function() {
  8646. // pick the last visible video in the row
  8647. // if nobody else is left, this picks the local video
  8648. var jid;
  8649. var videoElem = RTC.getVideoElementName();
  8650. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  8651. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8652. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8653. } else {
  8654. console.info("Last visible video no longer exists");
  8655. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  8656. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8657. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8658. } else {
  8659. // Try local video
  8660. console.info("Fallback to local video...");
  8661. jid = APP.xmpp.myResource();
  8662. }
  8663. }
  8664. console.info("electLastVisibleVideo: " + jid);
  8665. return jid;
  8666. };
  8667. my.onRemoteStreamAdded = function (stream) {
  8668. if (stream.peerjid) {
  8669. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8670. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8671. remoteVideos[resourceJid].addRemoteStreamElement(
  8672. stream.sid,
  8673. stream.getOriginalStream(),
  8674. stream.ssrc);
  8675. }
  8676. };
  8677. my.getLargeVideoResource = function () {
  8678. return LargeVideo.getResourceJid();
  8679. };
  8680. /**
  8681. * Called when large video update is finished
  8682. * @param currentSmallVideo small video currently displayed on large video
  8683. */
  8684. my.largeVideoUpdated = function (currentSmallVideo) {
  8685. // Makes sure that dominant speaker UI
  8686. // is enabled only on current small video
  8687. localVideoThumbnail.enableDominantSpeaker(
  8688. localVideoThumbnail === currentSmallVideo);
  8689. Object.keys(remoteVideos).forEach(
  8690. function (resourceJid) {
  8691. var remoteVideo = remoteVideos[resourceJid];
  8692. if (remoteVideo) {
  8693. remoteVideo.enableDominantSpeaker(
  8694. remoteVideo === currentSmallVideo);
  8695. }
  8696. }
  8697. );
  8698. };
  8699. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8700. resourceJid) {
  8701. if(focusedVideoResourceJid) {
  8702. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8703. if (oldSmallVideo && !interfaceConfig.filmStripOnly)
  8704. oldSmallVideo.focus(false);
  8705. }
  8706. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8707. // Unlock current focused.
  8708. if (focusedVideoResourceJid === resourceJid)
  8709. {
  8710. focusedVideoResourceJid = null;
  8711. // Enable the currently set dominant speaker.
  8712. if (currentDominantSpeaker) {
  8713. if(smallVideo && smallVideo.hasVideo()) {
  8714. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8715. }
  8716. }
  8717. if (!noPinnedEndpointChangedEvent) {
  8718. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8719. }
  8720. return;
  8721. }
  8722. // Lock new video
  8723. focusedVideoResourceJid = resourceJid;
  8724. // Update focused/pinned interface.
  8725. if (resourceJid) {
  8726. if (smallVideo && !interfaceConfig.filmStripOnly)
  8727. smallVideo.focus(true);
  8728. if (!noPinnedEndpointChangedEvent) {
  8729. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8730. }
  8731. }
  8732. LargeVideo.setState("video");
  8733. LargeVideo.updateLargeVideo(resourceJid);
  8734. // Writing volume not allowed in IE
  8735. if (!RTCBrowserType.isIExplorer()) {
  8736. $('audio').each(function (idx, el) {
  8737. el.volume = 0;
  8738. el.volume = 1;
  8739. });
  8740. }
  8741. };
  8742. /**
  8743. * Checks if container for participant identified by given peerJid exists
  8744. * in the document and creates it eventually.
  8745. *
  8746. * @param peerJid peer Jid to check.
  8747. *
  8748. * @return Returns <tt>true</tt> if the peer container exists,
  8749. * <tt>false</tt> - otherwise
  8750. */
  8751. my.ensurePeerContainerExists = function(peerJid) {
  8752. ContactList.ensureAddContact(peerJid);
  8753. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8754. if (!remoteVideos[resourceJid]) {
  8755. var remoteVideo = new RemoteVideo(peerJid, VideoLayout);
  8756. remoteVideos[resourceJid] = remoteVideo;
  8757. var videoType = remoteVideoTypes[resourceJid];
  8758. if (videoType) {
  8759. remoteVideo.setVideoType(videoType);
  8760. }
  8761. // In case this is not currently in the last n we don't show it.
  8762. if (localLastNCount &&
  8763. localLastNCount > 0 &&
  8764. $('#remoteVideos>span').length >= localLastNCount + 2) {
  8765. remoteVideo.showPeerContainer('hide');
  8766. }
  8767. else
  8768. VideoLayout.resizeThumbnails();
  8769. }
  8770. };
  8771. my.inputDisplayNameHandler = function (name) {
  8772. localVideoThumbnail.inputDisplayNameHandler(name);
  8773. };
  8774. my.videoactive = function (videoelem, resourceJid) {
  8775. console.info(resourceJid + " video is now active");
  8776. videoelem.show();
  8777. VideoLayout.resizeThumbnails();
  8778. // Update the large video to the last added video only if there's no
  8779. // current dominant, focused speaker or prezi playing or update it to
  8780. // the current dominant speaker.
  8781. if ((!focusedVideoResourceJid &&
  8782. !currentDominantSpeaker &&
  8783. !require("../prezi/Prezi").isPresentationVisible()) ||
  8784. focusedVideoResourceJid === resourceJid ||
  8785. (resourceJid &&
  8786. currentDominantSpeaker === resourceJid)) {
  8787. LargeVideo.updateLargeVideo(resourceJid, true);
  8788. }
  8789. };
  8790. /**
  8791. * Shows the presence status message for the given video.
  8792. */
  8793. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8794. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8795. };
  8796. /**
  8797. * Shows a visual indicator for the moderator of the conference.
  8798. */
  8799. my.showModeratorIndicator = function () {
  8800. var isModerator = APP.xmpp.isModerator();
  8801. if (isModerator) {
  8802. localVideoThumbnail.createModeratorIndicatorElement();
  8803. }
  8804. var members = APP.xmpp.getMembers();
  8805. Object.keys(members).forEach(function (jid) {
  8806. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8807. // Skip server side focus
  8808. return;
  8809. }
  8810. var resourceJid = Strophe.getResourceFromJid(jid);
  8811. var member = members[jid];
  8812. if (member.role === 'moderator') {
  8813. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8814. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8815. } else if (isModerator) {
  8816. // We are moderator, but user is not - add menu
  8817. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8818. remoteVideos[resourceJid].addRemoteVideoMenu();
  8819. }
  8820. }
  8821. });
  8822. };
  8823. /*
  8824. * Shows or hides the audio muted indicator over the local thumbnail video.
  8825. * @param {boolean} isMuted
  8826. */
  8827. my.showLocalAudioIndicator = function(isMuted) {
  8828. localVideoThumbnail.showAudioIndicator(isMuted);
  8829. };
  8830. /**
  8831. * Resizes the large video container.
  8832. */
  8833. my.resizeLargeVideoContainer = function () {
  8834. if(LargeVideo.isEnabled()) {
  8835. LargeVideo.resize();
  8836. } else {
  8837. VideoLayout.resizeVideoSpace();
  8838. }
  8839. VideoLayout.resizeThumbnails();
  8840. LargeVideo.position();
  8841. };
  8842. /**
  8843. * Resizes thumbnails.
  8844. */
  8845. my.resizeThumbnails = function(animate) {
  8846. var videoSpaceWidth = $('#remoteVideos').width();
  8847. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8848. var width = thumbnailSize[0];
  8849. var height = thumbnailSize[1];
  8850. $('.userAvatar').css('left', (width - height) / 2);
  8851. if(animate) {
  8852. $('#remoteVideos').animate({
  8853. height: height + 2 // adds 2 px because of small video 1px border
  8854. },
  8855. {
  8856. queue: false,
  8857. duration: 500
  8858. });
  8859. $('#remoteVideos>span').animate({
  8860. height: height,
  8861. width: width
  8862. },
  8863. {
  8864. queue: false,
  8865. duration: 500,
  8866. complete: function () {
  8867. $(document).trigger(
  8868. "remotevideo.resized",
  8869. [width,
  8870. height]);
  8871. }
  8872. });
  8873. } else {
  8874. // size videos so that while keeping AR and max height, we have a
  8875. // nice fit
  8876. $('#remoteVideos').height(height + 2);// adds 2 px because of small video 1px border
  8877. $('#remoteVideos>span').width(width);
  8878. $('#remoteVideos>span').height(height);
  8879. $(document).trigger("remotevideo.resized", [width, height]);
  8880. }
  8881. };
  8882. /**
  8883. * Calculates the thumbnail size.
  8884. *
  8885. * @param videoSpaceWidth the width of the video space
  8886. */
  8887. my.calculateThumbnailSize = function (videoSpaceWidth) {
  8888. // Calculate the available height, which is the inner window height minus
  8889. // 39px for the header minus 2px for the delimiter lines on the top and
  8890. // bottom of the large video, minus the 36px space inside the remoteVideos
  8891. // container used for highlighting shadow.
  8892. var availableHeight = 100;
  8893. var numvids = $('#remoteVideos>span:visible').length;
  8894. if (localLastNCount && localLastNCount > 0) {
  8895. numvids = Math.min(localLastNCount + 1, numvids);
  8896. }
  8897. // Remove the 3px borders arround videos and border around the remote
  8898. // videos area and the 4 pixels between the local video and the others
  8899. //TODO: Find out where the 4 pixels come from and remove them
  8900. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  8901. var availableWidth = availableWinWidth / numvids;
  8902. var aspectRatio = 16.0 / 9.0;
  8903. var maxHeight = Math.min(160, availableHeight);
  8904. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio, window.innerHeight - 18);
  8905. if (availableHeight < availableWidth / aspectRatio) {
  8906. availableWidth = Math.floor(availableHeight * aspectRatio);
  8907. }
  8908. return [availableWidth, availableHeight];
  8909. };
  8910. /**
  8911. * Returns the corresponding resource jid to the given peer container
  8912. * DOM element.
  8913. *
  8914. * @return the corresponding resource jid to the given peer container
  8915. * DOM element
  8916. */
  8917. my.getPeerContainerResourceJid = function (containerElement) {
  8918. var i = containerElement.id.indexOf('participant_');
  8919. if (i >= 0)
  8920. return containerElement.id.substring(i + 12);
  8921. };
  8922. my.getPeerVideoSel = function (peerResourceJid) {
  8923. return $('#participant_' + peerResourceJid +
  8924. '>' + APP.RTC.getVideoElementName());
  8925. };
  8926. /**
  8927. * On contact list item clicked.
  8928. */
  8929. $(ContactList).bind('contactclicked', function(event, jid) {
  8930. if (!jid) {
  8931. return;
  8932. }
  8933. if (jid === APP.xmpp.myJid()) {
  8934. $("#localVideoContainer").click();
  8935. return;
  8936. }
  8937. var resource = Strophe.getResourceFromJid(jid);
  8938. var videoSel = VideoLayout.getPeerVideoSel(resource);
  8939. if (videoSel.length > 0) {
  8940. var videoThumb = videoSel[0];
  8941. // It is not always the case that a videoThumb exists (if there is
  8942. // no actual video).
  8943. if (RTC.getVideoSrc(videoThumb)) {
  8944. // We have a video src, great! Let's update the large video
  8945. // now.
  8946. VideoLayout.handleVideoThumbClicked(
  8947. false,
  8948. Strophe.getResourceFromJid(jid));
  8949. } else {
  8950. // If we don't have a video src for jid, there's absolutely
  8951. // no point in calling handleVideoThumbClicked; Quite
  8952. // simply, it won't work because it needs an src to attach
  8953. // to the large video.
  8954. //
  8955. // Instead, we trigger the pinned endpoint changed event to
  8956. // let the bridge adjust its lastN set for myjid and store
  8957. // the pinned user in the lastNPickupJid variable to be
  8958. // picked up later by the lastN changed event handler.
  8959. lastNPickupJid = jid;
  8960. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  8961. Strophe.getResourceFromJid(jid));
  8962. }
  8963. }
  8964. });
  8965. /**
  8966. * On audio muted event.
  8967. */
  8968. my.onAudioMute = function (jid, isMuted) {
  8969. var resourceJid = Strophe.getResourceFromJid(jid);
  8970. if (resourceJid === APP.xmpp.myResource()) {
  8971. localVideoThumbnail.showAudioIndicator(isMuted);
  8972. } else {
  8973. VideoLayout.ensurePeerContainerExists(jid);
  8974. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  8975. if (APP.xmpp.isModerator()) {
  8976. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  8977. }
  8978. }
  8979. };
  8980. /**
  8981. * On video muted event.
  8982. */
  8983. my.onVideoMute = function (jid, value) {
  8984. if (jid !== APP.xmpp.myJid() &&
  8985. !APP.RTC.muteRemoteVideoStream(jid, value))
  8986. return;
  8987. if (jid === APP.xmpp.myJid()) {
  8988. localVideoThumbnail.showVideoIndicator(value);
  8989. } else {
  8990. var resource = Strophe.getResourceFromJid(jid);
  8991. VideoLayout.ensurePeerContainerExists(jid);
  8992. remoteVideos[resource].showVideoIndicator(value);
  8993. var el = VideoLayout.getPeerVideoSel(resource);
  8994. if (!value)
  8995. el.show();
  8996. else
  8997. el.hide();
  8998. }
  8999. };
  9000. /**
  9001. * Display name changed.
  9002. */
  9003. my.onDisplayNameChanged =
  9004. function (jid, displayName, status) {
  9005. if (jid === 'localVideoContainer' ||
  9006. jid === APP.xmpp.myJid()) {
  9007. localVideoThumbnail.setDisplayName(displayName);
  9008. } else {
  9009. VideoLayout.ensurePeerContainerExists(jid);
  9010. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9011. displayName,
  9012. status);
  9013. }
  9014. };
  9015. /**
  9016. * On dominant speaker changed event.
  9017. */
  9018. my.onDominantSpeakerChanged = function (resourceJid) {
  9019. // We ignore local user events.
  9020. if (resourceJid === APP.xmpp.myResource())
  9021. return;
  9022. var members = APP.xmpp.getMembers();
  9023. // Update the current dominant speaker.
  9024. if (resourceJid !== currentDominantSpeaker) {
  9025. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9026. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9027. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9028. !members[currentJID].displayName) && remoteVideos[resourceJid]) {
  9029. remoteVideos[resourceJid].setDisplayName(null);
  9030. }
  9031. if(resourceJid && (!members || !members[newJID] ||
  9032. !members[newJID].displayName) && remoteVideos[resourceJid]) {
  9033. remoteVideos[resourceJid].setDisplayName(null,
  9034. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9035. }
  9036. currentDominantSpeaker = resourceJid;
  9037. } else {
  9038. return;
  9039. }
  9040. // Obtain container for new dominant speaker.
  9041. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9042. // Local video will not have container found, but that's ok
  9043. // since we don't want to switch to local video.
  9044. if (!focusedVideoResourceJid && videoSel.length) {
  9045. // Update the large video if the video source is already available,
  9046. // otherwise wait for the "videoactive.jingle" event.
  9047. if (videoSel[0].currentTime > 0) {
  9048. LargeVideo.updateLargeVideo(resourceJid);
  9049. }
  9050. }
  9051. };
  9052. /**
  9053. * On last N change event.
  9054. *
  9055. * @param lastNEndpoints the list of last N endpoints
  9056. * @param endpointsEnteringLastN the list currently entering last N
  9057. * endpoints
  9058. */
  9059. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9060. endpointsEnteringLastN,
  9061. stream) {
  9062. if (lastNCount !== lastNEndpoints.length)
  9063. lastNCount = lastNEndpoints.length;
  9064. lastNEndpointsCache = lastNEndpoints;
  9065. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9066. //
  9067. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9068. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9069. // so E sees them. C is only in E's local LastN set.
  9070. //
  9071. // If F starts talking and LastN = 3, then E should see thumbnails for
  9072. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9073. // enters E's local LastN ejecting C.
  9074. // Increase the local LastN set size, if necessary.
  9075. if (lastNCount > localLastNCount) {
  9076. localLastNCount = lastNCount;
  9077. }
  9078. // Update the local LastN set preserving the order in which the
  9079. // endpoints appeared in the LastN/local LastN set.
  9080. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9081. for (var i = 0; i < localLastNSet.length; i++) {
  9082. if (nextLocalLastNSet.length >= localLastNCount) {
  9083. break;
  9084. }
  9085. var resourceJid = localLastNSet[i];
  9086. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9087. nextLocalLastNSet.push(resourceJid);
  9088. }
  9089. }
  9090. localLastNSet = nextLocalLastNSet;
  9091. var updateLargeVideo = false;
  9092. // Handle LastN/local LastN changes.
  9093. $('#remoteVideos>span').each(function( index, element ) {
  9094. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9095. var isReceived = true;
  9096. if (resourceJid &&
  9097. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9098. localLastNSet.indexOf(resourceJid) < 0) {
  9099. console.log("Remove from last N", resourceJid);
  9100. remoteVideos[resourceJid].showPeerContainer('hide');
  9101. isReceived = false;
  9102. } else if (resourceJid &&
  9103. $('#participant_' + resourceJid).is(':visible') &&
  9104. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9105. localLastNSet.indexOf(resourceJid) >= 0) {
  9106. remoteVideos[resourceJid].showPeerContainer('avatar');
  9107. isReceived = false;
  9108. }
  9109. if (!isReceived) {
  9110. // resourceJid has dropped out of the server side lastN set, so
  9111. // it is no longer being received. If resourceJid was being
  9112. // displayed in the large video we have to switch to another
  9113. // user.
  9114. if (!updateLargeVideo &&
  9115. resourceJid === LargeVideo.getResourceJid()) {
  9116. updateLargeVideo = true;
  9117. }
  9118. }
  9119. });
  9120. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9121. endpointsEnteringLastN = lastNEndpoints;
  9122. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9123. endpointsEnteringLastN.forEach(function (resourceJid) {
  9124. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9125. remoteVideos[resourceJid].showPeerContainer('show');
  9126. if (!isVisible) {
  9127. console.log("Add to last N", resourceJid);
  9128. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9129. var mediaStream =
  9130. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9131. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9132. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9133. if (lastNPickupJid == mediaStream.peerjid) {
  9134. // Clean up the lastN pickup jid.
  9135. lastNPickupJid = null;
  9136. // Don't fire the events again, they've already
  9137. // been fired in the contact list click handler.
  9138. VideoLayout.handleVideoThumbClicked(
  9139. false,
  9140. Strophe.getResourceFromJid(mediaStream.peerjid));
  9141. updateLargeVideo = false;
  9142. }
  9143. remoteVideos[resourceJid].
  9144. waitForPlayback(sel, mediaStream.stream);
  9145. }
  9146. });
  9147. }
  9148. // The endpoint that was being shown in the large video has dropped out
  9149. // of the lastN set and there was no lastN pickup jid. We need to update
  9150. // the large video now.
  9151. if (updateLargeVideo) {
  9152. var resource;
  9153. var myResource
  9154. = APP.xmpp.myResource();
  9155. // Find out which endpoint to show in the large video.
  9156. for (i = 0; i < lastNEndpoints.length; i++) {
  9157. resource = lastNEndpoints[i];
  9158. if (!resource || resource === myResource)
  9159. continue;
  9160. // videoSrcToSsrc needs to be update for this call to succeed.
  9161. LargeVideo.updateLargeVideo(resource);
  9162. break;
  9163. }
  9164. }
  9165. };
  9166. /**
  9167. * Updates local stats
  9168. * @param percent
  9169. * @param object
  9170. */
  9171. my.updateLocalConnectionStats = function (percent, object) {
  9172. var resolution = null;
  9173. if (object.resolution !== null) {
  9174. resolution = object.resolution;
  9175. object.resolution = resolution[APP.xmpp.myJid()];
  9176. delete resolution[APP.xmpp.myJid()];
  9177. }
  9178. localVideoThumbnail.updateStatsIndicator(percent, object);
  9179. for (var jid in resolution) {
  9180. if (resolution[jid] === null)
  9181. continue;
  9182. var resourceJid = Strophe.getResourceFromJid(jid);
  9183. if (remoteVideos[resourceJid] &&
  9184. remoteVideos[resourceJid].connectionIndicator) {
  9185. remoteVideos[resourceJid].connectionIndicator.
  9186. updateResolution(resolution[jid]);
  9187. }
  9188. }
  9189. };
  9190. /**
  9191. * Updates remote stats.
  9192. * @param jid the jid associated with the stats
  9193. * @param percent the connection quality percent
  9194. * @param object the stats data
  9195. */
  9196. my.updateConnectionStats = function (jid, percent, object) {
  9197. var resourceJid = Strophe.getResourceFromJid(jid);
  9198. if (remoteVideos[resourceJid])
  9199. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9200. };
  9201. /**
  9202. * Hides the connection indicator
  9203. * @param jid
  9204. */
  9205. my.hideConnectionIndicator = function (jid) {
  9206. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9207. };
  9208. /**
  9209. * Hides all the indicators
  9210. */
  9211. my.onStatsStop = function () {
  9212. for(var video in remoteVideos) {
  9213. remoteVideos[video].hideIndicator();
  9214. }
  9215. localVideoThumbnail.hideIndicator();
  9216. };
  9217. my.participantLeft = function (jid) {
  9218. // Unlock large video
  9219. var resourceJid = Strophe.getResourceFromJid(jid);
  9220. if (focusedVideoResourceJid === resourceJid) {
  9221. console.info("Focused video owner has left the conference");
  9222. focusedVideoResourceJid = null;
  9223. }
  9224. if (currentDominantSpeaker === resourceJid)
  9225. {
  9226. console.info("Dominant speaker has left the conference");
  9227. currentDominantSpeaker = null;
  9228. }
  9229. var remoteVideo = remoteVideos[resourceJid];
  9230. if (remoteVideo) {
  9231. // Remove remote video
  9232. console.info("Removing remote video: " + resourceJid);
  9233. remoteVideo.remove();
  9234. delete remoteVideos[resourceJid];
  9235. } else {
  9236. console.warn("No remote video for " + resourceJid);
  9237. }
  9238. VideoLayout.resizeThumbnails();
  9239. };
  9240. my.onVideoTypeChanged = function (resourceJid, newVideoType) {
  9241. if (remoteVideoTypes[resourceJid] === newVideoType) {
  9242. return;
  9243. }
  9244. console.info("Peer video type changed: ", resourceJid, newVideoType);
  9245. remoteVideoTypes[resourceJid] = newVideoType;
  9246. var smallVideo;
  9247. if (resourceJid === APP.xmpp.myResource()) {
  9248. if (!localVideoThumbnail) {
  9249. console.warn("Local video not ready yet");
  9250. return;
  9251. }
  9252. smallVideo = localVideoThumbnail;
  9253. } else if (remoteVideos[resourceJid]) {
  9254. smallVideo = remoteVideos[resourceJid];
  9255. } else {
  9256. return;
  9257. }
  9258. smallVideo.setVideoType(newVideoType);
  9259. LargeVideo.onVideoTypeChanged(resourceJid, newVideoType);
  9260. };
  9261. my.showMore = function (jid) {
  9262. if (jid === 'local') {
  9263. localVideoThumbnail.connectionIndicator.showMore();
  9264. } else {
  9265. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9266. if (remoteVideo) {
  9267. remoteVideo.connectionIndicator.showMore();
  9268. } else {
  9269. console.info("Error - no remote video for jid: " + jid);
  9270. }
  9271. }
  9272. };
  9273. my.addPreziContainer = function (id) {
  9274. var container = RemoteVideo.createContainer(id);
  9275. VideoLayout.resizeThumbnails();
  9276. return container;
  9277. };
  9278. my.setLargeVideoVisible = function (isVisible) {
  9279. LargeVideo.setLargeVideoVisible(isVisible);
  9280. if(!isVisible && focusedVideoResourceJid) {
  9281. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9282. if(smallVideo) {
  9283. smallVideo.focus(false);
  9284. smallVideo.showAvatar();
  9285. }
  9286. focusedVideoResourceJid = null;
  9287. }
  9288. };
  9289. /**
  9290. * Resizes the video area
  9291. * @param callback a function to be called when the video space is
  9292. * resized.
  9293. */
  9294. my.resizeVideoArea = function(isVisible, callback) {
  9295. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9296. VideoLayout.resizeThumbnails(true);
  9297. };
  9298. /**
  9299. * Resizes the #videospace html element
  9300. * @param animate boolean property that indicates whether the resize should be animated or not.
  9301. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  9302. * If that parameter is null the method will check the chat pannel visibility.
  9303. * @param completeFunction a function to be called when the video space is resized
  9304. */
  9305. my.resizeVideoSpace = function (animate, isChatVisible, completeFunction) {
  9306. var availableHeight = window.innerHeight;
  9307. var availableWidth = UIUtil.getAvailableVideoWidth(isChatVisible);
  9308. if (availableWidth < 0 || availableHeight < 0) return;
  9309. if(animate) {
  9310. $('#videospace').animate({
  9311. right: window.innerWidth - availableWidth,
  9312. width: availableWidth,
  9313. height: availableHeight
  9314. },
  9315. {
  9316. queue: false,
  9317. duration: 500,
  9318. complete: completeFunction
  9319. });
  9320. } else {
  9321. $('#videospace').width(availableWidth);
  9322. $('#videospace').height(availableHeight);
  9323. }
  9324. };
  9325. my.getSmallVideo = function (resourceJid) {
  9326. if(resourceJid == APP.xmpp.myResource()) {
  9327. return localVideoThumbnail;
  9328. } else {
  9329. if(!remoteVideos[resourceJid])
  9330. return null;
  9331. return remoteVideos[resourceJid];
  9332. }
  9333. };
  9334. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9335. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9336. if(smallVideo)
  9337. smallVideo.avatarChanged(thumbUrl);
  9338. else
  9339. console.warn(
  9340. "Missed avatar update - no small video yet for " + resourceJid);
  9341. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9342. };
  9343. my.createEtherpadIframe = function(src, onloadHandler)
  9344. {
  9345. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9346. };
  9347. my.setLargeVideoState = function (state) {
  9348. LargeVideo.setState(state);
  9349. };
  9350. my.getLargeVideoState = function () {
  9351. return LargeVideo.getState();
  9352. };
  9353. my.setLargeVideoHover = function (inHandler, outHandler) {
  9354. LargeVideo.setHover(inHandler, outHandler);
  9355. };
  9356. /**
  9357. * Indicates that the video has been interrupted.
  9358. */
  9359. my.onVideoInterrupted = function () {
  9360. LargeVideo.enableVideoProblemFilter(true);
  9361. var reconnectingKey = "connection.RECONNECTING";
  9362. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9363. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9364. $('#videoConnectionMessage').css({display: "block"});
  9365. };
  9366. /**
  9367. * Indicates that the video has been restored.
  9368. */
  9369. my.onVideoRestored = function () {
  9370. LargeVideo.enableVideoProblemFilter(false);
  9371. $('#videoConnectionMessage').css({display: "none"});
  9372. };
  9373. return my;
  9374. }(VideoLayout || {}));
  9375. module.exports = VideoLayout;
  9376. },{"../../../service/RTC/MediaStreamTypes":159,"../../../service/UI/UIEvents":163,"../../RTC/RTC":7,"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../prezi/Prezi":18,"../side_pannels/contactlist/ContactList":25,"../util/UIUtil":33,"./LargeVideo":35,"./LocalVideo":36,"./RemoteVideo":37}],40:[function(require,module,exports){
  9377. //var nouns = [
  9378. //];
  9379. var pluralNouns = [
  9380. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9381. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9382. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9383. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9384. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9385. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9386. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9387. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9388. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9389. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9390. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9391. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9392. ];
  9393. //var places = [
  9394. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9395. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9396. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9397. // "Bridge"
  9398. //];
  9399. var verbs = [
  9400. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9401. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9402. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9403. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9404. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9405. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9406. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9407. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9408. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9409. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9410. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9411. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9412. ];
  9413. var adverbs = [
  9414. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9415. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9416. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9417. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9418. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9419. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9420. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9421. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9422. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9423. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9424. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9425. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9426. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9427. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9428. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9429. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9430. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9431. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9432. ];
  9433. var adjectives = [
  9434. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9435. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9436. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9437. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9438. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9439. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9440. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9441. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9442. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9443. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9444. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9445. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9446. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9447. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9448. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9449. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9450. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9451. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9452. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9453. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9454. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9455. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9456. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9457. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9458. "Zealous"
  9459. ];
  9460. //var pronouns = [
  9461. //];
  9462. //var conjunctions = [
  9463. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9464. //];
  9465. /*
  9466. * Maps a string (category name) to the array of words from that category.
  9467. */
  9468. var CATEGORIES =
  9469. {
  9470. //"_NOUN_": nouns,
  9471. "_PLURALNOUN_": pluralNouns,
  9472. //"_PLACE_": places,
  9473. "_VERB_": verbs,
  9474. "_ADVERB_": adverbs,
  9475. "_ADJECTIVE_": adjectives
  9476. //"_PRONOUN_": pronouns,
  9477. //"_CONJUNCTION_": conjunctions,
  9478. };
  9479. var PATTERNS = [
  9480. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9481. // BeautifulFungiOrSpaghetti
  9482. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9483. // AmazinglyScaryToy
  9484. //"_ADVERB__ADJECTIVE__NOUN_",
  9485. // NeitherTrashNorRifle
  9486. //"Neither_NOUN_Nor_NOUN_",
  9487. //"Either_NOUN_Or_NOUN_",
  9488. // EitherCopulateOrInvestigate
  9489. //"Either_VERB_Or_VERB_",
  9490. //"Neither_VERB_Nor_VERB_",
  9491. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9492. //"The_ADVERB__ADJECTIVE__NOUN_",
  9493. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9494. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9495. // WolvesComputeBadly
  9496. //"_PLURALNOUN__VERB__ADVERB_",
  9497. // UniteFacilitateAndMerge
  9498. //"_VERB__VERB_And_VERB_",
  9499. //NastyWitchesAtThePub
  9500. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9501. ];
  9502. /*
  9503. * Returns a random element from the array 'arr'
  9504. */
  9505. function randomElement(arr) {
  9506. return arr[Math.floor(Math.random() * arr.length)];
  9507. }
  9508. /*
  9509. * Returns true if the string 's' contains one of the
  9510. * template strings.
  9511. */
  9512. function hasTemplate(s) {
  9513. for (var template in CATEGORIES){
  9514. if (s.indexOf(template) >= 0){
  9515. return true;
  9516. }
  9517. }
  9518. }
  9519. /**
  9520. * Generates new room name.
  9521. */
  9522. var RoomNameGenerator = {
  9523. generateRoomWithoutSeparator: function() {
  9524. // Note that if more than one pattern is available, the choice of
  9525. // 'name' won't have a uniform distribution amongst all patterns (names
  9526. // from patterns with fewer options will have higher probability of
  9527. // being chosen that names from patterns with more options).
  9528. var name = randomElement(PATTERNS);
  9529. var word;
  9530. while (hasTemplate(name)) {
  9531. for (var template in CATEGORIES) {
  9532. word = randomElement(CATEGORIES[template]);
  9533. name = name.replace(template, word);
  9534. }
  9535. }
  9536. return name;
  9537. }
  9538. };
  9539. module.exports = RoomNameGenerator;
  9540. },{}],41:[function(require,module,exports){
  9541. /* global $, interfaceConfig */
  9542. var animateTimeout, updateTimeout;
  9543. var RoomNameGenerator = require("./RoomnameGenerator");
  9544. function enter_room() {
  9545. var val = $("#enter_room_field").val();
  9546. if(!val) {
  9547. val = $("#enter_room_field").attr("room_name");
  9548. }
  9549. if (val) {
  9550. window.location.pathname = "/" + val;
  9551. }
  9552. }
  9553. function animate(word) {
  9554. var currentVal = $("#enter_room_field").attr("placeholder");
  9555. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9556. animateTimeout = setTimeout(function() {
  9557. animate(word.substring(1, word.length))
  9558. }, 70);
  9559. }
  9560. function update_roomname() {
  9561. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9562. $("#enter_room_field").attr("room_name", word);
  9563. $("#enter_room_field").attr("placeholder", "");
  9564. clearTimeout(animateTimeout);
  9565. animate(word);
  9566. updateTimeout = setTimeout(update_roomname, 10000);
  9567. }
  9568. function setupWelcomePage() {
  9569. $("#videoconference_page").hide();
  9570. $("#domain_name").text(
  9571. window.location.protocol + "//" + window.location.host + "/");
  9572. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9573. var leftWatermarkDiv =
  9574. $("#welcome_page_header div[class='watermark leftwatermark']");
  9575. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  9576. leftWatermarkDiv.css({display: 'block'});
  9577. leftWatermarkDiv.parent().get(0).href =
  9578. interfaceConfig.JITSI_WATERMARK_LINK;
  9579. }
  9580. }
  9581. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9582. var rightWatermarkDiv =
  9583. $("#welcome_page_header div[class='watermark rightwatermark']");
  9584. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9585. rightWatermarkDiv.css({display: 'block'});
  9586. rightWatermarkDiv.parent().get(0).href =
  9587. interfaceConfig.BRAND_WATERMARK_LINK;
  9588. rightWatermarkDiv.get(0).style.backgroundImage =
  9589. "url(images/rightwatermark.png)";
  9590. }
  9591. }
  9592. if (interfaceConfig.SHOW_POWERED_BY) {
  9593. $("#welcome_page_header>a[class='poweredby']")
  9594. .css({display: 'block'});
  9595. }
  9596. $("#enter_room_button").click(function() {
  9597. enter_room();
  9598. });
  9599. $("#enter_room_field").keydown(function (event) {
  9600. if (event.keyCode === 13 /* enter */) {
  9601. enter_room();
  9602. }
  9603. });
  9604. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  9605. var updateTimeout;
  9606. var animateTimeout;
  9607. var selector = $("#reload_roomname");
  9608. selector.click(function () {
  9609. clearTimeout(updateTimeout);
  9610. clearTimeout(animateTimeout);
  9611. update_roomname();
  9612. });
  9613. selector.show();
  9614. update_roomname();
  9615. }
  9616. $("#disable_welcome").click(function () {
  9617. window.localStorage.welcomePageDisabled =
  9618. $("#disable_welcome").is(":checked");
  9619. });
  9620. }
  9621. module.exports = setupWelcomePage;
  9622. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9623. /* global $, $iq, config, interfaceConfig */
  9624. var params = {};
  9625. function getConfigParamsFromUrl() {
  9626. if(!location.hash)
  9627. return {};
  9628. var hash = location.hash.substr(1);
  9629. var result = {};
  9630. hash.split("&").forEach(function(part) {
  9631. var item = part.split("=");
  9632. result[item[0]] = JSON.parse(
  9633. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9634. });
  9635. return result;
  9636. }
  9637. params = getConfigParamsFromUrl();
  9638. var URLProcessor = {
  9639. setConfigParametersFromUrl: function () {
  9640. for(var key in params) {
  9641. if(typeof key !== "string")
  9642. continue;
  9643. var confObj = null, confKey;
  9644. if (key.indexOf("config.") === 0) {
  9645. confObj = config;
  9646. confKey = key.substr("config.".length);
  9647. } else if (key.indexOf("interfaceConfig.") === 0) {
  9648. confObj = interfaceConfig;
  9649. confKey = key.substr("interfaceConfig.".length);
  9650. }
  9651. if (!confObj)
  9652. continue;
  9653. var value = params[key];
  9654. if (confObj[confKey] && typeof confObj[confKey] !== typeof value)
  9655. {
  9656. console.warn("The type of " + key +
  9657. " is wrong. That parameter won't be updated in config.js.");
  9658. continue;
  9659. }
  9660. confObj[confKey] = value;
  9661. }
  9662. }
  9663. };
  9664. module.exports = URLProcessor;
  9665. },{}],43:[function(require,module,exports){
  9666. /* global APP, require */
  9667. var EventEmitter = require("events");
  9668. var eventEmitter = new EventEmitter();
  9669. var CQEvents = require("../../service/connectionquality/CQEvents");
  9670. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9671. /**
  9672. * local stats
  9673. * @type {{}}
  9674. */
  9675. var stats = {};
  9676. /**
  9677. * remote stats
  9678. * @type {{}}
  9679. */
  9680. var remoteStats = {};
  9681. /**
  9682. * Interval for sending statistics to other participants
  9683. * @type {null}
  9684. */
  9685. var sendIntervalId = null;
  9686. /**
  9687. * Start statistics sending.
  9688. */
  9689. function startSendingStats() {
  9690. sendStats();
  9691. sendIntervalId = setInterval(sendStats, 10000);
  9692. }
  9693. /**
  9694. * Sends statistics to other participants
  9695. */
  9696. function sendStats() {
  9697. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9698. }
  9699. /**
  9700. * Converts statistics to format for sending through XMPP
  9701. * @param stats the statistics
  9702. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9703. */
  9704. function convertToMUCStats(stats) {
  9705. return {
  9706. "bitrate_download": stats.bitrate.download,
  9707. "bitrate_upload": stats.bitrate.upload,
  9708. "packetLoss_total": stats.packetLoss.total,
  9709. "packetLoss_download": stats.packetLoss.download,
  9710. "packetLoss_upload": stats.packetLoss.upload
  9711. };
  9712. }
  9713. /**
  9714. * Converts statistics to format used by VideoLayout
  9715. * @param stats
  9716. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9717. */
  9718. function parseMUCStats(stats) {
  9719. return {
  9720. bitrate: {
  9721. download: stats.bitrate_download,
  9722. upload: stats.bitrate_upload
  9723. },
  9724. packetLoss: {
  9725. total: stats.packetLoss_total,
  9726. download: stats.packetLoss_download,
  9727. upload: stats.packetLoss_upload
  9728. }
  9729. };
  9730. }
  9731. var ConnectionQuality = {
  9732. init: function () {
  9733. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9734. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9735. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9736. },
  9737. /**
  9738. * Updates the local statistics
  9739. * @param data new statistics
  9740. */
  9741. updateLocalStats: function (data) {
  9742. stats = data;
  9743. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9744. if (sendIntervalId == null) {
  9745. startSendingStats();
  9746. }
  9747. },
  9748. /**
  9749. * Updates remote statistics
  9750. * @param jid the jid associated with the statistics
  9751. * @param data the statistics
  9752. */
  9753. updateRemoteStats: function (jid, data) {
  9754. if (data == null || data.packetLoss_total == null) {
  9755. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9756. return;
  9757. }
  9758. remoteStats[jid] = parseMUCStats(data);
  9759. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9760. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9761. },
  9762. /**
  9763. * Stops statistics sending.
  9764. */
  9765. stopSendingStats: function () {
  9766. clearInterval(sendIntervalId);
  9767. sendIntervalId = null;
  9768. //notify UI about stopping statistics gathering
  9769. eventEmitter.emit(CQEvents.STOP);
  9770. },
  9771. /**
  9772. * Returns the local statistics.
  9773. */
  9774. getStats: function () {
  9775. return stats;
  9776. },
  9777. addListener: function (type, listener) {
  9778. eventEmitter.on(type, listener);
  9779. }
  9780. };
  9781. module.exports = ConnectionQuality;
  9782. },{"../../service/connectionquality/CQEvents":165,"../../service/xmpp/XMPPEvents":169,"events":170}],44:[function(require,module,exports){
  9783. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9784. getUserMediaWithConstraints */
  9785. /**
  9786. * Indicates that desktop stream is currently in use(for toggle purpose).
  9787. * @type {boolean}
  9788. */
  9789. var isUsingScreenStream = false;
  9790. /**
  9791. * Indicates that switch stream operation is in progress and prevent from
  9792. * triggering new events.
  9793. * @type {boolean}
  9794. */
  9795. var switchInProgress = false;
  9796. /**
  9797. * Method used to get screen sharing stream.
  9798. *
  9799. * @type {function (stream_callback, failure_callback}
  9800. */
  9801. var obtainDesktopStream = null;
  9802. /**
  9803. * Indicates whether desktop sharing extension is installed.
  9804. * @type {boolean}
  9805. */
  9806. var extInstalled = false;
  9807. /**
  9808. * Indicates whether update of desktop sharing extension is required.
  9809. * @type {boolean}
  9810. */
  9811. var extUpdateRequired = false;
  9812. var AdapterJS = require("../RTC/adapter.screenshare");
  9813. var EventEmitter = require("events");
  9814. var eventEmitter = new EventEmitter();
  9815. var DesktopSharingEventTypes
  9816. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9817. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9818. var RTCEvents = require("../../service/RTC/RTCEvents");
  9819. /**
  9820. * Method obtains desktop stream from WebRTC 'screen' source.
  9821. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9822. */
  9823. function obtainWebRTCScreen(streamCallback, failCallback) {
  9824. APP.RTC.getUserMediaWithConstraints(
  9825. ['screen'],
  9826. streamCallback,
  9827. failCallback
  9828. );
  9829. }
  9830. /**
  9831. * Constructs inline install URL for Chrome desktop streaming extension.
  9832. * The 'chromeExtensionId' must be defined in config.js.
  9833. * @returns {string}
  9834. */
  9835. function getWebStoreInstallUrl()
  9836. {
  9837. return "https://chrome.google.com/webstore/detail/" +
  9838. config.chromeExtensionId;
  9839. }
  9840. /**
  9841. * Checks whether extension update is required.
  9842. * @param minVersion minimal required version
  9843. * @param extVersion current extension version
  9844. * @returns {boolean}
  9845. */
  9846. function isUpdateRequired(minVersion, extVersion)
  9847. {
  9848. try
  9849. {
  9850. var s1 = minVersion.split('.');
  9851. var s2 = extVersion.split('.');
  9852. var len = Math.max(s1.length, s2.length);
  9853. for (var i = 0; i < len; i++)
  9854. {
  9855. var n1 = 0,
  9856. n2 = 0;
  9857. if (i < s1.length)
  9858. n1 = parseInt(s1[i]);
  9859. if (i < s2.length)
  9860. n2 = parseInt(s2[i]);
  9861. if (isNaN(n1) || isNaN(n2))
  9862. {
  9863. return true;
  9864. }
  9865. else if (n1 !== n2)
  9866. {
  9867. return n1 > n2;
  9868. }
  9869. }
  9870. // will happen if boths version has identical numbers in
  9871. // their components (even if one of them is longer, has more components)
  9872. return false;
  9873. }
  9874. catch (e)
  9875. {
  9876. console.error("Failed to parse extension version", e);
  9877. APP.UI.messageHandler.showError("dialog.error",
  9878. "dialog.detectext");
  9879. return true;
  9880. }
  9881. }
  9882. function checkChromeExtInstalled(callback) {
  9883. if (!chrome.runtime) {
  9884. // No API, so no extension for sure
  9885. callback(false, false);
  9886. return;
  9887. }
  9888. chrome.runtime.sendMessage(
  9889. config.chromeExtensionId,
  9890. { getVersion: true },
  9891. function (response) {
  9892. if (!response || !response.version) {
  9893. // Communication failure - assume that no endpoint exists
  9894. console.warn(
  9895. "Extension not installed?: ", chrome.runtime.lastError);
  9896. callback(false, false);
  9897. return;
  9898. }
  9899. // Check installed extension version
  9900. var extVersion = response.version;
  9901. console.log('Extension version is: ' + extVersion);
  9902. var updateRequired
  9903. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  9904. callback(!updateRequired, updateRequired);
  9905. }
  9906. );
  9907. }
  9908. function doGetStreamFromExtension(streamCallback, failCallback) {
  9909. // Sends 'getStream' msg to the extension.
  9910. // Extension id must be defined in the config.
  9911. chrome.runtime.sendMessage(
  9912. config.chromeExtensionId,
  9913. { getStream: true, sources: config.desktopSharingSources },
  9914. function (response) {
  9915. if (!response) {
  9916. failCallback(chrome.runtime.lastError);
  9917. return;
  9918. }
  9919. console.log("Response from extension: " + response);
  9920. if (response.streamId) {
  9921. APP.RTC.getUserMediaWithConstraints(
  9922. ['desktop'],
  9923. function (stream) {
  9924. streamCallback(stream);
  9925. },
  9926. failCallback,
  9927. null, null, null,
  9928. response.streamId);
  9929. } else {
  9930. failCallback("Extension failed to get the stream");
  9931. }
  9932. }
  9933. );
  9934. }
  9935. /**
  9936. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  9937. * stream for returned stream token.
  9938. */
  9939. function obtainScreenFromExtension(streamCallback, failCallback) {
  9940. if (extInstalled) {
  9941. doGetStreamFromExtension(streamCallback, failCallback);
  9942. } else {
  9943. if (extUpdateRequired) {
  9944. alert(
  9945. 'Jitsi Desktop Streamer requires update. ' +
  9946. 'Changes will take effect after next Chrome restart.');
  9947. }
  9948. chrome.webstore.install(
  9949. getWebStoreInstallUrl(),
  9950. function (arg) {
  9951. console.log("Extension installed successfully", arg);
  9952. extInstalled = true;
  9953. // We need to give a moment for the endpoint to become available
  9954. window.setTimeout(function () {
  9955. doGetStreamFromExtension(streamCallback, failCallback);
  9956. }, 500);
  9957. },
  9958. function (arg) {
  9959. console.log("Failed to install the extension", arg);
  9960. failCallback(arg);
  9961. APP.UI.messageHandler.showError("dialog.error",
  9962. "dialog.failtoinstall");
  9963. }
  9964. );
  9965. }
  9966. }
  9967. /**
  9968. * Call this method to toggle desktop sharing feature.
  9969. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  9970. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  9971. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  9972. * enabled), pass any other string or nothing in order to disable this
  9973. * feature completely.
  9974. */
  9975. function setDesktopSharing(method) {
  9976. obtainDesktopStream = null;
  9977. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  9978. // care about 'method' parameter
  9979. if (RTCBrowserType.isTemasysPluginUsed()) {
  9980. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  9981. console.info("Screensharing not supported by this plugin version");
  9982. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  9983. console.info(
  9984. "Screensharing not available with Temasys plugin on this site");
  9985. } else {
  9986. obtainDesktopStream = obtainWebRTCScreen;
  9987. console.info("Using Temasys plugin for desktop sharing");
  9988. }
  9989. } else if (RTCBrowserType.isChrome()) {
  9990. if (method == "ext") {
  9991. if (RTCBrowserType.getChromeVersion() >= 34) {
  9992. obtainDesktopStream = obtainScreenFromExtension;
  9993. console.info("Using Chrome extension for desktop sharing");
  9994. initChromeExtension();
  9995. } else {
  9996. console.info("Chrome extension not supported until ver 34");
  9997. }
  9998. } else if (method == "webrtc") {
  9999. obtainDesktopStream = obtainWebRTCScreen;
  10000. console.info("Using Chrome WebRTC for desktop sharing");
  10001. }
  10002. }
  10003. if (!obtainDesktopStream) {
  10004. console.info("Desktop sharing disabled");
  10005. }
  10006. }
  10007. /**
  10008. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10009. * config.js to support inline installs. Host site must be selected as main
  10010. * website of published extension.
  10011. */
  10012. function initInlineInstalls()
  10013. {
  10014. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10015. }
  10016. function initChromeExtension() {
  10017. // Initialize Chrome extension inline installs
  10018. initInlineInstalls();
  10019. // Check if extension is installed
  10020. checkChromeExtInstalled(function (installed, updateRequired) {
  10021. extInstalled = installed;
  10022. extUpdateRequired = updateRequired;
  10023. console.info(
  10024. "Chrome extension installed: " + extInstalled +
  10025. " updateRequired: " + extUpdateRequired);
  10026. });
  10027. }
  10028. function getVideoStreamFailed(error) {
  10029. console.error("Failed to obtain the stream to switch to", error);
  10030. switchInProgress = false;
  10031. isUsingScreenStream = false;
  10032. newStreamCreated(null);
  10033. }
  10034. function getDesktopStreamFailed(error) {
  10035. console.error("Failed to obtain the stream to switch to", error);
  10036. switchInProgress = false;
  10037. }
  10038. function streamSwitchDone() {
  10039. switchInProgress = false;
  10040. eventEmitter.emit(
  10041. DesktopSharingEventTypes.SWITCHING_DONE,
  10042. isUsingScreenStream);
  10043. }
  10044. function newStreamCreated(stream)
  10045. {
  10046. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10047. stream, isUsingScreenStream, streamSwitchDone);
  10048. }
  10049. function onEndedHandler(stream) {
  10050. if (!switchInProgress && isUsingScreenStream) {
  10051. APP.desktopsharing.toggleScreenSharing();
  10052. }
  10053. //FIXME: to be verified
  10054. if (stream.removeEventListener) {
  10055. stream.removeEventListener('ended', onEndedHandler);
  10056. } else {
  10057. stream.detachEvent('ended', onEndedHandler);
  10058. }
  10059. }
  10060. // Called when RTC finishes initialization
  10061. function onWebRtcReady() {
  10062. setDesktopSharing(config.desktopSharing);
  10063. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10064. }
  10065. module.exports = {
  10066. isUsingScreenStream: function () {
  10067. return isUsingScreenStream;
  10068. },
  10069. /**
  10070. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10071. * and enabled.
  10072. */
  10073. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10074. init: function () {
  10075. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10076. },
  10077. addListener: function (listener, type)
  10078. {
  10079. eventEmitter.on(type, listener);
  10080. },
  10081. removeListener: function (listener, type) {
  10082. eventEmitter.removeListener(type, listener);
  10083. },
  10084. /*
  10085. * Toggles screen sharing.
  10086. */
  10087. toggleScreenSharing: function () {
  10088. if (switchInProgress || !obtainDesktopStream) {
  10089. console.warn("Switch in progress or no method defined");
  10090. return;
  10091. }
  10092. switchInProgress = true;
  10093. if (!isUsingScreenStream)
  10094. {
  10095. // Switch to desktop stream
  10096. obtainDesktopStream(
  10097. function (stream) {
  10098. // We now use screen stream
  10099. isUsingScreenStream = true;
  10100. // Hook 'ended' event to restore camera
  10101. // when screen stream stops
  10102. //FIXME: to be verified
  10103. if (stream.addEventListener) {
  10104. stream.addEventListener('ended', function () {
  10105. onEndedHandler(stream);
  10106. });
  10107. } else {
  10108. stream.attachEvent('ended', function () {
  10109. onEndedHandler(stream);
  10110. });
  10111. }
  10112. newStreamCreated(stream);
  10113. },
  10114. getDesktopStreamFailed);
  10115. } else {
  10116. // Disable screen stream
  10117. APP.RTC.getUserMediaWithConstraints(
  10118. ['video'],
  10119. function (stream) {
  10120. // We are now using camera stream
  10121. isUsingScreenStream = false;
  10122. newStreamCreated(stream);
  10123. },
  10124. getVideoStreamFailed, config.resolution || '360'
  10125. );
  10126. }
  10127. }
  10128. };
  10129. },{"../../service/RTC/RTCEvents":160,"../../service/desktopsharing/DesktopSharingEventTypes":166,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":170}],45:[function(require,module,exports){
  10130. /* global APP, $ */
  10131. //maps keycode to character, id of popover for given function and function
  10132. var shortcuts = {};
  10133. function initShortcutHandlers() {
  10134. shortcuts = {
  10135. 67: {
  10136. character: "C",
  10137. id: "toggleChatPopover",
  10138. function: APP.UI.toggleChat
  10139. },
  10140. 70: {
  10141. character: "F",
  10142. id: "filmstripPopover",
  10143. function: APP.UI.toggleFilmStrip
  10144. },
  10145. 77: {
  10146. character: "M",
  10147. id: "mutePopover",
  10148. function: APP.UI.toggleAudio
  10149. },
  10150. 84: {
  10151. character: "T",
  10152. function: function() {
  10153. if(!APP.RTC.localAudio.isMuted()) {
  10154. APP.UI.toggleAudio();
  10155. }
  10156. }
  10157. },
  10158. 86: {
  10159. character: "V",
  10160. id: "toggleVideoPopover",
  10161. function: APP.UI.toggleVideo
  10162. }
  10163. };
  10164. }
  10165. var KeyboardShortcut = {
  10166. init: function () {
  10167. initShortcutHandlers();
  10168. window.onkeyup = function(e) {
  10169. var keycode = e.which;
  10170. if(!($(":focus").is("input[type=text]") ||
  10171. $(":focus").is("input[type=password]") ||
  10172. $(":focus").is("textarea"))) {
  10173. if (typeof shortcuts[keycode] === "object") {
  10174. shortcuts[keycode].function();
  10175. }
  10176. else if (keycode >= "0".charCodeAt(0) &&
  10177. keycode <= "9".charCodeAt(0)) {
  10178. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10179. }
  10180. //esc while the smileys are visible hides them
  10181. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10182. APP.UI.toggleSmileys();
  10183. }
  10184. };
  10185. window.onkeydown = function(e) {
  10186. if(!($(":focus").is("input[type=text]") ||
  10187. $(":focus").is("input[type=password]") ||
  10188. $(":focus").is("textarea"))) {
  10189. if(e.which === "T".charCodeAt(0)) {
  10190. if(APP.RTC.localAudio.isMuted()) {
  10191. APP.UI.toggleAudio();
  10192. }
  10193. }
  10194. }
  10195. };
  10196. var self = this;
  10197. $('body').popover({ selector: '[data-toggle=popover]',
  10198. trigger: 'click hover',
  10199. content: function() {
  10200. return this.getAttribute("content") +
  10201. self.getShortcut(this.getAttribute("shortcut"));
  10202. }
  10203. });
  10204. },
  10205. /**
  10206. *
  10207. * @param id indicates the popover associated with the shortcut
  10208. * @returns {string} the keyboard shortcut used for the id given
  10209. */
  10210. getShortcut: function (id) {
  10211. for (var keycode in shortcuts) {
  10212. if (shortcuts.hasOwnProperty(keycode)) {
  10213. if (shortcuts[keycode].id === id) {
  10214. return " (" + shortcuts[keycode].character + ")";
  10215. }
  10216. }
  10217. }
  10218. return "";
  10219. }
  10220. };
  10221. module.exports = KeyboardShortcut;
  10222. },{}],46:[function(require,module,exports){
  10223. /* global APP, require, $ */
  10224. /**
  10225. * This module is meant to (eventually) contain and manage all information
  10226. * about members/participants of the conference, so that other modules don't
  10227. * have to do it on their own, and so that other modules can access members'
  10228. * information from a single place.
  10229. *
  10230. * Currently this module only manages information about the support of jingle
  10231. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10232. * be added as needed.
  10233. */
  10234. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10235. var Events = require("../../service/members/Events");
  10236. var EventEmitter = require("events");
  10237. var eventEmitter = new EventEmitter();
  10238. /**
  10239. * The actual container.
  10240. */
  10241. var members = {};
  10242. /**
  10243. * There is at least one member that supports DTMF (i.e. is jigasi).
  10244. */
  10245. var atLeastOneDtmf = false;
  10246. function registerListeners() {
  10247. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10248. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10249. }
  10250. /**
  10251. * Handles a new member joining the MUC.
  10252. */
  10253. function onMucMemberJoined(jid, id, displayName) {
  10254. var member = {
  10255. displayName: displayName
  10256. };
  10257. APP.xmpp.getConnection().disco.info(
  10258. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10259. members[jid] = member;
  10260. }
  10261. /**
  10262. * Handles a member leaving the MUC.
  10263. */
  10264. function onMucMemberLeft(jid) {
  10265. delete members[jid];
  10266. updateAtLeastOneDtmf();
  10267. }
  10268. /**
  10269. * Handles the reception of a disco#info packet from a particular JID.
  10270. * @param jid the JID sending the packet.
  10271. * @param iq the packet.
  10272. */
  10273. function onDiscoInfoReceived(jid, iq) {
  10274. if (!members[jid])
  10275. return;
  10276. var supportsDtmf
  10277. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10278. updateDtmf(jid, supportsDtmf);
  10279. }
  10280. /**
  10281. * Updates the 'supportsDtmf' field for a member.
  10282. * @param jid the jid of the member.
  10283. * @param newValue the new value for the 'supportsDtmf' field.
  10284. */
  10285. function updateDtmf(jid, newValue) {
  10286. var oldValue = members[jid].supportsDtmf;
  10287. members[jid].supportsDtmf = newValue;
  10288. if (newValue != oldValue) {
  10289. updateAtLeastOneDtmf();
  10290. }
  10291. }
  10292. /**
  10293. * Checks each member's 'supportsDtmf' field and updates
  10294. * 'atLastOneSupportsDtmf'.
  10295. */
  10296. function updateAtLeastOneDtmf() {
  10297. var newAtLeastOneDtmf = false;
  10298. for (var key in members) {
  10299. if (typeof members[key].supportsDtmf !== 'undefined'
  10300. && members[key].supportsDtmf) {
  10301. newAtLeastOneDtmf= true;
  10302. break;
  10303. }
  10304. }
  10305. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10306. atLeastOneDtmf = newAtLeastOneDtmf;
  10307. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10308. }
  10309. }
  10310. /**
  10311. * Exported interface.
  10312. */
  10313. var Members = {
  10314. start: function() {
  10315. registerListeners();
  10316. },
  10317. addListener: function(type, listener) {
  10318. eventEmitter.on(type, listener);
  10319. },
  10320. removeListener: function (type, listener) {
  10321. eventEmitter.removeListener(type, listener);
  10322. },
  10323. size: function () {
  10324. return Object.keys(members).length;
  10325. },
  10326. getMembers: function () {
  10327. return members;
  10328. }
  10329. };
  10330. module.exports = Members;
  10331. },{"../../service/members/Events":167,"../../service/xmpp/XMPPEvents":169,"events":170}],47:[function(require,module,exports){
  10332. var email = '';
  10333. var displayName = '';
  10334. var userId;
  10335. var language = null;
  10336. function supportsLocalStorage() {
  10337. try {
  10338. return 'localStorage' in window && window.localStorage !== null;
  10339. } catch (e) {
  10340. console.log("localstorage is not supported");
  10341. return false;
  10342. }
  10343. }
  10344. function generateUniqueId() {
  10345. function _p8() {
  10346. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10347. }
  10348. return _p8() + _p8() + _p8() + _p8();
  10349. }
  10350. if (supportsLocalStorage()) {
  10351. if (!window.localStorage.jitsiMeetId) {
  10352. window.localStorage.jitsiMeetId = generateUniqueId();
  10353. console.log("generated id", window.localStorage.jitsiMeetId);
  10354. }
  10355. userId = window.localStorage.jitsiMeetId || '';
  10356. email = window.localStorage.email || '';
  10357. displayName = window.localStorage.displayname || '';
  10358. language = window.localStorage.language;
  10359. } else {
  10360. console.log("local storage is not supported");
  10361. userId = generateUniqueId();
  10362. }
  10363. var Settings = {
  10364. setDisplayName: function (newDisplayName) {
  10365. displayName = newDisplayName;
  10366. window.localStorage.displayname = displayName;
  10367. return displayName;
  10368. },
  10369. setEmail: function (newEmail) {
  10370. email = newEmail;
  10371. window.localStorage.email = newEmail;
  10372. return email;
  10373. },
  10374. getSettings: function () {
  10375. return {
  10376. email: email,
  10377. displayName: displayName,
  10378. uid: userId,
  10379. language: language
  10380. };
  10381. },
  10382. setLanguage: function (lang) {
  10383. language = lang;
  10384. window.localStorage.language = lang;
  10385. }
  10386. };
  10387. module.exports = Settings;
  10388. },{}],48:[function(require,module,exports){
  10389. /* global config, $, APP, Strophe, callstats */
  10390. var jsSHA = require('jssha');
  10391. var io = require('socket.io-client');
  10392. var callStats = null;
  10393. function initCallback (err, msg) {
  10394. console.log("Initializing Status: err="+err+" msg="+msg);
  10395. }
  10396. var CallStats = {
  10397. init: function (jingleSession) {
  10398. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10399. return;
  10400. callStats = new callstats($, io, jsSHA);
  10401. this.session = jingleSession;
  10402. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10403. this.userID = APP.xmpp.myResource();
  10404. var location = window.location;
  10405. this.confID = location.protocol + "//" +
  10406. location.hostname + location.pathname;
  10407. //userID is generated or given by the origin server
  10408. callStats.initialize(config.callStatsID,
  10409. config.callStatsSecret,
  10410. this.userID,
  10411. initCallback);
  10412. var usage = callStats.fabricUsage.multiplex;
  10413. callStats.addNewFabric(this.peerconnection,
  10414. Strophe.getResourceFromJid(jingleSession.peerjid),
  10415. usage,
  10416. this.confID,
  10417. this.pcCallback.bind(this));
  10418. },
  10419. pcCallback: function (err, msg) {
  10420. if (!callStats)
  10421. return;
  10422. console.log("Monitoring status: "+ err + " msg: " + msg);
  10423. callStats.sendFabricEvent(this.peerconnection,
  10424. callStats.fabricEvent.fabricSetup, this.confID);
  10425. },
  10426. sendMuteEvent: function (mute, type) {
  10427. if (!callStats)
  10428. return;
  10429. var event = null;
  10430. if (type === "video") {
  10431. event = (mute? callStats.fabricEvent.videoPause :
  10432. callStats.fabricEvent.videoResume);
  10433. }
  10434. else {
  10435. event = (mute? callStats.fabricEvent.audioMute :
  10436. callStats.fabricEvent.audioUnmute);
  10437. }
  10438. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10439. },
  10440. sendTerminateEvent: function () {
  10441. if(!callStats) {
  10442. return;
  10443. }
  10444. callStats.sendFabricEvent(this.peerconnection,
  10445. callStats.fabricEvent.fabricTerminated, this.confID);
  10446. },
  10447. sendSetupFailedEvent: function () {
  10448. if(!callStats) {
  10449. return;
  10450. }
  10451. callStats.sendFabricEvent(this.peerconnection,
  10452. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10453. }
  10454. };
  10455. module.exports = CallStats;
  10456. },{"jssha":71,"socket.io-client":109}],49:[function(require,module,exports){
  10457. /* global config */
  10458. /**
  10459. * Provides statistics for the local stream.
  10460. */
  10461. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10462. /**
  10463. * Size of the webaudio analyzer buffer.
  10464. * @type {number}
  10465. */
  10466. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  10467. /**
  10468. * Value of the webaudio analyzer smoothing time parameter.
  10469. * @type {number}
  10470. */
  10471. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  10472. /**
  10473. * Converts time domain data array to audio level.
  10474. * @param samples the time domain data array.
  10475. * @returns {number} the audio level
  10476. */
  10477. function timeDomainDataToAudioLevel(samples) {
  10478. var maxVolume = 0;
  10479. var length = samples.length;
  10480. for (var i = 0; i < length; i++) {
  10481. if (maxVolume < samples[i])
  10482. maxVolume = samples[i];
  10483. }
  10484. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10485. }
  10486. /**
  10487. * Animates audio level change
  10488. * @param newLevel the new audio level
  10489. * @param lastLevel the last audio level
  10490. * @returns {Number} the audio level to be set
  10491. */
  10492. function animateLevel(newLevel, lastLevel) {
  10493. var value = 0;
  10494. var diff = lastLevel - newLevel;
  10495. if(diff > 0.2) {
  10496. value = lastLevel - 0.2;
  10497. }
  10498. else if(diff < -0.4) {
  10499. value = lastLevel + 0.4;
  10500. }
  10501. else {
  10502. value = newLevel;
  10503. }
  10504. return parseFloat(value.toFixed(3));
  10505. }
  10506. /**
  10507. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10508. *
  10509. * @param stream the local stream
  10510. * @param interval stats refresh interval given in ms.
  10511. * @constructor
  10512. */
  10513. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10514. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10515. this.stream = stream;
  10516. this.intervalId = null;
  10517. this.intervalMilis = interval;
  10518. this.eventEmitter = eventEmitter;
  10519. this.audioLevel = 0;
  10520. this.statisticsService = statisticsService;
  10521. }
  10522. /**
  10523. * Starts the collecting the statistics.
  10524. */
  10525. LocalStatsCollector.prototype.start = function () {
  10526. if (config.disableAudioLevels || !window.AudioContext ||
  10527. RTCBrowserType.isTemasysPluginUsed())
  10528. return;
  10529. var context = new AudioContext();
  10530. var analyser = context.createAnalyser();
  10531. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  10532. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  10533. var source = context.createMediaStreamSource(this.stream);
  10534. source.connect(analyser);
  10535. var self = this;
  10536. this.intervalId = setInterval(
  10537. function () {
  10538. var array = new Uint8Array(analyser.frequencyBinCount);
  10539. analyser.getByteTimeDomainData(array);
  10540. var audioLevel = timeDomainDataToAudioLevel(array);
  10541. if (audioLevel != self.audioLevel) {
  10542. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10543. self.eventEmitter.emit(
  10544. "statistics.audioLevel",
  10545. self.statisticsService.LOCAL_JID,
  10546. self.audioLevel);
  10547. }
  10548. },
  10549. this.intervalMilis
  10550. );
  10551. };
  10552. /**
  10553. * Stops collecting the statistics.
  10554. */
  10555. LocalStatsCollector.prototype.stop = function () {
  10556. if (this.intervalId) {
  10557. clearInterval(this.intervalId);
  10558. this.intervalId = null;
  10559. }
  10560. };
  10561. module.exports = LocalStatsCollector;
  10562. },{"../RTC/RTCBrowserType":8}],50:[function(require,module,exports){
  10563. /* global require, ssrc2jid */
  10564. /* jshint -W117 */
  10565. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10566. /* Whether we support the browser we are running into for logging statistics */
  10567. var browserSupported = RTCBrowserType.isChrome() ||
  10568. RTCBrowserType.isOpera() || RTCBrowserType.isFirefox();
  10569. /**
  10570. * Calculates packet lost percent using the number of lost packets and the
  10571. * number of all packet.
  10572. * @param lostPackets the number of lost packets
  10573. * @param totalPackets the number of all packets.
  10574. * @returns {number} packet loss percent
  10575. */
  10576. function calculatePacketLoss(lostPackets, totalPackets) {
  10577. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10578. return 0;
  10579. return Math.round((lostPackets/totalPackets)*100);
  10580. }
  10581. function getStatValue(item, name) {
  10582. var browserType = RTCBrowserType.getBrowserType();
  10583. if (!keyMap[browserType][name])
  10584. throw "The property isn't supported!";
  10585. var key = keyMap[browserType][name];
  10586. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10587. item.stat(key) : item[key];
  10588. }
  10589. /**
  10590. * Peer statistics data holder.
  10591. * @constructor
  10592. */
  10593. function PeerStats()
  10594. {
  10595. this.ssrc2Loss = {};
  10596. this.ssrc2AudioLevel = {};
  10597. this.ssrc2bitrate = {};
  10598. this.ssrc2resolution = {};
  10599. }
  10600. /**
  10601. * The bandwidth
  10602. * @type {{}}
  10603. */
  10604. PeerStats.bandwidth = {};
  10605. /**
  10606. * The bit rate
  10607. * @type {{}}
  10608. */
  10609. PeerStats.bitrate = {};
  10610. /**
  10611. * The packet loss rate
  10612. * @type {{}}
  10613. */
  10614. PeerStats.packetLoss = null;
  10615. /**
  10616. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10617. * represented by this instance.
  10618. * @param ssrc audio or video RTP stream SSRC.
  10619. * @param lossRate new packet loss rate value to be set.
  10620. */
  10621. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10622. {
  10623. this.ssrc2Loss[ssrc] = lossRate;
  10624. };
  10625. /**
  10626. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10627. * represented by this instance.
  10628. * @param ssrc audio or video RTP stream SSRC.
  10629. * @param resolution new resolution value to be set.
  10630. */
  10631. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10632. {
  10633. if(resolution === null && this.ssrc2resolution[ssrc])
  10634. {
  10635. delete this.ssrc2resolution[ssrc];
  10636. }
  10637. else if(resolution !== null)
  10638. this.ssrc2resolution[ssrc] = resolution;
  10639. };
  10640. /**
  10641. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10642. * represented by this instance.
  10643. * @param ssrc audio or video RTP stream SSRC.
  10644. * @param bitrate new bitrate value to be set.
  10645. */
  10646. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10647. {
  10648. if(this.ssrc2bitrate[ssrc])
  10649. {
  10650. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10651. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10652. }
  10653. else {
  10654. this.ssrc2bitrate[ssrc] = bitrate;
  10655. }
  10656. };
  10657. /**
  10658. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10659. * the stream which belongs to the peer represented by this instance.
  10660. * @param ssrc RTP stream SSRC for which current audio level value will be
  10661. * updated.
  10662. * @param audioLevel the new audio level value to be set. Value is truncated to
  10663. * fit the range from 0 to 1.
  10664. */
  10665. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10666. {
  10667. // Range limit 0 - 1
  10668. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10669. };
  10670. function formatAudioLevel(audioLevel) {
  10671. return Math.min(Math.max(audioLevel, 0), 1);
  10672. }
  10673. /**
  10674. * Array with the transport information.
  10675. * @type {Array}
  10676. */
  10677. PeerStats.transport = [];
  10678. /**
  10679. * <tt>StatsCollector</tt> registers for stats updates of given
  10680. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10681. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10682. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10683. * instance as an event source.
  10684. *
  10685. * @param peerconnection webRTC peer connection object.
  10686. * @param interval stats refresh interval given in ms.
  10687. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10688. * called on stats update.
  10689. * @constructor
  10690. */
  10691. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10692. {
  10693. this.peerconnection = peerconnection;
  10694. this.baselineAudioLevelsReport = null;
  10695. this.currentAudioLevelsReport = null;
  10696. this.currentStatsReport = null;
  10697. this.baselineStatsReport = null;
  10698. this.audioLevelsIntervalId = null;
  10699. this.eventEmitter = eventEmitter;
  10700. /**
  10701. * Gather PeerConnection stats once every this many milliseconds.
  10702. */
  10703. this.GATHER_INTERVAL = 15000;
  10704. /**
  10705. * Log stats via the focus once every this many milliseconds.
  10706. */
  10707. this.LOG_INTERVAL = 60000;
  10708. /**
  10709. * Gather stats and store them in this.statsToBeLogged.
  10710. */
  10711. this.gatherStatsIntervalId = null;
  10712. /**
  10713. * Send the stats already saved in this.statsToBeLogged to be logged via
  10714. * the focus.
  10715. */
  10716. this.logStatsIntervalId = null;
  10717. /**
  10718. * Stores the statistics which will be send to the focus to be logged.
  10719. */
  10720. this.statsToBeLogged =
  10721. {
  10722. timestamps: [],
  10723. stats: {}
  10724. };
  10725. // Updates stats interval
  10726. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10727. this.statsIntervalId = null;
  10728. this.statsIntervalMilis = statsInterval;
  10729. // Map of jids to PeerStats
  10730. this.jid2stats = {};
  10731. }
  10732. module.exports = StatsCollector;
  10733. /**
  10734. * Stops stats updates.
  10735. */
  10736. StatsCollector.prototype.stop = function () {
  10737. if (this.audioLevelsIntervalId) {
  10738. clearInterval(this.audioLevelsIntervalId);
  10739. this.audioLevelsIntervalId = null;
  10740. }
  10741. if (this.statsIntervalId)
  10742. {
  10743. clearInterval(this.statsIntervalId);
  10744. this.statsIntervalId = null;
  10745. }
  10746. if(this.logStatsIntervalId)
  10747. {
  10748. clearInterval(this.logStatsIntervalId);
  10749. this.logStatsIntervalId = null;
  10750. }
  10751. if(this.gatherStatsIntervalId)
  10752. {
  10753. clearInterval(this.gatherStatsIntervalId);
  10754. this.gatherStatsIntervalId = null;
  10755. }
  10756. };
  10757. /**
  10758. * Callback passed to <tt>getStats</tt> method.
  10759. * @param error an error that occurred on <tt>getStats</tt> call.
  10760. */
  10761. StatsCollector.prototype.errorCallback = function (error)
  10762. {
  10763. console.error("Get stats error", error);
  10764. this.stop();
  10765. };
  10766. /**
  10767. * Starts stats updates.
  10768. */
  10769. StatsCollector.prototype.start = function ()
  10770. {
  10771. var self = this;
  10772. if (!config.disableAudioLevels) {
  10773. this.audioLevelsIntervalId = setInterval(
  10774. function () {
  10775. // Interval updates
  10776. self.peerconnection.getStats(
  10777. function (report) {
  10778. var results = null;
  10779. if (!report || !report.result ||
  10780. typeof report.result != 'function') {
  10781. results = report;
  10782. }
  10783. else {
  10784. results = report.result();
  10785. }
  10786. //console.error("Got interval report", results);
  10787. self.currentAudioLevelsReport = results;
  10788. self.processAudioLevelReport();
  10789. self.baselineAudioLevelsReport =
  10790. self.currentAudioLevelsReport;
  10791. },
  10792. self.errorCallback
  10793. );
  10794. },
  10795. self.audioLevelsIntervalMilis
  10796. );
  10797. }
  10798. if (!config.disableStats && browserSupported) {
  10799. this.statsIntervalId = setInterval(
  10800. function () {
  10801. // Interval updates
  10802. self.peerconnection.getStats(
  10803. function (report) {
  10804. var results = null;
  10805. if (!report || !report.result ||
  10806. typeof report.result != 'function') {
  10807. //firefox
  10808. results = report;
  10809. }
  10810. else {
  10811. //chrome
  10812. results = report.result();
  10813. }
  10814. //console.error("Got interval report", results);
  10815. self.currentStatsReport = results;
  10816. try {
  10817. self.processStatsReport();
  10818. }
  10819. catch (e) {
  10820. console.error("Unsupported key:" + e, e);
  10821. }
  10822. self.baselineStatsReport = self.currentStatsReport;
  10823. },
  10824. self.errorCallback
  10825. );
  10826. },
  10827. self.statsIntervalMilis
  10828. );
  10829. }
  10830. if (config.logStats && (browserSupported && !RTCBrowserType.isFirefox())) {
  10831. this.gatherStatsIntervalId = setInterval(
  10832. function () {
  10833. self.peerconnection.getStats(
  10834. function (report) {
  10835. self.addStatsToBeLogged(report.result());
  10836. },
  10837. function () {
  10838. }
  10839. );
  10840. },
  10841. this.GATHER_INTERVAL
  10842. );
  10843. this.logStatsIntervalId = setInterval(
  10844. function() { self.logStats(); },
  10845. this.LOG_INTERVAL);
  10846. }
  10847. };
  10848. /**
  10849. * Checks whether a certain record should be included in the logged statistics.
  10850. */
  10851. function acceptStat(reportId, reportType, statName) {
  10852. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10853. return false;
  10854. if (reportType == "ssrc") {
  10855. if (statName == "googTrackId" ||
  10856. statName == "transportId" ||
  10857. statName == "ssrc")
  10858. return false;
  10859. }
  10860. return true;
  10861. }
  10862. /**
  10863. * Checks whether a certain record should be included in the logged statistics.
  10864. */
  10865. function acceptReport(id, type) {
  10866. if (id.substring(0, 15) == "googCertificate" ||
  10867. id.substring(0, 9) == "googTrack" ||
  10868. id.substring(0, 20) == "googLibjingleSession")
  10869. return false;
  10870. if (type == "googComponent")
  10871. return false;
  10872. return true;
  10873. }
  10874. /**
  10875. * Converts the stats to the format used for logging, and saves the data in
  10876. * this.statsToBeLogged.
  10877. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10878. */
  10879. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10880. var self = this;
  10881. var num_records = this.statsToBeLogged.timestamps.length;
  10882. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10883. reports.map(function (report) {
  10884. if (!acceptReport(report.id, report.type))
  10885. return;
  10886. var stat = self.statsToBeLogged.stats[report.id];
  10887. if (!stat) {
  10888. stat = self.statsToBeLogged.stats[report.id] = {};
  10889. }
  10890. stat.type = report.type;
  10891. report.names().map(function (name) {
  10892. if (!acceptStat(report.id, report.type, name))
  10893. return;
  10894. var values = stat[name];
  10895. if (!values) {
  10896. values = stat[name] = [];
  10897. }
  10898. while (values.length < num_records) {
  10899. values.push(null);
  10900. }
  10901. values.push(report.stat(name));
  10902. });
  10903. });
  10904. };
  10905. StatsCollector.prototype.logStats = function () {
  10906. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10907. return;
  10908. // Reset the stats
  10909. this.statsToBeLogged.stats = {};
  10910. this.statsToBeLogged.timestamps = [];
  10911. };
  10912. var keyMap = {};
  10913. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10914. "ssrc": "ssrc",
  10915. "packetsReceived": "packetsReceived",
  10916. "packetsLost": "packetsLost",
  10917. "packetsSent": "packetsSent",
  10918. "bytesReceived": "bytesReceived",
  10919. "bytesSent": "bytesSent"
  10920. };
  10921. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10922. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10923. "sendBandwidth": "googAvailableSendBandwidth",
  10924. "remoteAddress": "googRemoteAddress",
  10925. "transportType": "googTransportType",
  10926. "localAddress": "googLocalAddress",
  10927. "activeConnection": "googActiveConnection",
  10928. "ssrc": "ssrc",
  10929. "packetsReceived": "packetsReceived",
  10930. "packetsSent": "packetsSent",
  10931. "packetsLost": "packetsLost",
  10932. "bytesReceived": "bytesReceived",
  10933. "bytesSent": "bytesSent",
  10934. "googFrameHeightReceived": "googFrameHeightReceived",
  10935. "googFrameWidthReceived": "googFrameWidthReceived",
  10936. "googFrameHeightSent": "googFrameHeightSent",
  10937. "googFrameWidthSent": "googFrameWidthSent",
  10938. "audioInputLevel": "audioInputLevel",
  10939. "audioOutputLevel": "audioOutputLevel"
  10940. };
  10941. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  10942. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  10943. /**
  10944. * Stats processing logic.
  10945. */
  10946. StatsCollector.prototype.processStatsReport = function () {
  10947. if (!this.baselineStatsReport) {
  10948. return;
  10949. }
  10950. for (var idx in this.currentStatsReport) {
  10951. var now = this.currentStatsReport[idx];
  10952. try {
  10953. if (getStatValue(now, 'receiveBandwidth') ||
  10954. getStatValue(now, 'sendBandwidth')) {
  10955. PeerStats.bandwidth = {
  10956. "download": Math.round(
  10957. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10958. "upload": Math.round(
  10959. (getStatValue(now, 'sendBandwidth')) / 1000)
  10960. };
  10961. }
  10962. }
  10963. catch(e){/*not supported*/}
  10964. if(now.type == 'googCandidatePair')
  10965. {
  10966. var ip, type, localIP, active;
  10967. try {
  10968. ip = getStatValue(now, 'remoteAddress');
  10969. type = getStatValue(now, "transportType");
  10970. localIP = getStatValue(now, "localAddress");
  10971. active = getStatValue(now, "activeConnection");
  10972. }
  10973. catch(e){/*not supported*/}
  10974. if(!ip || !type || !localIP || active != "true")
  10975. continue;
  10976. var addressSaved = false;
  10977. for(var i = 0; i < PeerStats.transport.length; i++)
  10978. {
  10979. if(PeerStats.transport[i].ip == ip &&
  10980. PeerStats.transport[i].type == type &&
  10981. PeerStats.transport[i].localip == localIP)
  10982. {
  10983. addressSaved = true;
  10984. }
  10985. }
  10986. if(addressSaved)
  10987. continue;
  10988. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10989. continue;
  10990. }
  10991. if(now.type == "candidatepair")
  10992. {
  10993. if(now.state == "succeeded")
  10994. continue;
  10995. var local = this.currentStatsReport[now.localCandidateId];
  10996. var remote = this.currentStatsReport[now.remoteCandidateId];
  10997. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10998. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10999. }
  11000. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11001. now.type != "inboundrtp") {
  11002. continue;
  11003. }
  11004. var before = this.baselineStatsReport[idx];
  11005. if (!before) {
  11006. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11007. continue;
  11008. }
  11009. var ssrc = getStatValue(now, 'ssrc');
  11010. if(!ssrc)
  11011. continue;
  11012. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11013. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11014. console.warn("No jid for ssrc: " + ssrc);
  11015. continue;
  11016. }
  11017. var jidStats = this.jid2stats[jid];
  11018. if (!jidStats) {
  11019. jidStats = new PeerStats();
  11020. this.jid2stats[jid] = jidStats;
  11021. }
  11022. var isDownloadStream = true;
  11023. var key = 'packetsReceived';
  11024. if (!getStatValue(now, key))
  11025. {
  11026. isDownloadStream = false;
  11027. key = 'packetsSent';
  11028. if (!getStatValue(now, key))
  11029. {
  11030. console.warn("No packetsReceived nor packetSent stat found");
  11031. continue;
  11032. }
  11033. }
  11034. var packetsNow = getStatValue(now, key);
  11035. if(!packetsNow || packetsNow < 0)
  11036. packetsNow = 0;
  11037. var packetsBefore = getStatValue(before, key);
  11038. if(!packetsBefore || packetsBefore < 0)
  11039. packetsBefore = 0;
  11040. var packetRate = packetsNow - packetsBefore;
  11041. if(!packetRate || packetRate < 0)
  11042. packetRate = 0;
  11043. var currentLoss = getStatValue(now, 'packetsLost');
  11044. if(!currentLoss || currentLoss < 0)
  11045. currentLoss = 0;
  11046. var previousLoss = getStatValue(before, 'packetsLost');
  11047. if(!previousLoss || previousLoss < 0)
  11048. previousLoss = 0;
  11049. var lossRate = currentLoss - previousLoss;
  11050. if(!lossRate || lossRate < 0)
  11051. lossRate = 0;
  11052. var packetsTotal = (packetRate + lossRate);
  11053. jidStats.setSsrcLoss(ssrc,
  11054. {"packetsTotal": packetsTotal,
  11055. "packetsLost": lossRate,
  11056. "isDownloadStream": isDownloadStream});
  11057. var bytesReceived = 0, bytesSent = 0;
  11058. if(getStatValue(now, "bytesReceived"))
  11059. {
  11060. bytesReceived = getStatValue(now, "bytesReceived") -
  11061. getStatValue(before, "bytesReceived");
  11062. }
  11063. if(getStatValue(now, "bytesSent"))
  11064. {
  11065. bytesSent = getStatValue(now, "bytesSent") -
  11066. getStatValue(before, "bytesSent");
  11067. }
  11068. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11069. if(bytesReceived <= 0 || time <= 0)
  11070. {
  11071. bytesReceived = 0;
  11072. }
  11073. else
  11074. {
  11075. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11076. }
  11077. if(bytesSent <= 0 || time <= 0)
  11078. {
  11079. bytesSent = 0;
  11080. }
  11081. else
  11082. {
  11083. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11084. }
  11085. jidStats.setSsrcBitrate(ssrc, {
  11086. "download": bytesReceived,
  11087. "upload": bytesSent});
  11088. var resolution = {height: null, width: null};
  11089. try {
  11090. if (getStatValue(now, "googFrameHeightReceived") &&
  11091. getStatValue(now, "googFrameWidthReceived")) {
  11092. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11093. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11094. }
  11095. else if (getStatValue(now, "googFrameHeightSent") &&
  11096. getStatValue(now, "googFrameWidthSent")) {
  11097. resolution.height = getStatValue(now, "googFrameHeightSent");
  11098. resolution.width = getStatValue(now, "googFrameWidthSent");
  11099. }
  11100. }
  11101. catch(e){/*not supported*/}
  11102. if(resolution.height && resolution.width)
  11103. {
  11104. jidStats.setSsrcResolution(ssrc, resolution);
  11105. }
  11106. else
  11107. {
  11108. jidStats.setSsrcResolution(ssrc, null);
  11109. }
  11110. }
  11111. var self = this;
  11112. // Jid stats
  11113. var totalPackets = {download: 0, upload: 0};
  11114. var lostPackets = {download: 0, upload: 0};
  11115. var bitrateDownload = 0;
  11116. var bitrateUpload = 0;
  11117. var resolutions = {};
  11118. Object.keys(this.jid2stats).forEach(
  11119. function (jid)
  11120. {
  11121. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11122. function (ssrc)
  11123. {
  11124. var type = "upload";
  11125. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11126. type = "download";
  11127. totalPackets[type] +=
  11128. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11129. lostPackets[type] +=
  11130. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11131. }
  11132. );
  11133. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11134. function (ssrc) {
  11135. bitrateDownload +=
  11136. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11137. bitrateUpload +=
  11138. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11139. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11140. }
  11141. );
  11142. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11143. }
  11144. );
  11145. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11146. PeerStats.packetLoss = {
  11147. total:
  11148. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11149. totalPackets.download + totalPackets.upload),
  11150. download:
  11151. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11152. upload:
  11153. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11154. };
  11155. this.eventEmitter.emit("statistics.connectionstats",
  11156. {
  11157. "bitrate": PeerStats.bitrate,
  11158. "packetLoss": PeerStats.packetLoss,
  11159. "bandwidth": PeerStats.bandwidth,
  11160. "resolution": resolutions,
  11161. "transport": PeerStats.transport
  11162. });
  11163. PeerStats.transport = [];
  11164. };
  11165. /**
  11166. * Stats processing logic.
  11167. */
  11168. StatsCollector.prototype.processAudioLevelReport = function () {
  11169. if (!this.baselineAudioLevelsReport) {
  11170. return;
  11171. }
  11172. for (var idx in this.currentAudioLevelsReport) {
  11173. var now = this.currentAudioLevelsReport[idx];
  11174. if (now.type != 'ssrc') {
  11175. continue;
  11176. }
  11177. var before = this.baselineAudioLevelsReport[idx];
  11178. if (!before) {
  11179. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11180. continue;
  11181. }
  11182. var ssrc = getStatValue(now, 'ssrc');
  11183. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11184. if (!jid) {
  11185. if((Date.now() - now.timestamp) < 3000)
  11186. console.warn("No jid for ssrc: " + ssrc);
  11187. continue;
  11188. }
  11189. var jidStats = this.jid2stats[jid];
  11190. if (!jidStats) {
  11191. jidStats = new PeerStats();
  11192. this.jid2stats[jid] = jidStats;
  11193. }
  11194. // Audio level
  11195. var audioLevel = null;
  11196. try {
  11197. audioLevel = getStatValue(now, 'audioInputLevel');
  11198. if (!audioLevel)
  11199. audioLevel = getStatValue(now, 'audioOutputLevel');
  11200. }
  11201. catch(e) {/*not supported*/
  11202. console.warn("Audio Levels are not available in the statistics.");
  11203. clearInterval(this.audioLevelsIntervalId);
  11204. return;
  11205. }
  11206. if (audioLevel) {
  11207. // TODO: can't find specs about what this value really is,
  11208. // but it seems to vary between 0 and around 32k.
  11209. audioLevel = audioLevel / 32767;
  11210. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11211. if(jid != APP.xmpp.myJid())
  11212. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11213. }
  11214. }
  11215. };
  11216. },{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){
  11217. /* global require, APP */
  11218. /**
  11219. * Created by hristo on 8/4/14.
  11220. */
  11221. var LocalStats = require("./LocalStatsCollector.js");
  11222. var RTPStats = require("./RTPStatsCollector.js");
  11223. var EventEmitter = require("events");
  11224. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11225. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11226. var CallStats = require("./CallStats");
  11227. var RTCEvents = require("../../service/RTC/RTCEvents");
  11228. var eventEmitter = new EventEmitter();
  11229. var localStats = null;
  11230. var rtpStats = null;
  11231. function stopLocal() {
  11232. if (localStats) {
  11233. localStats.stop();
  11234. localStats = null;
  11235. }
  11236. }
  11237. function stopRemote() {
  11238. if (rtpStats) {
  11239. rtpStats.stop();
  11240. eventEmitter.emit("statistics.stop");
  11241. rtpStats = null;
  11242. }
  11243. }
  11244. function startRemoteStats (peerconnection) {
  11245. if (rtpStats) {
  11246. rtpStats.stop();
  11247. }
  11248. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11249. rtpStats.start();
  11250. }
  11251. function onStreamCreated(stream) {
  11252. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11253. return;
  11254. }
  11255. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11256. eventEmitter);
  11257. localStats.start();
  11258. }
  11259. function onDisposeConference(onUnload) {
  11260. CallStats.sendTerminateEvent();
  11261. stopRemote();
  11262. if(onUnload) {
  11263. stopLocal();
  11264. eventEmitter.removeAllListeners();
  11265. }
  11266. }
  11267. var statistics = {
  11268. /**
  11269. * Indicates that this audio level is for local jid.
  11270. * @type {string}
  11271. */
  11272. LOCAL_JID: 'local',
  11273. addAudioLevelListener: function(listener)
  11274. {
  11275. eventEmitter.on("statistics.audioLevel", listener);
  11276. },
  11277. removeAudioLevelListener: function(listener)
  11278. {
  11279. eventEmitter.removeListener("statistics.audioLevel", listener);
  11280. },
  11281. addConnectionStatsListener: function(listener)
  11282. {
  11283. eventEmitter.on("statistics.connectionstats", listener);
  11284. },
  11285. removeConnectionStatsListener: function(listener)
  11286. {
  11287. eventEmitter.removeListener("statistics.connectionstats", listener);
  11288. },
  11289. addRemoteStatsStopListener: function(listener)
  11290. {
  11291. eventEmitter.on("statistics.stop", listener);
  11292. },
  11293. removeRemoteStatsStopListener: function(listener)
  11294. {
  11295. eventEmitter.removeListener("statistics.stop", listener);
  11296. },
  11297. stop: function () {
  11298. stopLocal();
  11299. stopRemote();
  11300. if(eventEmitter)
  11301. {
  11302. eventEmitter.removeAllListeners();
  11303. }
  11304. },
  11305. stopRemoteStatistics: function()
  11306. {
  11307. stopRemote();
  11308. },
  11309. start: function () {
  11310. APP.RTC.addStreamListener(onStreamCreated,
  11311. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11312. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11313. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11314. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11315. startRemoteStats(event.peerconnection);
  11316. // CallStats.init(event);
  11317. });
  11318. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11319. CallStats.init(session);
  11320. });
  11321. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11322. CallStats.sendMuteEvent(mute, "audio");
  11323. });
  11324. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11325. CallStats.sendSetupFailedEvent();
  11326. });
  11327. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11328. CallStats.sendMuteEvent(mute, "video");
  11329. });
  11330. }
  11331. };
  11332. module.exports = statistics;
  11333. },{"../../service/RTC/RTCEvents":160,"../../service/RTC/StreamEventTypes.js":162,"../../service/xmpp/XMPPEvents":169,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":170}],52:[function(require,module,exports){
  11334. /* global $, require, config, interfaceConfig */
  11335. var i18n = require("i18next-client");
  11336. var languages = require("../../service/translation/languages");
  11337. var Settings = require("../settings/Settings");
  11338. var DEFAULT_LANG = languages.EN;
  11339. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11340. return value.replace("__app__", interfaceConfig.APP_NAME);
  11341. });
  11342. var defaultOptions = {
  11343. detectLngQS: "lang",
  11344. useCookie: false,
  11345. fallbackLng: DEFAULT_LANG,
  11346. load: "unspecific",
  11347. resGetPath: 'lang/__ns__-__lng__.json',
  11348. ns: {
  11349. namespaces: ['main', 'languages'],
  11350. defaultNs: 'main'
  11351. },
  11352. lngWhitelist : languages.getLanguages(),
  11353. fallbackOnNull: true,
  11354. fallbackOnEmpty: true,
  11355. useDataAttrOptions: true,
  11356. app: interfaceConfig.APP_NAME,
  11357. getAsync: false,
  11358. defaultValueFromContent: false,
  11359. customLoad: function(lng, ns, options, done) {
  11360. var resPath = "lang/__ns__-__lng__.json";
  11361. if(lng === languages.EN)
  11362. resPath = "lang/__ns__.json";
  11363. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11364. i18n.functions.ajax({
  11365. url: url,
  11366. success: function(data, status, xhr) {
  11367. i18n.functions.log('loaded: ' + url);
  11368. done(null, data);
  11369. },
  11370. error : function(xhr, status, error) {
  11371. if ((status && status == 200) ||
  11372. (xhr && xhr.status && xhr.status == 200)) {
  11373. // file loaded but invalid json, stop waste time !
  11374. i18n.functions.error('There is a typo in: ' + url);
  11375. } else if ((status && status == 404) ||
  11376. (xhr && xhr.status && xhr.status == 404)) {
  11377. i18n.functions.log('Does not exist: ' + url);
  11378. } else {
  11379. var theStatus = status ? status :
  11380. ((xhr && xhr.status) ? xhr.status : null);
  11381. i18n.functions.log(theStatus + ' when loading ' + url);
  11382. }
  11383. done(error, {});
  11384. },
  11385. dataType: "json",
  11386. async : options.getAsync
  11387. });
  11388. }
  11389. // options for caching
  11390. // useLocalStorage: true,
  11391. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11392. };
  11393. function initCompleted(t) {
  11394. $("[data-i18n]").i18n();
  11395. }
  11396. function checkForParameter() {
  11397. var query = window.location.search.substring(1);
  11398. var vars = query.split("&");
  11399. for (var i=0;i<vars.length;i++) {
  11400. var pair = vars[i].split("=");
  11401. if(pair[0] == "lang")
  11402. {
  11403. return pair[1];
  11404. }
  11405. }
  11406. return null;
  11407. }
  11408. module.exports = {
  11409. init: function (lang) {
  11410. var options = defaultOptions;
  11411. if(!lang)
  11412. {
  11413. lang = checkForParameter();
  11414. if(!lang)
  11415. {
  11416. var settings = Settings.getSettings();
  11417. if(settings)
  11418. lang = settings.language;
  11419. if(!lang && config.defaultLanguage)
  11420. {
  11421. lang = config.defaultLanguage;
  11422. }
  11423. }
  11424. }
  11425. if(lang) {
  11426. options.lng = lang;
  11427. }
  11428. i18n.init(options, initCompleted);
  11429. },
  11430. translateString: function (key, options) {
  11431. return i18n.t(key, options);
  11432. },
  11433. setLanguage: function (lang) {
  11434. if(!lang)
  11435. lang = DEFAULT_LANG;
  11436. i18n.setLng(lang, defaultOptions, initCompleted);
  11437. },
  11438. getCurrentLanguage: function () {
  11439. return i18n.lng();
  11440. },
  11441. translateElement: function (selector) {
  11442. selector.i18n();
  11443. },
  11444. generateTranslationHTML: function (key, options) {
  11445. var str = "<span data-i18n=\"" + key + "\"";
  11446. if(options)
  11447. {
  11448. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11449. }
  11450. str += ">";
  11451. str += this.translateString(key, options);
  11452. str += "</span>";
  11453. return str;
  11454. }
  11455. };
  11456. },{"../../service/translation/languages":168,"../settings/Settings":47,"i18next-client":70}],53:[function(require,module,exports){
  11457. /*
  11458. * JingleSession provides an API to manage a single Jingle session. We will
  11459. * have different implementations depending on the underlying interface used
  11460. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  11461. */
  11462. function JingleSession(me, sid, connection, service, eventEmitter) {
  11463. /**
  11464. * Our JID.
  11465. */
  11466. this.me = me;
  11467. /**
  11468. * The Jingle session identifier.
  11469. */
  11470. this.sid = sid;
  11471. /**
  11472. * The XMPP connection.
  11473. */
  11474. this.connection = connection;
  11475. /**
  11476. * The XMPP service.
  11477. */
  11478. this.service = service;
  11479. /**
  11480. * The event emitter.
  11481. */
  11482. this.eventEmitter = eventEmitter;
  11483. /**
  11484. * Whether to use dripping or not. Dripping is sending trickle candidates
  11485. * not one-by-one.
  11486. * Note: currently we do not support 'false'.
  11487. */
  11488. this.usedrip = true;
  11489. /**
  11490. * When dripping is used, stores ICE candidates which are to be sent.
  11491. */
  11492. this.drip_container = [];
  11493. // Media constraints. Is this WebRTC only?
  11494. this.media_constraints = null;
  11495. // ICE servers config (RTCConfiguration?).
  11496. this.ice_config = {};
  11497. }
  11498. /**
  11499. * Prepares this object to initiate a session.
  11500. * @param peerjid the JID of the remote peer.
  11501. * @param isInitiator whether we will be the Jingle initiator.
  11502. * @param media_constraints
  11503. * @param ice_config
  11504. */
  11505. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  11506. media_constraints, ice_config) {
  11507. this.media_constraints = media_constraints;
  11508. this.ice_config = ice_config;
  11509. if (this.state !== null) {
  11510. console.error('attempt to initiate on session ' + this.sid +
  11511. 'in state ' + this.state);
  11512. return;
  11513. }
  11514. this.state = 'pending';
  11515. this.initiator = isInitiator ? this.me : peerjid;
  11516. this.responder = !isInitiator ? this.me : peerjid;
  11517. this.peerjid = peerjid;
  11518. this.doInitialize();
  11519. };
  11520. /**
  11521. * Finishes initialization.
  11522. */
  11523. JingleSession.prototype.doInitialize = function() {};
  11524. /**
  11525. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  11526. * Note: currently only used on transport-info
  11527. */
  11528. JingleSession.prototype.addIceCandidates = function(contents) {};
  11529. /**
  11530. * Handles an 'add-source' event.
  11531. *
  11532. * @param contents an array of Jingle 'content' elements.
  11533. */
  11534. JingleSession.prototype.addSources = function(contents) {};
  11535. /**
  11536. * Handles a 'remove-source' event.
  11537. *
  11538. * @param contents an array of Jingle 'content' elements.
  11539. */
  11540. JingleSession.prototype.removeSources = function(contents) {};
  11541. /**
  11542. * Terminates this Jingle session (stops sending media and closes the streams?)
  11543. */
  11544. JingleSession.prototype.terminate = function() {};
  11545. /**
  11546. * Sends a Jingle session-terminate message to the peer and terminates the
  11547. * session.
  11548. * @param reason
  11549. * @param text
  11550. */
  11551. JingleSession.prototype.sendTerminate = function(reason, text) {};
  11552. /**
  11553. * Handles an offer from the remote peer (prepares to accept a session).
  11554. * @param jingle the 'jingle' XML element.
  11555. */
  11556. JingleSession.prototype.setOffer = function(jingle) {};
  11557. /**
  11558. * Handles an answer from the remote peer (prepares to accept a session).
  11559. * @param jingle the 'jingle' XML element.
  11560. */
  11561. JingleSession.prototype.setAnswer = function(jingle) {};
  11562. module.exports = JingleSession;
  11563. },{}],54:[function(require,module,exports){
  11564. /* jshint -W117 */
  11565. var JingleSession = require("./JingleSession");
  11566. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11567. var SDPDiffer = require("./SDPDiffer");
  11568. var SDPUtil = require("./SDPUtil");
  11569. var SDP = require("./SDP");
  11570. var async = require("async");
  11571. var transform = require("sdp-transform");
  11572. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11573. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11574. var SSRCReplacement = require("./LocalSSRCReplacement");
  11575. // Jingle stuff
  11576. function JingleSessionPC(me, sid, connection, service, eventEmitter) {
  11577. JingleSession.call(this, me, sid, connection, service, eventEmitter);
  11578. this.initiator = null;
  11579. this.responder = null;
  11580. this.peerjid = null;
  11581. this.state = null;
  11582. this.localSDP = null;
  11583. this.remoteSDP = null;
  11584. this.relayedStreams = [];
  11585. this.pc_constraints = null;
  11586. this.usetrickle = true;
  11587. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11588. this.hadstuncandidate = false;
  11589. this.hadturncandidate = false;
  11590. this.lasticecandidate = false;
  11591. this.statsinterval = null;
  11592. this.reason = null;
  11593. this.addssrc = [];
  11594. this.removessrc = [];
  11595. this.pendingop = null;
  11596. this.switchstreams = false;
  11597. this.wait = true;
  11598. this.localStreamsSSRC = null;
  11599. this.ssrcOwners = {};
  11600. this.ssrcVideoTypes = {};
  11601. this.eventEmitter = eventEmitter;
  11602. /**
  11603. * The indicator which determines whether the (local) video has been muted
  11604. * in response to a user command in contrast to an automatic decision made
  11605. * by the application logic.
  11606. */
  11607. this.videoMuteByUser = false;
  11608. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11609. // We start with the queue paused. We resume it when the signaling state is
  11610. // stable and the ice connection state is connected.
  11611. this.modifySourcesQueue.pause();
  11612. }
  11613. JingleSessionPC.prototype = JingleSession.prototype;
  11614. JingleSessionPC.prototype.constructor = JingleSessionPC;
  11615. JingleSessionPC.prototype.setOffer = function(offer) {
  11616. this.setRemoteDescription(offer, 'offer');
  11617. };
  11618. JingleSessionPC.prototype.setAnswer = function(answer) {
  11619. this.setRemoteDescription(answer, 'answer');
  11620. };
  11621. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  11622. var signalingState = this.peerconnection.signalingState;
  11623. var iceConnectionState = this.peerconnection.iceConnectionState;
  11624. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11625. this.modifySourcesQueue.resume();
  11626. } else {
  11627. this.modifySourcesQueue.pause();
  11628. }
  11629. };
  11630. JingleSessionPC.prototype.doInitialize = function () {
  11631. var self = this;
  11632. this.hadstuncandidate = false;
  11633. this.hadturncandidate = false;
  11634. this.lasticecandidate = false;
  11635. this.isreconnect = false;
  11636. this.peerconnection = new TraceablePeerConnection(
  11637. this.connection.jingle.ice_config,
  11638. this.connection.jingle.pc_constraints,
  11639. this);
  11640. this.peerconnection.onicecandidate = function (event) {
  11641. self.sendIceCandidate(event.candidate);
  11642. };
  11643. this.peerconnection.onaddstream = function (event) {
  11644. if (event.stream.id !== 'default') {
  11645. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11646. self.remoteStreamAdded(event);
  11647. } else {
  11648. // This is a recvonly stream. Clients that implement Unified Plan,
  11649. // such as Firefox use recvonly "streams/channels/tracks" for
  11650. // receiving remote stream/tracks, as opposed to Plan B where there
  11651. // are only 3 channels: audio, video and data.
  11652. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11653. }
  11654. };
  11655. this.peerconnection.onremovestream = function (event) {
  11656. // Remove the stream from remoteStreams
  11657. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11658. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11659. };
  11660. this.peerconnection.onsignalingstatechange = function (event) {
  11661. if (!(self && self.peerconnection)) return;
  11662. self.updateModifySourcesQueue();
  11663. };
  11664. /**
  11665. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  11666. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  11667. * RTCPeerConnection.iceConnectionState changes.
  11668. *
  11669. * @param event the event containing information about the change
  11670. */
  11671. this.peerconnection.oniceconnectionstatechange = function (event) {
  11672. if (!(self && self.peerconnection)) return;
  11673. self.updateModifySourcesQueue();
  11674. switch (self.peerconnection.iceConnectionState) {
  11675. case 'connected':
  11676. // Informs interested parties that the connection has been restored.
  11677. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  11678. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  11679. self.isreconnect = false;
  11680. break;
  11681. case 'disconnected':
  11682. self.isreconnect = true;
  11683. // Informs interested parties that the connection has been interrupted.
  11684. if (self.peerconnection.signalingState === 'stable')
  11685. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  11686. break;
  11687. case 'failed':
  11688. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11689. break;
  11690. }
  11691. onIceConnectionStateChange(self.sid, self);
  11692. };
  11693. this.peerconnection.onnegotiationneeded = function (event) {
  11694. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11695. };
  11696. // add any local and relayed stream
  11697. APP.RTC.localStreams.forEach(function(stream) {
  11698. self.peerconnection.addStream(stream.getOriginalStream());
  11699. });
  11700. this.relayedStreams.forEach(function(stream) {
  11701. self.peerconnection.addStream(stream);
  11702. });
  11703. };
  11704. function onIceConnectionStateChange(sid, session) {
  11705. switch (session.peerconnection.iceConnectionState) {
  11706. case 'checking':
  11707. session.timeChecking = (new Date()).getTime();
  11708. session.firstconnect = true;
  11709. break;
  11710. case 'completed': // on caller side
  11711. case 'connected':
  11712. if (session.firstconnect) {
  11713. session.firstconnect = false;
  11714. var metadata = {};
  11715. metadata.setupTime
  11716. = (new Date()).getTime() - session.timeChecking;
  11717. session.peerconnection.getStats(function (res) {
  11718. if(res && res.result) {
  11719. res.result().forEach(function (report) {
  11720. if (report.type == 'googCandidatePair' &&
  11721. report.stat('googActiveConnection') == 'true') {
  11722. metadata.localCandidateType
  11723. = report.stat('googLocalCandidateType');
  11724. metadata.remoteCandidateType
  11725. = report.stat('googRemoteCandidateType');
  11726. // log pair as well so we can get nice pie
  11727. // charts
  11728. metadata.candidatePair
  11729. = report.stat('googLocalCandidateType') +
  11730. ';' +
  11731. report.stat('googRemoteCandidateType');
  11732. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11733. {
  11734. metadata.ipv6 = true;
  11735. }
  11736. }
  11737. });
  11738. }
  11739. });
  11740. }
  11741. break;
  11742. }
  11743. }
  11744. JingleSessionPC.prototype.accept = function () {
  11745. this.state = 'active';
  11746. var pranswer = this.peerconnection.localDescription;
  11747. if (!pranswer || pranswer.type != 'pranswer') {
  11748. return;
  11749. }
  11750. console.log('going from pranswer to answer');
  11751. if (this.usetrickle) {
  11752. // remove candidates already sent from session-accept
  11753. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11754. for (var i = 0; i < lines.length; i++) {
  11755. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11756. }
  11757. }
  11758. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11759. // FIXME: change any inactive to sendrecv or whatever they were originally
  11760. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11761. }
  11762. var prsdp = new SDP(pranswer.sdp);
  11763. var accept = $iq({to: this.peerjid,
  11764. type: 'set'})
  11765. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11766. action: 'session-accept',
  11767. initiator: this.initiator,
  11768. responder: this.responder,
  11769. sid: this.sid });
  11770. // FIXME why do we generate session-accept in 3 different places ?
  11771. prsdp.toJingle(
  11772. accept,
  11773. this.initiator == this.me ? 'initiator' : 'responder',
  11774. this.localStreamsSSRC);
  11775. var sdp = this.peerconnection.localDescription.sdp;
  11776. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11777. // FIXME: change any inactive to sendrecv or whatever they were originally
  11778. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11779. }
  11780. var self = this;
  11781. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11782. function () {
  11783. //console.log('setLocalDescription success');
  11784. self.setLocalDescription();
  11785. SSRCReplacement.processSessionInit(accept);
  11786. self.connection.sendIQ(accept,
  11787. function () {
  11788. var ack = {};
  11789. ack.source = 'answer';
  11790. $(document).trigger('ack.jingle', [self.sid, ack]);
  11791. },
  11792. function (stanza) {
  11793. var error = ($(stanza).find('error').length) ? {
  11794. code: $(stanza).find('error').attr('code'),
  11795. reason: $(stanza).find('error :first')[0].tagName
  11796. }:{};
  11797. error.source = 'answer';
  11798. JingleSessionPC.onJingleError(self.sid, error);
  11799. },
  11800. 10000);
  11801. },
  11802. function (e) {
  11803. console.error('setLocalDescription failed', e);
  11804. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11805. }
  11806. );
  11807. };
  11808. JingleSessionPC.prototype.terminate = function (reason) {
  11809. this.state = 'ended';
  11810. this.reason = reason;
  11811. this.peerconnection.close();
  11812. if (this.statsinterval !== null) {
  11813. window.clearInterval(this.statsinterval);
  11814. this.statsinterval = null;
  11815. }
  11816. };
  11817. JingleSessionPC.prototype.active = function () {
  11818. return this.state == 'active';
  11819. };
  11820. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  11821. var self = this;
  11822. if (candidate && !this.lasticecandidate) {
  11823. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11824. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11825. if (!(ice && jcand)) {
  11826. console.error('failed to get ice && jcand');
  11827. return;
  11828. }
  11829. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11830. if (jcand.type === 'srflx') {
  11831. this.hadstuncandidate = true;
  11832. } else if (jcand.type === 'relay') {
  11833. this.hadturncandidate = true;
  11834. }
  11835. if (this.usetrickle) {
  11836. if (this.usedrip) {
  11837. if (this.drip_container.length === 0) {
  11838. // start 20ms callout
  11839. window.setTimeout(function () {
  11840. if (self.drip_container.length === 0) return;
  11841. self.sendIceCandidates(self.drip_container);
  11842. self.drip_container = [];
  11843. }, 20);
  11844. }
  11845. this.drip_container.push(candidate);
  11846. return;
  11847. } else {
  11848. self.sendIceCandidate([candidate]);
  11849. }
  11850. }
  11851. } else {
  11852. //console.log('sendIceCandidate: last candidate.');
  11853. if (!this.usetrickle) {
  11854. //console.log('should send full offer now...');
  11855. //FIXME why do we generate session-accept in 3 different places ?
  11856. var init = $iq({to: this.peerjid,
  11857. type: 'set'})
  11858. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11859. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11860. initiator: this.initiator,
  11861. sid: this.sid});
  11862. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11863. var sendJingle = function (ssrc) {
  11864. if(!ssrc)
  11865. ssrc = {};
  11866. self.localSDP.toJingle(
  11867. init,
  11868. self.initiator == self.me ? 'initiator' : 'responder',
  11869. ssrc);
  11870. SSRCReplacement.processSessionInit(init);
  11871. self.connection.sendIQ(init,
  11872. function () {
  11873. //console.log('session initiate ack');
  11874. var ack = {};
  11875. ack.source = 'offer';
  11876. $(document).trigger('ack.jingle', [self.sid, ack]);
  11877. },
  11878. function (stanza) {
  11879. self.state = 'error';
  11880. self.peerconnection.close();
  11881. var error = ($(stanza).find('error').length) ? {
  11882. code: $(stanza).find('error').attr('code'),
  11883. reason: $(stanza).find('error :first')[0].tagName,
  11884. }:{};
  11885. error.source = 'offer';
  11886. JingleSessionPC.onJingleError(self.sid, error);
  11887. },
  11888. 10000);
  11889. };
  11890. sendJingle();
  11891. }
  11892. this.lasticecandidate = true;
  11893. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11894. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11895. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11896. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11897. }
  11898. }
  11899. };
  11900. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  11901. console.log('sendIceCandidates', candidates);
  11902. var cand = $iq({to: this.peerjid, type: 'set'})
  11903. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11904. action: 'transport-info',
  11905. initiator: this.initiator,
  11906. sid: this.sid});
  11907. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11908. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11909. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11910. if (cands.length > 0) {
  11911. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11912. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11913. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11914. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11915. }).c('transport', ice);
  11916. for (var i = 0; i < cands.length; i++) {
  11917. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11918. }
  11919. // add fingerprint
  11920. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11921. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11922. tmp.required = true;
  11923. cand.c(
  11924. 'fingerprint',
  11925. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11926. .t(tmp.fingerprint);
  11927. delete tmp.fingerprint;
  11928. cand.attrs(tmp);
  11929. cand.up();
  11930. }
  11931. cand.up(); // transport
  11932. cand.up(); // content
  11933. }
  11934. }
  11935. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11936. //console.log('was this the last candidate', this.lasticecandidate);
  11937. this.connection.sendIQ(cand,
  11938. function () {
  11939. var ack = {};
  11940. ack.source = 'transportinfo';
  11941. $(document).trigger('ack.jingle', [this.sid, ack]);
  11942. },
  11943. function (stanza) {
  11944. var error = ($(stanza).find('error').length) ? {
  11945. code: $(stanza).find('error').attr('code'),
  11946. reason: $(stanza).find('error :first')[0].tagName,
  11947. }:{};
  11948. error.source = 'transportinfo';
  11949. JingleSessionPC.onJingleError(this.sid, error);
  11950. },
  11951. 10000);
  11952. };
  11953. JingleSessionPC.prototype.sendOffer = function () {
  11954. //console.log('sendOffer...');
  11955. var self = this;
  11956. this.peerconnection.createOffer(function (sdp) {
  11957. self.createdOffer(sdp);
  11958. },
  11959. function (e) {
  11960. console.error('createOffer failed', e);
  11961. },
  11962. this.media_constraints
  11963. );
  11964. };
  11965. // FIXME createdOffer is never used in jitsi-meet
  11966. JingleSessionPC.prototype.createdOffer = function (sdp) {
  11967. //console.log('createdOffer', sdp);
  11968. var self = this;
  11969. this.localSDP = new SDP(sdp.sdp);
  11970. //this.localSDP.mangle();
  11971. var sendJingle = function () {
  11972. var init = $iq({to: this.peerjid,
  11973. type: 'set'})
  11974. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11975. action: 'session-initiate',
  11976. initiator: this.initiator,
  11977. sid: this.sid});
  11978. self.localSDP.toJingle(
  11979. init,
  11980. this.initiator == this.me ? 'initiator' : 'responder',
  11981. this.localStreamsSSRC);
  11982. SSRCReplacement.processSessionInit(init);
  11983. self.connection.sendIQ(init,
  11984. function () {
  11985. var ack = {};
  11986. ack.source = 'offer';
  11987. $(document).trigger('ack.jingle', [self.sid, ack]);
  11988. },
  11989. function (stanza) {
  11990. self.state = 'error';
  11991. self.peerconnection.close();
  11992. var error = ($(stanza).find('error').length) ? {
  11993. code: $(stanza).find('error').attr('code'),
  11994. reason: $(stanza).find('error :first')[0].tagName,
  11995. }:{};
  11996. error.source = 'offer';
  11997. JingleSessionPC.onJingleError(self.sid, error);
  11998. },
  11999. 10000);
  12000. }
  12001. sdp.sdp = this.localSDP.raw;
  12002. this.peerconnection.setLocalDescription(sdp,
  12003. function () {
  12004. if(self.usetrickle)
  12005. {
  12006. sendJingle();
  12007. }
  12008. self.setLocalDescription();
  12009. //console.log('setLocalDescription success');
  12010. },
  12011. function (e) {
  12012. console.error('setLocalDescription failed', e);
  12013. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12014. }
  12015. );
  12016. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12017. for (var i = 0; i < cands.length; i++) {
  12018. var cand = SDPUtil.parse_icecandidate(cands[i]);
  12019. if (cand.type == 'srflx') {
  12020. this.hadstuncandidate = true;
  12021. } else if (cand.type == 'relay') {
  12022. this.hadturncandidate = true;
  12023. }
  12024. }
  12025. };
  12026. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  12027. var self = this;
  12028. $(contents).each(function (idx, content) {
  12029. var name = $(content).attr('name');
  12030. var mediaType = this.getAttribute('name');
  12031. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12032. ssrcs.each(function () {
  12033. var ssrc = this.getAttribute('ssrc');
  12034. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  12035. function () {
  12036. var owner = this.getAttribute('owner');
  12037. self.ssrcOwners[ssrc] = owner;
  12038. }
  12039. );
  12040. });
  12041. });
  12042. };
  12043. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  12044. return this.ssrcOwners[ssrc];
  12045. };
  12046. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  12047. //console.log('setting remote description... ', desctype);
  12048. this.remoteSDP = new SDP('');
  12049. this.remoteSDP.fromJingle(elem);
  12050. this.readSsrcInfo($(elem).find(">content"));
  12051. if (this.peerconnection.remoteDescription !== null) {
  12052. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12053. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12054. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12055. for (var i = 0; i < pranswer.media.length; i++) {
  12056. // make sure we have ice ufrag and pwd
  12057. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12058. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12059. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12060. } else {
  12061. console.warn('no ice ufrag?');
  12062. }
  12063. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12064. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12065. } else {
  12066. console.warn('no ice pwd?');
  12067. }
  12068. }
  12069. // copy over candidates
  12070. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12071. for (var j = 0; j < lines.length; j++) {
  12072. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12073. }
  12074. }
  12075. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12076. }
  12077. }
  12078. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12079. this.peerconnection.setRemoteDescription(remotedesc,
  12080. function () {
  12081. //console.log('setRemoteDescription success');
  12082. },
  12083. function (e) {
  12084. console.error('setRemoteDescription error', e);
  12085. JingleSessionPC.onJingleFatalError(self, e);
  12086. }
  12087. );
  12088. };
  12089. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  12090. var self = this;
  12091. if (this.peerconnection.signalingState == 'closed') {
  12092. return;
  12093. }
  12094. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12095. console.log('trickle ice candidate arriving before session accept...');
  12096. // create a PRANSWER for setRemoteDescription
  12097. if (!this.remoteSDP) {
  12098. var cobbled = 'v=0\r\n' +
  12099. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12100. 's=-\r\n' +
  12101. 't=0 0\r\n';
  12102. // first, take some things from the local description
  12103. for (var i = 0; i < this.localSDP.media.length; i++) {
  12104. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12105. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12106. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12107. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12108. }
  12109. cobbled += 'a=inactive\r\n';
  12110. }
  12111. this.remoteSDP = new SDP(cobbled);
  12112. }
  12113. // then add things like ice and dtls from remote candidate
  12114. elem.each(function () {
  12115. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12116. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12117. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12118. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12119. var tmp = $(this).find('transport');
  12120. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12121. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12122. tmp = $(this).find('transport>fingerprint');
  12123. if (tmp.length) {
  12124. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12125. } else {
  12126. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12127. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12128. }
  12129. break;
  12130. }
  12131. }
  12132. }
  12133. });
  12134. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12135. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12136. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12137. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12138. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12139. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12140. }).length == this.remoteSDP.media.length;
  12141. if (iscomplete) {
  12142. console.log('setting pranswer');
  12143. try {
  12144. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12145. function() {
  12146. },
  12147. function(e) {
  12148. console.log('setRemoteDescription pranswer failed', e.toString());
  12149. });
  12150. } catch (e) {
  12151. console.error('setting pranswer failed', e);
  12152. }
  12153. } else {
  12154. //console.log('not yet setting pranswer');
  12155. }
  12156. }
  12157. // operate on each content element
  12158. elem.each(function () {
  12159. // would love to deactivate this, but firefox still requires it
  12160. var idx = -1;
  12161. var i;
  12162. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12163. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12164. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12165. idx = i;
  12166. break;
  12167. }
  12168. }
  12169. if (idx == -1) { // fall back to localdescription
  12170. for (i = 0; i < self.localSDP.media.length; i++) {
  12171. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12172. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12173. idx = i;
  12174. break;
  12175. }
  12176. }
  12177. }
  12178. var name = $(this).attr('name');
  12179. // TODO: check ice-pwd and ice-ufrag?
  12180. $(this).find('transport>candidate').each(function () {
  12181. var line, candidate;
  12182. line = SDPUtil.candidateFromJingle(this);
  12183. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12184. sdpMid: name,
  12185. candidate: line});
  12186. try {
  12187. self.peerconnection.addIceCandidate(candidate);
  12188. } catch (e) {
  12189. console.error('addIceCandidate failed', e.toString(), line);
  12190. }
  12191. });
  12192. });
  12193. };
  12194. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  12195. //console.log('createAnswer', provisional);
  12196. var self = this;
  12197. this.peerconnection.createAnswer(
  12198. function (sdp) {
  12199. self.createdAnswer(sdp, provisional);
  12200. },
  12201. function (e) {
  12202. console.error('createAnswer failed', e);
  12203. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12204. },
  12205. this.media_constraints
  12206. );
  12207. };
  12208. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  12209. //console.log('createAnswer callback');
  12210. var self = this;
  12211. this.localSDP = new SDP(sdp.sdp);
  12212. //this.localSDP.mangle();
  12213. this.usepranswer = provisional === true;
  12214. if (this.usetrickle) {
  12215. if (this.usepranswer) {
  12216. sdp.type = 'pranswer';
  12217. for (var i = 0; i < this.localSDP.media.length; i++) {
  12218. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12219. }
  12220. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12221. }
  12222. }
  12223. var self = this;
  12224. var sendJingle = function (ssrcs) {
  12225. // FIXME why do we generate session-accept in 3 different places ?
  12226. var accept = $iq({to: self.peerjid,
  12227. type: 'set'})
  12228. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12229. action: 'session-accept',
  12230. initiator: self.initiator,
  12231. responder: self.responder,
  12232. sid: self.sid });
  12233. self.localSDP.toJingle(
  12234. accept,
  12235. self.initiator == self.me ? 'initiator' : 'responder',
  12236. ssrcs);
  12237. SSRCReplacement.processSessionInit(accept);
  12238. self.connection.sendIQ(accept,
  12239. function () {
  12240. var ack = {};
  12241. ack.source = 'answer';
  12242. $(document).trigger('ack.jingle', [self.sid, ack]);
  12243. },
  12244. function (stanza) {
  12245. var error = ($(stanza).find('error').length) ? {
  12246. code: $(stanza).find('error').attr('code'),
  12247. reason: $(stanza).find('error :first')[0].tagName,
  12248. }:{};
  12249. error.source = 'answer';
  12250. JingleSessionPC.onJingleError(self.sid, error);
  12251. },
  12252. 10000);
  12253. }
  12254. sdp.sdp = this.localSDP.raw;
  12255. this.peerconnection.setLocalDescription(sdp,
  12256. function () {
  12257. //console.log('setLocalDescription success');
  12258. if (self.usetrickle && !self.usepranswer) {
  12259. sendJingle();
  12260. }
  12261. self.setLocalDescription();
  12262. },
  12263. function (e) {
  12264. console.error('setLocalDescription failed', e);
  12265. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12266. }
  12267. );
  12268. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12269. for (var j = 0; j < cands.length; j++) {
  12270. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12271. if (cand.type == 'srflx') {
  12272. this.hadstuncandidate = true;
  12273. } else if (cand.type == 'relay') {
  12274. this.hadturncandidate = true;
  12275. }
  12276. }
  12277. };
  12278. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  12279. var self = this,
  12280. term = $iq({to: this.peerjid,
  12281. type: 'set'})
  12282. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12283. action: 'session-terminate',
  12284. initiator: this.initiator,
  12285. sid: this.sid})
  12286. .c('reason')
  12287. .c(reason || 'success');
  12288. if (text) {
  12289. term.up().c('text').t(text);
  12290. }
  12291. this.connection.sendIQ(term,
  12292. function () {
  12293. self.peerconnection.close();
  12294. self.peerconnection = null;
  12295. self.terminate();
  12296. var ack = {};
  12297. ack.source = 'terminate';
  12298. $(document).trigger('ack.jingle', [self.sid, ack]);
  12299. },
  12300. function (stanza) {
  12301. var error = ($(stanza).find('error').length) ? {
  12302. code: $(stanza).find('error').attr('code'),
  12303. reason: $(stanza).find('error :first')[0].tagName,
  12304. }:{};
  12305. $(document).trigger('ack.jingle', [self.sid, error]);
  12306. },
  12307. 10000);
  12308. if (this.statsinterval !== null) {
  12309. window.clearInterval(this.statsinterval);
  12310. this.statsinterval = null;
  12311. }
  12312. };
  12313. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  12314. var self = this;
  12315. // FIXME: dirty waiting
  12316. if (!this.peerconnection.localDescription)
  12317. {
  12318. console.warn("addSource - localDescription not ready yet")
  12319. setTimeout(function()
  12320. {
  12321. self.addSource(elem, fromJid);
  12322. },
  12323. 200
  12324. );
  12325. return;
  12326. }
  12327. console.log('addssrc', new Date().getTime());
  12328. console.log('ice', this.peerconnection.iceConnectionState);
  12329. this.readSsrcInfo(elem);
  12330. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12331. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12332. $(elem).each(function (idx, content) {
  12333. var name = $(content).attr('name');
  12334. var lines = '';
  12335. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12336. var semantics = this.getAttribute('semantics');
  12337. var ssrcs = $(this).find('>source').map(function () {
  12338. return this.getAttribute('ssrc');
  12339. }).get();
  12340. if (ssrcs.length != 0) {
  12341. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12342. }
  12343. });
  12344. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12345. tmp.each(function () {
  12346. var ssrc = $(this).attr('ssrc');
  12347. if(mySdp.containsSSRC(ssrc)){
  12348. /**
  12349. * This happens when multiple participants change their streams at the same time and
  12350. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12351. * addssrc are scheduled for update IQ. See
  12352. */
  12353. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12354. return;
  12355. }
  12356. if (sdp.containsSSRC(ssrc)) {
  12357. console.warn("Source-add request for existing SSRC: " + ssrc);
  12358. return;
  12359. }
  12360. $(this).find('>parameter').each(function () {
  12361. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12362. if ($(this).attr('value') && $(this).attr('value').length)
  12363. lines += ':' + $(this).attr('value');
  12364. lines += '\r\n';
  12365. });
  12366. });
  12367. sdp.media.forEach(function(media, idx) {
  12368. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12369. return;
  12370. sdp.media[idx] += lines;
  12371. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12372. self.addssrc[idx] += lines;
  12373. });
  12374. sdp.raw = sdp.session + sdp.media.join('');
  12375. });
  12376. this.modifySourcesQueue.push(function() {
  12377. // When a source is added and if this is FF, a new channel is allocated
  12378. // for receiving the added source. We need to diffuse the SSRC of this
  12379. // new recvonly channel to the rest of the peers.
  12380. console.log('modify sources done');
  12381. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12382. console.log("SDPs", mySdp, newSdp);
  12383. self.notifyMySSRCUpdate(mySdp, newSdp);
  12384. });
  12385. };
  12386. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  12387. var self = this;
  12388. // FIXME: dirty waiting
  12389. if (!this.peerconnection.localDescription)
  12390. {
  12391. console.warn("removeSource - localDescription not ready yet")
  12392. setTimeout(function()
  12393. {
  12394. self.removeSource(elem, fromJid);
  12395. },
  12396. 200
  12397. );
  12398. return;
  12399. }
  12400. console.log('removessrc', new Date().getTime());
  12401. console.log('ice', this.peerconnection.iceConnectionState);
  12402. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12403. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12404. $(elem).each(function (idx, content) {
  12405. var name = $(content).attr('name');
  12406. var lines = '';
  12407. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12408. var semantics = this.getAttribute('semantics');
  12409. var ssrcs = $(this).find('>source').map(function () {
  12410. return this.getAttribute('ssrc');
  12411. }).get();
  12412. if (ssrcs.length != 0) {
  12413. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12414. }
  12415. });
  12416. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12417. tmp.each(function () {
  12418. var ssrc = $(this).attr('ssrc');
  12419. // This should never happen, but can be useful for bug detection
  12420. if(mySdp.containsSSRC(ssrc)){
  12421. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12422. return;
  12423. }
  12424. $(this).find('>parameter').each(function () {
  12425. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12426. if ($(this).attr('value') && $(this).attr('value').length)
  12427. lines += ':' + $(this).attr('value');
  12428. lines += '\r\n';
  12429. });
  12430. });
  12431. sdp.media.forEach(function(media, idx) {
  12432. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12433. return;
  12434. sdp.media[idx] += lines;
  12435. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12436. self.removessrc[idx] += lines;
  12437. });
  12438. sdp.raw = sdp.session + sdp.media.join('');
  12439. });
  12440. this.modifySourcesQueue.push(function() {
  12441. // When a source is removed and if this is FF, the recvonly channel that
  12442. // receives the remote stream is deactivated . We need to diffuse the
  12443. // recvonly SSRC removal to the rest of the peers.
  12444. console.log('modify sources done');
  12445. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12446. console.log("SDPs", mySdp, newSdp);
  12447. self.notifyMySSRCUpdate(mySdp, newSdp);
  12448. });
  12449. };
  12450. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  12451. var self = this;
  12452. if (this.peerconnection.signalingState == 'closed') return;
  12453. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12454. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12455. this.setLocalDescription();
  12456. if(successCallback){
  12457. successCallback();
  12458. }
  12459. queueCallback();
  12460. return;
  12461. }
  12462. // Reset switch streams flag
  12463. this.switchstreams = false;
  12464. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12465. // add sources
  12466. this.addssrc.forEach(function(lines, idx) {
  12467. sdp.media[idx] += lines;
  12468. });
  12469. this.addssrc = [];
  12470. // remove sources
  12471. this.removessrc.forEach(function(lines, idx) {
  12472. lines = lines.split('\r\n');
  12473. lines.pop(); // remove empty last element;
  12474. lines.forEach(function(line) {
  12475. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12476. });
  12477. });
  12478. this.removessrc = [];
  12479. sdp.raw = sdp.session + sdp.media.join('');
  12480. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12481. function() {
  12482. if(self.signalingState == 'closed') {
  12483. console.error("createAnswer attempt on closed state");
  12484. queueCallback("createAnswer attempt on closed state");
  12485. return;
  12486. }
  12487. self.peerconnection.createAnswer(
  12488. function(modifiedAnswer) {
  12489. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12490. if (self.pendingop !== null) {
  12491. var sdp = new SDP(modifiedAnswer.sdp);
  12492. if (sdp.media.length > 1) {
  12493. switch(self.pendingop) {
  12494. case 'mute':
  12495. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12496. break;
  12497. case 'unmute':
  12498. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12499. break;
  12500. }
  12501. sdp.raw = sdp.session + sdp.media.join('');
  12502. modifiedAnswer.sdp = sdp.raw;
  12503. }
  12504. self.pendingop = null;
  12505. }
  12506. // FIXME: pushing down an answer while ice connection state
  12507. // is still checking is bad...
  12508. //console.log(self.peerconnection.iceConnectionState);
  12509. // trying to work around another chrome bug
  12510. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12511. self.peerconnection.setLocalDescription(modifiedAnswer,
  12512. function() {
  12513. //console.log('modified setLocalDescription ok');
  12514. self.setLocalDescription();
  12515. if(successCallback){
  12516. successCallback();
  12517. }
  12518. queueCallback();
  12519. },
  12520. function(error) {
  12521. console.error('modified setLocalDescription failed', error);
  12522. queueCallback(error);
  12523. }
  12524. );
  12525. },
  12526. function(error) {
  12527. console.error('modified answer failed', error);
  12528. queueCallback(error);
  12529. }
  12530. );
  12531. },
  12532. function(error) {
  12533. console.error('modify failed', error);
  12534. queueCallback(error);
  12535. }
  12536. );
  12537. };
  12538. /**
  12539. * Switches video streams.
  12540. * @param new_stream new stream that will be used as video of this session.
  12541. * @param oldStream old video stream of this session.
  12542. * @param success_callback callback executed after successful stream switch.
  12543. */
  12544. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12545. var self = this;
  12546. // Remember SDP to figure out added/removed SSRCs
  12547. var oldSdp = null;
  12548. if(self.peerconnection) {
  12549. if(self.peerconnection.localDescription) {
  12550. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12551. }
  12552. self.peerconnection.removeStream(oldStream, true);
  12553. if(new_stream)
  12554. self.peerconnection.addStream(new_stream);
  12555. }
  12556. // Conference is not active
  12557. if(!oldSdp || !self.peerconnection) {
  12558. success_callback();
  12559. return;
  12560. }
  12561. self.switchstreams = true;
  12562. self.modifySourcesQueue.push(function() {
  12563. console.log('modify sources done');
  12564. success_callback();
  12565. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12566. console.log("SDPs", oldSdp, newSdp);
  12567. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12568. });
  12569. };
  12570. /**
  12571. * Figures out added/removed ssrcs and send update IQs.
  12572. * @param old_sdp SDP object for old description.
  12573. * @param new_sdp SDP object for new description.
  12574. */
  12575. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12576. if (!(this.peerconnection.signalingState == 'stable' &&
  12577. this.peerconnection.iceConnectionState == 'connected')){
  12578. console.log("Too early to send updates");
  12579. return;
  12580. }
  12581. // send source-remove IQ.
  12582. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12583. var remove = $iq({to: this.peerjid, type: 'set'})
  12584. .c('jingle', {
  12585. xmlns: 'urn:xmpp:jingle:1',
  12586. action: 'source-remove',
  12587. initiator: this.initiator,
  12588. sid: this.sid
  12589. }
  12590. );
  12591. var removed = sdpDiffer.toJingle(remove);
  12592. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  12593. // it in the current form
  12594. if (removed)
  12595. remove = SSRCReplacement.processSourceRemove(remove);
  12596. if (removed && remove) {
  12597. console.info("Sending source-remove", remove);
  12598. this.connection.sendIQ(remove,
  12599. function (res) {
  12600. console.info('got remove result', res);
  12601. },
  12602. function (err) {
  12603. console.error('got remove error', err);
  12604. }
  12605. );
  12606. } else {
  12607. console.log('removal not necessary');
  12608. }
  12609. // send source-add IQ.
  12610. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12611. var add = $iq({to: this.peerjid, type: 'set'})
  12612. .c('jingle', {
  12613. xmlns: 'urn:xmpp:jingle:1',
  12614. action: 'source-add',
  12615. initiator: this.initiator,
  12616. sid: this.sid
  12617. }
  12618. );
  12619. var added = sdpDiffer.toJingle(add);
  12620. // Let 'source-add' IQ through the hack and see if we're allowed to send
  12621. // it in the current form
  12622. if (added)
  12623. add = SSRCReplacement.processSourceAdd(add);
  12624. if (added && add) {
  12625. console.info("Sending source-add", add);
  12626. this.connection.sendIQ(add,
  12627. function (res) {
  12628. console.info('got add result', res);
  12629. },
  12630. function (err) {
  12631. console.error('got add error', err);
  12632. }
  12633. );
  12634. } else {
  12635. console.log('addition not necessary');
  12636. }
  12637. };
  12638. /**
  12639. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12640. *
  12641. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12642. * tracks; otherwise, <tt>false</tt>
  12643. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12644. * tracks have been enabled/disabled. The function may, optionally, return
  12645. * another function which is to be invoked after the whole mute/unmute operation
  12646. * has completed successfully.
  12647. * @param options an object which specifies optional arguments such as the
  12648. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12649. * specifies whether the method was initiated in response to a user command (in
  12650. * contrast to an automatic decision made by the application logic)
  12651. */
  12652. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  12653. var byUser;
  12654. if (options) {
  12655. byUser = options.byUser;
  12656. if (typeof byUser === 'undefined') {
  12657. byUser = true;
  12658. }
  12659. } else {
  12660. byUser = true;
  12661. }
  12662. // The user's command to mute the (local) video takes precedence over any
  12663. // automatic decision made by the application logic.
  12664. if (byUser) {
  12665. this.videoMuteByUser = mute;
  12666. } else if (this.videoMuteByUser) {
  12667. return;
  12668. }
  12669. this.hardMuteVideo(mute);
  12670. var self = this;
  12671. var oldSdp = null;
  12672. if(self.peerconnection) {
  12673. if(self.peerconnection.localDescription) {
  12674. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12675. }
  12676. }
  12677. this.modifySourcesQueue.push(function() {
  12678. console.log('modify sources done');
  12679. callback(mute);
  12680. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12681. console.log("SDPs", oldSdp, newSdp);
  12682. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12683. });
  12684. };
  12685. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  12686. this.pendingop = muted ? 'mute' : 'unmute';
  12687. };
  12688. JingleSessionPC.prototype.sendMute = function (muted, content) {
  12689. var info = $iq({to: this.peerjid,
  12690. type: 'set'})
  12691. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12692. action: 'session-info',
  12693. initiator: this.initiator,
  12694. sid: this.sid });
  12695. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12696. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12697. if (content) {
  12698. info.attrs({'name': content});
  12699. }
  12700. this.connection.send(info);
  12701. };
  12702. JingleSessionPC.prototype.sendRinging = function () {
  12703. var info = $iq({to: this.peerjid,
  12704. type: 'set'})
  12705. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12706. action: 'session-info',
  12707. initiator: this.initiator,
  12708. sid: this.sid });
  12709. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12710. this.connection.send(info);
  12711. };
  12712. JingleSessionPC.prototype.getStats = function (interval) {
  12713. var self = this;
  12714. var recv = {audio: 0, video: 0};
  12715. var lost = {audio: 0, video: 0};
  12716. var lastrecv = {audio: 0, video: 0};
  12717. var lastlost = {audio: 0, video: 0};
  12718. var loss = {audio: 0, video: 0};
  12719. var delta = {audio: 0, video: 0};
  12720. this.statsinterval = window.setInterval(function () {
  12721. if (self && self.peerconnection && self.peerconnection.getStats) {
  12722. self.peerconnection.getStats(function (stats) {
  12723. var results = stats.result();
  12724. // TODO: there are so much statistics you can get from this..
  12725. for (var i = 0; i < results.length; ++i) {
  12726. if (results[i].type == 'ssrc') {
  12727. var packetsrecv = results[i].stat('packetsReceived');
  12728. var packetslost = results[i].stat('packetsLost');
  12729. if (packetsrecv && packetslost) {
  12730. packetsrecv = parseInt(packetsrecv, 10);
  12731. packetslost = parseInt(packetslost, 10);
  12732. if (results[i].stat('googFrameRateReceived')) {
  12733. lastlost.video = lost.video;
  12734. lastrecv.video = recv.video;
  12735. recv.video = packetsrecv;
  12736. lost.video = packetslost;
  12737. } else {
  12738. lastlost.audio = lost.audio;
  12739. lastrecv.audio = recv.audio;
  12740. recv.audio = packetsrecv;
  12741. lost.audio = packetslost;
  12742. }
  12743. }
  12744. }
  12745. }
  12746. delta.audio = recv.audio - lastrecv.audio;
  12747. delta.video = recv.video - lastrecv.video;
  12748. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12749. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12750. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12751. });
  12752. }
  12753. }, interval || 3000);
  12754. return this.statsinterval;
  12755. };
  12756. JingleSessionPC.onJingleError = function (session, error)
  12757. {
  12758. console.error("Jingle error", error);
  12759. }
  12760. JingleSessionPC.onJingleFatalError = function (session, error)
  12761. {
  12762. this.service.sessionTerminated = true;
  12763. this.connection.emuc.doLeave();
  12764. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12765. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  12766. }
  12767. JingleSessionPC.prototype.setLocalDescription = function () {
  12768. var self = this;
  12769. var newssrcs = [];
  12770. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12771. session.media.forEach(function (media) {
  12772. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12773. // TODO(gp) maybe exclude FID streams?
  12774. media.ssrcs.forEach(function (ssrc) {
  12775. if (ssrc.attribute !== 'cname') {
  12776. return;
  12777. }
  12778. newssrcs.push({
  12779. 'ssrc': ssrc.id,
  12780. 'type': media.type
  12781. });
  12782. });
  12783. }
  12784. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12785. {
  12786. newssrcs.push({
  12787. 'ssrc': self.localStreamsSSRC[media.type],
  12788. 'type': media.type
  12789. });
  12790. }
  12791. });
  12792. console.log('new ssrcs', newssrcs);
  12793. // Bind us as local SSRCs owner
  12794. if (newssrcs.length > 0) {
  12795. for (var i = 1; i <= newssrcs.length; i ++) {
  12796. var ssrc = newssrcs[i-1].ssrc;
  12797. var myJid = self.connection.emuc.myroomjid;
  12798. self.ssrcOwners[ssrc] = myJid;
  12799. }
  12800. }
  12801. }
  12802. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12803. // TODO: is this hack (along with the XMPPEvent-s used only for it) still needed
  12804. // now that we announce an SSRC for receive-only streams?
  12805. function sendKeyframe(pc) {
  12806. console.log('sendkeyframe', pc.iceConnectionState);
  12807. if (pc.iceConnectionState !== 'connected') return; // safe...
  12808. pc.setRemoteDescription(
  12809. pc.remoteDescription,
  12810. function () {
  12811. pc.createAnswer(
  12812. function (modifiedAnswer) {
  12813. pc.setLocalDescription(
  12814. modifiedAnswer,
  12815. function () {
  12816. // noop
  12817. },
  12818. function (error) {
  12819. console.log('triggerKeyframe setLocalDescription failed', error);
  12820. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  12821. }
  12822. );
  12823. },
  12824. function (error) {
  12825. console.log('triggerKeyframe createAnswer failed', error);
  12826. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  12827. }
  12828. );
  12829. },
  12830. function (error) {
  12831. console.log('triggerKeyframe setRemoteDescription failed', error);
  12832. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  12833. }
  12834. );
  12835. }
  12836. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  12837. var self = this;
  12838. var thessrc;
  12839. var streamId = APP.RTC.getStreamID(data.stream);
  12840. // look up an associated JID for a stream id
  12841. if (!streamId) {
  12842. console.error("No stream ID for", data.stream);
  12843. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12844. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12845. var ssrclines
  12846. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12847. ssrclines = ssrclines.filter(function (line) {
  12848. // NOTE(gp) previously we filtered on the mslabel, but that property
  12849. // is not always present.
  12850. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12851. if (RTCBrowserType.isTemasysPluginUsed()) {
  12852. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12853. } else {
  12854. return ((line.indexOf('msid:' + streamId) !== -1));
  12855. }
  12856. });
  12857. if (ssrclines.length) {
  12858. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12859. if (!self.ssrcOwners[thessrc]) {
  12860. console.error("No SSRC owner known for: " + thessrc);
  12861. return;
  12862. }
  12863. data.peerjid = self.ssrcOwners[thessrc];
  12864. console.log('associated jid', self.ssrcOwners[thessrc]);
  12865. } else {
  12866. console.error("No SSRC lines for ", streamId);
  12867. }
  12868. }
  12869. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12870. var isVideo = data.stream.getVideoTracks().length > 0;
  12871. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12872. // TODO: is this hack still needed now that we announce an SSRC for
  12873. // receive-only streams?
  12874. if (isVideo &&
  12875. data.peerjid && this.peerjid === data.peerjid &&
  12876. data.stream.getVideoTracks().length === 0 &&
  12877. APP.RTC.localVideo.getTracks().length > 0) {
  12878. window.setTimeout(function () {
  12879. sendKeyframe(self.peerconnection);
  12880. }, 3000);
  12881. }
  12882. }
  12883. module.exports = JingleSessionPC;
  12884. },{"../../service/xmpp/XMPPEvents":169,"../RTC/RTCBrowserType":8,"./JingleSession":53,"./LocalSSRCReplacement":55,"./SDP":56,"./SDPDiffer":57,"./SDPUtil":58,"./TraceablePeerConnection":59,"async":69,"sdp-transform":106}],55:[function(require,module,exports){
  12885. /* global $ */
  12886. /*
  12887. Here we do modifications of local video SSRCs. There are 2 situations we have
  12888. to handle:
  12889. 1. We generate SSRC for local recvonly video stream. This is the case when we
  12890. have no local camera and it is not generated automatically, but SSRC=1 is
  12891. used implicitly. If that happens RTCP packets will be dropped by the JVB
  12892. and we won't be able to request video key frames correctly.
  12893. 2. A hack to re-use SSRC of the first video stream for any new stream created
  12894. in future. It turned out that Chrome may keep on using the SSRC of removed
  12895. video stream in RTCP even though a new one has been created. So we just
  12896. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  12897. notifications are blocked once first video SSRC is advertised to the focus.
  12898. What this hack does:
  12899. 1. Stores the SSRC of the first video stream created by
  12900. a) scanning Jingle session-accept/session-invite for existing video SSRC
  12901. b) watching for 'source-add' for new video stream if it has not been
  12902. created in step a)
  12903. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  12904. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  12905. returned to the other parts of the application.
  12906. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  12907. blocks those notifications. This makes Jicofo and all participants think
  12908. that it exists all the time even if the video stream has been removed or
  12909. replaced locally. Thanks to that there is no additional signaling activity
  12910. on video mute or when switching to the desktop stream.
  12911. */
  12912. var SDP = require('./SDP');
  12913. var RTCBrowserType = require('../RTC/RTCBrowserType');
  12914. /**
  12915. * The hack is enabled on all browsers except FF by default
  12916. * FIXME finish the hack once removeStream method is implemented in FF
  12917. * @type {boolean}
  12918. */
  12919. var isEnabled = !RTCBrowserType.isFirefox();
  12920. /**
  12921. * Stored SSRC of local video stream.
  12922. */
  12923. var localVideoSSRC;
  12924. /**
  12925. * SSRC used for recvonly video stream when we have no local camera.
  12926. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  12927. * instead of 1.
  12928. */
  12929. var localRecvOnlySSRC;
  12930. /**
  12931. * cname for <tt>localRecvOnlySSRC</tt>
  12932. */
  12933. var localRecvOnlyCName;
  12934. /**
  12935. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  12936. * from given Jingle IQ.
  12937. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  12938. * @param actionName display name of the action which will be printed in log
  12939. * messages.
  12940. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  12941. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  12942. * other SSRCs left to be signaled after removing it.
  12943. */
  12944. var filterOutSource = function (modifyIq, actionName) {
  12945. var modifyIqTree = $(modifyIq.tree());
  12946. if (!localVideoSSRC)
  12947. return modifyIqTree[0];
  12948. var videoSSRC = modifyIqTree.find(
  12949. '>jingle>content[name="video"]' +
  12950. '>description>source[ssrc="' + localVideoSSRC + '"]');
  12951. if (!videoSSRC.length) {
  12952. return modifyIqTree[0];
  12953. }
  12954. console.info(
  12955. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  12956. videoSSRC.remove();
  12957. // Check if any sources still left to be added/removed
  12958. if (modifyIqTree.find('>jingle>content>description>source').length) {
  12959. return modifyIqTree[0];
  12960. } else {
  12961. return null;
  12962. }
  12963. };
  12964. /**
  12965. * Scans given Jingle IQ for video SSRC and stores it.
  12966. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  12967. */
  12968. var storeLocalVideoSSRC = function (jingleIq) {
  12969. var videoSSRCs =
  12970. $(jingleIq.tree())
  12971. .find('>jingle>content[name="video"]>description>source');
  12972. videoSSRCs.each(function (idx, ssrcElem) {
  12973. if (localVideoSSRC)
  12974. return;
  12975. // We consider SSRC real only if it has msid attribute
  12976. // recvonly streams in FF do not have it as well as local SSRCs
  12977. // we generate for recvonly streams in Chrome
  12978. var ssrSel = $(ssrcElem);
  12979. var msid = ssrSel.find('>parameter[name="msid"]');
  12980. if (msid.length) {
  12981. var ssrcVal = ssrSel.attr('ssrc');
  12982. if (ssrcVal) {
  12983. localVideoSSRC = ssrcVal;
  12984. console.info('Stored local video SSRC' +
  12985. ' for future re-use: ' + localVideoSSRC);
  12986. }
  12987. }
  12988. });
  12989. };
  12990. /**
  12991. * Generates new SSRC for local video recvonly stream.
  12992. * FIXME what about eventual SSRC collision ?
  12993. */
  12994. function generateRecvonlySSRC() {
  12995. //
  12996. localRecvOnlySSRC =
  12997. Math.random().toString(10).substring(2, 11);
  12998. localRecvOnlyCName =
  12999. Math.random().toString(36).substring(2);
  13000. console.info(
  13001. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  13002. ", cname: " + localRecvOnlyCName);
  13003. }
  13004. var LocalSSRCReplacement = {
  13005. /**
  13006. * Method must be called before 'session-initiate' or 'session-invite' is
  13007. * sent. Scans the IQ for local video SSRC and stores it if detected.
  13008. *
  13009. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  13010. * which will be scanned for local video SSRC.
  13011. */
  13012. processSessionInit: function (sessionInit) {
  13013. if (!isEnabled)
  13014. return;
  13015. if (localVideoSSRC) {
  13016. console.error("Local SSRC stored already: " + localVideoSSRC);
  13017. return;
  13018. }
  13019. storeLocalVideoSSRC(sessionInit);
  13020. },
  13021. /**
  13022. * If we have local video SSRC stored searched given
  13023. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  13024. * with the stored one.
  13025. * @param localDescription local description object that will have local
  13026. * video SSRC replaced with the stored one
  13027. * @returns modified <tt>localDescription</tt> object.
  13028. */
  13029. mungeLocalVideoSSRC: function (localDescription) {
  13030. if (!isEnabled)
  13031. return localDescription;
  13032. if (!localDescription) {
  13033. console.warn("localDescription is null or undefined");
  13034. return localDescription;
  13035. }
  13036. // IF we have local video SSRC stored make sure it is replaced
  13037. // with old SSRC
  13038. if (localVideoSSRC) {
  13039. var newSdp = new SDP(localDescription.sdp);
  13040. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  13041. !newSdp.containsSSRC(localVideoSSRC)) {
  13042. // Get new video SSRC
  13043. var map = newSdp.getMediaSsrcMap();
  13044. var videoPart = map[1];
  13045. var videoSSRCs = videoPart.ssrcs;
  13046. var newSSRC = Object.keys(videoSSRCs)[0];
  13047. console.info(
  13048. "Replacing new video SSRC: " + newSSRC +
  13049. " with " + localVideoSSRC);
  13050. localDescription.sdp =
  13051. newSdp.raw.replace(
  13052. new RegExp('a=ssrc:' + newSSRC, 'g'),
  13053. 'a=ssrc:' + localVideoSSRC);
  13054. }
  13055. } else {
  13056. // Make sure we have any SSRC for recvonly video stream
  13057. var sdp = new SDP(localDescription.sdp);
  13058. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  13059. sdp.media[1].indexOf('a=recvonly') !== -1) {
  13060. if (!localRecvOnlySSRC) {
  13061. generateRecvonlySSRC();
  13062. }
  13063. console.info('No SSRC in video recvonly stream' +
  13064. ' - adding SSRC: ' + localRecvOnlySSRC);
  13065. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  13066. ' cname:' + localRecvOnlyCName + '\r\n';
  13067. localDescription.sdp = sdp.session + sdp.media.join('');
  13068. }
  13069. }
  13070. return localDescription;
  13071. },
  13072. /**
  13073. * Method must be called before 'source-add' notification is sent. In case
  13074. * we have local video SSRC advertised already it will be removed from the
  13075. * notification. If no other SSRCs are described by given IQ null will be
  13076. * returned which means that there is no point in sending the notification.
  13077. * @param sourceAdd 'source-add' Jingle IQ to be processed
  13078. * @returns modified 'source-add' IQ which can be sent to the focus or
  13079. * <tt>null</tt> if no notification shall be sent. It is no longer
  13080. * a Strophe IQ Builder instance, but DOM element tree.
  13081. */
  13082. processSourceAdd: function (sourceAdd) {
  13083. if (!isEnabled)
  13084. return sourceAdd;
  13085. if (!localVideoSSRC) {
  13086. // Store local SSRC if available
  13087. storeLocalVideoSSRC(sourceAdd);
  13088. return sourceAdd;
  13089. } else {
  13090. return filterOutSource(sourceAdd, 'source-add');
  13091. }
  13092. },
  13093. /**
  13094. * Method must be called before 'source-remove' notification is sent.
  13095. * Removes local video SSRC from the notification. If there are no other
  13096. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  13097. * means that there is no point in sending the notification.
  13098. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  13099. * @returns modified 'source-remove' IQ which can be sent to the focus or
  13100. * <tt>null</tt> if no notification shall be sent. It is no longer
  13101. * a Strophe IQ Builder instance, but DOM element tree.
  13102. */
  13103. processSourceRemove: function (sourceRemove) {
  13104. if (!isEnabled)
  13105. return sourceRemove;
  13106. return filterOutSource(sourceRemove, 'source-remove');
  13107. },
  13108. /**
  13109. * Turns the hack on or off
  13110. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  13111. * to disable it
  13112. */
  13113. setEnabled: function (enabled) {
  13114. isEnabled = enabled;
  13115. }
  13116. };
  13117. module.exports = LocalSSRCReplacement;
  13118. },{"../RTC/RTCBrowserType":8,"./SDP":56}],56:[function(require,module,exports){
  13119. /* jshint -W117 */
  13120. var SDPUtil = require("./SDPUtil");
  13121. // SDP STUFF
  13122. function SDP(sdp) {
  13123. this.media = sdp.split('\r\nm=');
  13124. for (var i = 1; i < this.media.length; i++) {
  13125. this.media[i] = 'm=' + this.media[i];
  13126. if (i != this.media.length - 1) {
  13127. this.media[i] += '\r\n';
  13128. }
  13129. }
  13130. this.session = this.media.shift() + '\r\n';
  13131. this.raw = this.session + this.media.join('');
  13132. }
  13133. /**
  13134. * Returns map of MediaChannel mapped per channel idx.
  13135. */
  13136. SDP.prototype.getMediaSsrcMap = function() {
  13137. var self = this;
  13138. var media_ssrcs = {};
  13139. var tmp;
  13140. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  13141. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  13142. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  13143. var media = {
  13144. mediaindex: mediaindex,
  13145. mid: mid,
  13146. ssrcs: {},
  13147. ssrcGroups: []
  13148. };
  13149. media_ssrcs[mediaindex] = media;
  13150. tmp.forEach(function (line) {
  13151. var linessrc = line.substring(7).split(' ')[0];
  13152. // allocate new ChannelSsrc
  13153. if(!media.ssrcs[linessrc]) {
  13154. media.ssrcs[linessrc] = {
  13155. ssrc: linessrc,
  13156. lines: []
  13157. };
  13158. }
  13159. media.ssrcs[linessrc].lines.push(line);
  13160. });
  13161. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  13162. tmp.forEach(function(line){
  13163. var semantics = line.substr(0, idx).substr(13);
  13164. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13165. if (ssrcs.length != 0) {
  13166. media.ssrcGroups.push({
  13167. semantics: semantics,
  13168. ssrcs: ssrcs
  13169. });
  13170. }
  13171. });
  13172. }
  13173. return media_ssrcs;
  13174. };
  13175. /**
  13176. * Returns <tt>true</tt> if this SDP contains given SSRC.
  13177. * @param ssrc the ssrc to check.
  13178. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  13179. */
  13180. SDP.prototype.containsSSRC = function(ssrc) {
  13181. var medias = this.getMediaSsrcMap();
  13182. var contains = false;
  13183. Object.keys(medias).forEach(function(mediaindex){
  13184. var media = medias[mediaindex];
  13185. //console.log("Check", channel, ssrc);
  13186. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  13187. contains = true;
  13188. }
  13189. });
  13190. return contains;
  13191. };
  13192. // remove iSAC and CN from SDP
  13193. SDP.prototype.mangle = function () {
  13194. var i, j, mline, lines, rtpmap, newdesc;
  13195. for (i = 0; i < this.media.length; i++) {
  13196. lines = this.media[i].split('\r\n');
  13197. lines.pop(); // remove empty last element
  13198. mline = SDPUtil.parse_mline(lines.shift());
  13199. if (mline.media != 'audio')
  13200. continue;
  13201. newdesc = '';
  13202. mline.fmt.length = 0;
  13203. for (j = 0; j < lines.length; j++) {
  13204. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  13205. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  13206. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  13207. continue;
  13208. mline.fmt.push(rtpmap.id);
  13209. newdesc += lines[j] + '\r\n';
  13210. } else {
  13211. newdesc += lines[j] + '\r\n';
  13212. }
  13213. }
  13214. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  13215. this.media[i] += newdesc;
  13216. }
  13217. this.raw = this.session + this.media.join('');
  13218. };
  13219. // remove lines matching prefix from session section
  13220. SDP.prototype.removeSessionLines = function(prefix) {
  13221. var self = this;
  13222. var lines = SDPUtil.find_lines(this.session, prefix);
  13223. lines.forEach(function(line) {
  13224. self.session = self.session.replace(line + '\r\n', '');
  13225. });
  13226. this.raw = this.session + this.media.join('');
  13227. return lines;
  13228. }
  13229. // remove lines matching prefix from a media section specified by mediaindex
  13230. // TODO: non-numeric mediaindex could match mid
  13231. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  13232. var self = this;
  13233. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  13234. lines.forEach(function(line) {
  13235. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  13236. });
  13237. this.raw = this.session + this.media.join('');
  13238. return lines;
  13239. }
  13240. // add content's to a jingle element
  13241. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  13242. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  13243. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  13244. var self = this;
  13245. // new bundle plan
  13246. if (SDPUtil.find_line(this.session, 'a=group:')) {
  13247. lines = SDPUtil.find_lines(this.session, 'a=group:');
  13248. for (i = 0; i < lines.length; i++) {
  13249. tmp = lines[i].split(' ');
  13250. var semantics = tmp.shift().substr(8);
  13251. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  13252. for (j = 0; j < tmp.length; j++) {
  13253. elem.c('content', {name: tmp[j]}).up();
  13254. }
  13255. elem.up();
  13256. }
  13257. }
  13258. for (i = 0; i < this.media.length; i++) {
  13259. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  13260. if (!(mline.media === 'audio' ||
  13261. mline.media === 'video' ||
  13262. mline.media === 'application'))
  13263. {
  13264. continue;
  13265. }
  13266. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  13267. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13268. } else {
  13269. if(ssrcs && ssrcs[mline.media])
  13270. {
  13271. ssrc = ssrcs[mline.media];
  13272. }
  13273. else
  13274. ssrc = false;
  13275. }
  13276. elem.c('content', {creator: thecreator, name: mline.media});
  13277. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13278. // prefer identifier from a=mid if present
  13279. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13280. elem.attrs({ name: mid });
  13281. }
  13282. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13283. {
  13284. elem.c('description',
  13285. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13286. media: mline.media });
  13287. if (ssrc) {
  13288. elem.attrs({ssrc: ssrc});
  13289. }
  13290. for (j = 0; j < mline.fmt.length; j++) {
  13291. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13292. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13293. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13294. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13295. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13296. for (k = 0; k < tmp.length; k++) {
  13297. elem.c('parameter', tmp[k]).up();
  13298. }
  13299. }
  13300. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13301. elem.up();
  13302. }
  13303. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13304. elem.c('encryption', {required: 1});
  13305. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13306. crypto.forEach(function(line) {
  13307. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13308. });
  13309. elem.up(); // end of encryption
  13310. }
  13311. if (ssrc) {
  13312. // new style mapping
  13313. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13314. // FIXME: group by ssrc and support multiple different ssrcs
  13315. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13316. if(ssrclines.length > 0) {
  13317. ssrclines.forEach(function (line) {
  13318. idx = line.indexOf(' ');
  13319. var linessrc = line.substr(0, idx).substr(7);
  13320. if (linessrc != ssrc) {
  13321. elem.up();
  13322. ssrc = linessrc;
  13323. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13324. }
  13325. var kv = line.substr(idx + 1);
  13326. elem.c('parameter');
  13327. if (kv.indexOf(':') == -1) {
  13328. elem.attrs({ name: kv });
  13329. } else {
  13330. var k = kv.split(':', 2)[0];
  13331. elem.attrs({ name: k });
  13332. var v = kv.split(':', 2)[1];
  13333. v = SDPUtil.filter_special_chars(v);
  13334. elem.attrs({ value: v });
  13335. }
  13336. elem.up();
  13337. });
  13338. }
  13339. else
  13340. {
  13341. elem.up();
  13342. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13343. elem.c('parameter');
  13344. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13345. elem.up();
  13346. var msid = null;
  13347. if(mline.media == "audio")
  13348. {
  13349. msid = APP.RTC.localAudio.getId();
  13350. }
  13351. else
  13352. {
  13353. msid = APP.RTC.localVideo.getId();
  13354. }
  13355. if(msid != null)
  13356. {
  13357. msid = SDPUtil.filter_special_chars(msid);
  13358. elem.c('parameter');
  13359. elem.attrs({name: "msid", value:msid});
  13360. elem.up();
  13361. elem.c('parameter');
  13362. elem.attrs({name: "mslabel", value:msid});
  13363. elem.up();
  13364. elem.c('parameter');
  13365. elem.attrs({name: "label", value:msid});
  13366. elem.up();
  13367. }
  13368. }
  13369. elem.up();
  13370. // XEP-0339 handle ssrc-group attributes
  13371. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13372. ssrc_group_lines.forEach(function(line) {
  13373. idx = line.indexOf(' ');
  13374. var semantics = line.substr(0, idx).substr(13);
  13375. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13376. if (ssrcs.length != 0) {
  13377. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13378. ssrcs.forEach(function(ssrc) {
  13379. elem.c('source', { ssrc: ssrc })
  13380. .up();
  13381. });
  13382. elem.up();
  13383. }
  13384. });
  13385. }
  13386. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13387. elem.c('rtcp-mux').up();
  13388. }
  13389. // XEP-0293 -- map a=rtcp-fb:*
  13390. this.RtcpFbToJingle(i, elem, '*');
  13391. // XEP-0294
  13392. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13393. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13394. for (j = 0; j < lines.length; j++) {
  13395. tmp = SDPUtil.parse_extmap(lines[j]);
  13396. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13397. uri: tmp.uri,
  13398. id: tmp.value });
  13399. if (tmp.hasOwnProperty('direction')) {
  13400. switch (tmp.direction) {
  13401. case 'sendonly':
  13402. elem.attrs({senders: 'responder'});
  13403. break;
  13404. case 'recvonly':
  13405. elem.attrs({senders: 'initiator'});
  13406. break;
  13407. case 'sendrecv':
  13408. elem.attrs({senders: 'both'});
  13409. break;
  13410. case 'inactive':
  13411. elem.attrs({senders: 'none'});
  13412. break;
  13413. }
  13414. }
  13415. // TODO: handle params
  13416. elem.up();
  13417. }
  13418. }
  13419. elem.up(); // end of description
  13420. }
  13421. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13422. this.TransportToJingle(i, elem);
  13423. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13424. elem.attrs({senders: 'both'});
  13425. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13426. elem.attrs({senders: 'initiator'});
  13427. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13428. elem.attrs({senders: 'responder'});
  13429. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13430. elem.attrs({senders: 'none'});
  13431. }
  13432. if (mline.port == '0') {
  13433. // estos hack to reject an m-line
  13434. elem.attrs({senders: 'rejected'});
  13435. }
  13436. elem.up(); // end of content
  13437. }
  13438. elem.up();
  13439. return elem;
  13440. };
  13441. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13442. var i = mediaindex;
  13443. var tmp;
  13444. var self = this;
  13445. elem.c('transport');
  13446. // XEP-0343 DTLS/SCTP
  13447. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13448. {
  13449. var sctpmap = SDPUtil.find_line(
  13450. this.media[i], 'a=sctpmap:', self.session);
  13451. if (sctpmap)
  13452. {
  13453. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13454. elem.c('sctpmap',
  13455. {
  13456. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13457. number: sctpAttrs[0], /* SCTP port */
  13458. protocol: sctpAttrs[1], /* protocol */
  13459. });
  13460. // Optional stream count attribute
  13461. if (sctpAttrs.length > 2)
  13462. elem.attrs({ streams: sctpAttrs[2]});
  13463. elem.up();
  13464. }
  13465. }
  13466. // XEP-0320
  13467. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13468. fingerprints.forEach(function(line) {
  13469. tmp = SDPUtil.parse_fingerprint(line);
  13470. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13471. elem.c('fingerprint').t(tmp.fingerprint);
  13472. delete tmp.fingerprint;
  13473. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13474. if (line) {
  13475. tmp.setup = line.substr(8);
  13476. }
  13477. elem.attrs(tmp);
  13478. elem.up(); // end of fingerprint
  13479. });
  13480. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13481. if (tmp) {
  13482. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13483. elem.attrs(tmp);
  13484. // XEP-0176
  13485. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13486. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13487. lines.forEach(function (line) {
  13488. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13489. });
  13490. }
  13491. }
  13492. elem.up(); // end of transport
  13493. }
  13494. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13495. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13496. lines.forEach(function (line) {
  13497. var tmp = SDPUtil.parse_rtcpfb(line);
  13498. if (tmp.type == 'trr-int') {
  13499. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13500. elem.up();
  13501. } else {
  13502. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13503. if (tmp.params.length > 0) {
  13504. elem.attrs({'subtype': tmp.params[0]});
  13505. }
  13506. elem.up();
  13507. }
  13508. });
  13509. };
  13510. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13511. var media = '';
  13512. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13513. if (tmp.length) {
  13514. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13515. if (tmp.attr('value')) {
  13516. media += tmp.attr('value');
  13517. } else {
  13518. media += '0';
  13519. }
  13520. media += '\r\n';
  13521. }
  13522. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13523. tmp.each(function () {
  13524. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13525. if ($(this).attr('subtype')) {
  13526. media += ' ' + $(this).attr('subtype');
  13527. }
  13528. media += '\r\n';
  13529. });
  13530. return media;
  13531. };
  13532. // construct an SDP from a jingle stanza
  13533. SDP.prototype.fromJingle = function (jingle) {
  13534. var self = this;
  13535. this.raw = 'v=0\r\n' +
  13536. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13537. 's=-\r\n' +
  13538. 't=0 0\r\n';
  13539. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13540. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13541. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13542. var contents = $(group).find('>content').map(function (idx, content) {
  13543. return content.getAttribute('name');
  13544. }).get();
  13545. if (contents.length > 0) {
  13546. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13547. }
  13548. });
  13549. }
  13550. this.session = this.raw;
  13551. jingle.find('>content').each(function () {
  13552. var m = self.jingle2media($(this));
  13553. self.media.push(m);
  13554. });
  13555. // reconstruct msid-semantic -- apparently not necessary
  13556. /*
  13557. var msid = SDPUtil.parse_ssrc(this.raw);
  13558. if (msid.hasOwnProperty('mslabel')) {
  13559. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13560. }
  13561. */
  13562. this.raw = this.session + this.media.join('');
  13563. };
  13564. // translate a jingle content element into an an SDP media part
  13565. SDP.prototype.jingle2media = function (content) {
  13566. var media = '',
  13567. desc = content.find('description'),
  13568. ssrc = desc.attr('ssrc'),
  13569. self = this,
  13570. tmp;
  13571. var sctp = content.find(
  13572. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13573. tmp = { media: desc.attr('media') };
  13574. tmp.port = '1';
  13575. if (content.attr('senders') == 'rejected') {
  13576. // estos hack to reject an m-line.
  13577. tmp.port = '0';
  13578. }
  13579. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13580. if (sctp.length)
  13581. tmp.proto = 'DTLS/SCTP';
  13582. else
  13583. tmp.proto = 'RTP/SAVPF';
  13584. } else {
  13585. tmp.proto = 'RTP/AVPF';
  13586. }
  13587. if (!sctp.length)
  13588. {
  13589. tmp.fmt = desc.find('payload-type').map(
  13590. function () { return this.getAttribute('id'); }).get();
  13591. media += SDPUtil.build_mline(tmp) + '\r\n';
  13592. }
  13593. else
  13594. {
  13595. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13596. media += 'a=sctpmap:' + sctp.attr('number') +
  13597. ' ' + sctp.attr('protocol');
  13598. var streamCount = sctp.attr('streams');
  13599. if (streamCount)
  13600. media += ' ' + streamCount + '\r\n';
  13601. else
  13602. media += '\r\n';
  13603. }
  13604. media += 'c=IN IP4 0.0.0.0\r\n';
  13605. if (!sctp.length)
  13606. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13607. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13608. if (tmp.length) {
  13609. if (tmp.attr('ufrag')) {
  13610. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13611. }
  13612. if (tmp.attr('pwd')) {
  13613. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13614. }
  13615. tmp.find('>fingerprint').each(function () {
  13616. // FIXME: check namespace at some point
  13617. media += 'a=fingerprint:' + this.getAttribute('hash');
  13618. media += ' ' + $(this).text();
  13619. media += '\r\n';
  13620. if (this.getAttribute('setup')) {
  13621. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13622. }
  13623. });
  13624. }
  13625. switch (content.attr('senders')) {
  13626. case 'initiator':
  13627. media += 'a=sendonly\r\n';
  13628. break;
  13629. case 'responder':
  13630. media += 'a=recvonly\r\n';
  13631. break;
  13632. case 'none':
  13633. media += 'a=inactive\r\n';
  13634. break;
  13635. case 'both':
  13636. media += 'a=sendrecv\r\n';
  13637. break;
  13638. }
  13639. media += 'a=mid:' + content.attr('name') + '\r\n';
  13640. // <description><rtcp-mux/></description>
  13641. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13642. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13643. if (desc.find('rtcp-mux').length) {
  13644. media += 'a=rtcp-mux\r\n';
  13645. }
  13646. if (desc.find('encryption').length) {
  13647. desc.find('encryption>crypto').each(function () {
  13648. media += 'a=crypto:' + this.getAttribute('tag');
  13649. media += ' ' + this.getAttribute('crypto-suite');
  13650. media += ' ' + this.getAttribute('key-params');
  13651. if (this.getAttribute('session-params')) {
  13652. media += ' ' + this.getAttribute('session-params');
  13653. }
  13654. media += '\r\n';
  13655. });
  13656. }
  13657. desc.find('payload-type').each(function () {
  13658. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13659. if ($(this).find('>parameter').length) {
  13660. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13661. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13662. media += '\r\n';
  13663. }
  13664. // xep-0293
  13665. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13666. });
  13667. // xep-0293
  13668. media += self.RtcpFbFromJingle(desc, '*');
  13669. // xep-0294
  13670. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13671. tmp.each(function () {
  13672. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13673. });
  13674. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13675. media += SDPUtil.candidateFromJingle(this);
  13676. });
  13677. // XEP-0339 handle ssrc-group attributes
  13678. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13679. var semantics = this.getAttribute('semantics');
  13680. var ssrcs = $(this).find('>source').map(function() {
  13681. return this.getAttribute('ssrc');
  13682. }).get();
  13683. if (ssrcs.length != 0) {
  13684. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13685. }
  13686. });
  13687. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13688. tmp.each(function () {
  13689. var ssrc = this.getAttribute('ssrc');
  13690. $(this).find('>parameter').each(function () {
  13691. var name = this.getAttribute('name');
  13692. var value = this.getAttribute('value');
  13693. value = SDPUtil.filter_special_chars(value);
  13694. media += 'a=ssrc:' + ssrc + ' ' + name;
  13695. if (value && value.length)
  13696. media += ':' + value;
  13697. media += '\r\n';
  13698. });
  13699. });
  13700. return media;
  13701. };
  13702. module.exports = SDP;
  13703. },{"./SDPUtil":58}],57:[function(require,module,exports){
  13704. var SDPUtil = require("./SDPUtil");
  13705. function SDPDiffer(mySDP, otherSDP) {
  13706. this.mySDP = mySDP;
  13707. this.otherSDP = otherSDP;
  13708. }
  13709. /**
  13710. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13711. * @param otherSdp the other SDP to check ssrc with.
  13712. */
  13713. SDPDiffer.prototype.getNewMedia = function() {
  13714. // this could be useful in Array.prototype.
  13715. function arrayEquals(array) {
  13716. // if the other array is a falsy value, return
  13717. if (!array)
  13718. return false;
  13719. // compare lengths - can save a lot of time
  13720. if (this.length != array.length)
  13721. return false;
  13722. for (var i = 0, l=this.length; i < l; i++) {
  13723. // Check if we have nested arrays
  13724. if (this[i] instanceof Array && array[i] instanceof Array) {
  13725. // recurse into the nested arrays
  13726. if (!this[i].equals(array[i]))
  13727. return false;
  13728. }
  13729. else if (this[i] != array[i]) {
  13730. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13731. return false;
  13732. }
  13733. }
  13734. return true;
  13735. }
  13736. var myMedias = this.mySDP.getMediaSsrcMap();
  13737. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13738. var newMedia = {};
  13739. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13740. var myMedia = myMedias[othersMediaIdx];
  13741. var othersMedia = othersMedias[othersMediaIdx];
  13742. if(!myMedia && othersMedia) {
  13743. // Add whole channel
  13744. newMedia[othersMediaIdx] = othersMedia;
  13745. return;
  13746. }
  13747. // Look for new ssrcs accross the channel
  13748. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13749. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13750. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13751. if(!newMedia[othersMediaIdx]){
  13752. newMedia[othersMediaIdx] = {
  13753. mediaindex: othersMedia.mediaindex,
  13754. mid: othersMedia.mid,
  13755. ssrcs: {},
  13756. ssrcGroups: []
  13757. };
  13758. }
  13759. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13760. }
  13761. });
  13762. // Look for new ssrc groups across the channels
  13763. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13764. // try to match the other ssrc-group with an ssrc-group of ours
  13765. var matched = false;
  13766. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13767. var mySsrcGroup = myMedia.ssrcGroups[i];
  13768. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13769. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13770. matched = true;
  13771. break;
  13772. }
  13773. }
  13774. if (!matched) {
  13775. // Allocate channel if we've found an ssrc-group that doesn't
  13776. // exist in our channel
  13777. if(!newMedia[othersMediaIdx]){
  13778. newMedia[othersMediaIdx] = {
  13779. mediaindex: othersMedia.mediaindex,
  13780. mid: othersMedia.mid,
  13781. ssrcs: {},
  13782. ssrcGroups: []
  13783. };
  13784. }
  13785. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13786. }
  13787. });
  13788. });
  13789. return newMedia;
  13790. };
  13791. /**
  13792. * Sends SSRC update IQ.
  13793. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13794. * @param sid session identifier that will be put into the IQ.
  13795. * @param initiator initiator identifier.
  13796. * @param toJid destination Jid
  13797. * @param isAdd indicates if this is remove or add operation.
  13798. */
  13799. SDPDiffer.prototype.toJingle = function(modify) {
  13800. var sdpMediaSsrcs = this.getNewMedia();
  13801. var self = this;
  13802. // FIXME: only announce video ssrcs since we mix audio and dont need
  13803. // the audio ssrcs therefore
  13804. var modified = false;
  13805. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13806. modified = true;
  13807. var media = sdpMediaSsrcs[mediaindex];
  13808. modify.c('content', {name: media.mid});
  13809. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13810. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13811. // generate sources from lines
  13812. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13813. var mediaSsrc = media.ssrcs[ssrcNum];
  13814. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13815. modify.attrs({ssrc: mediaSsrc.ssrc});
  13816. // iterate over ssrc lines
  13817. mediaSsrc.lines.forEach(function (line) {
  13818. var idx = line.indexOf(' ');
  13819. var kv = line.substr(idx + 1);
  13820. modify.c('parameter');
  13821. if (kv.indexOf(':') == -1) {
  13822. modify.attrs({ name: kv });
  13823. } else {
  13824. var nv = kv.split(':', 2);
  13825. var name = nv[0];
  13826. var value = SDPUtil.filter_special_chars(nv[1]);
  13827. modify.attrs({ name: name });
  13828. modify.attrs({ value: value });
  13829. }
  13830. modify.up(); // end of parameter
  13831. });
  13832. modify.up(); // end of source
  13833. });
  13834. // generate source groups from lines
  13835. media.ssrcGroups.forEach(function(ssrcGroup) {
  13836. if (ssrcGroup.ssrcs.length != 0) {
  13837. modify.c('ssrc-group', {
  13838. semantics: ssrcGroup.semantics,
  13839. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13840. });
  13841. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13842. modify.c('source', { ssrc: ssrc })
  13843. .up(); // end of source
  13844. });
  13845. modify.up(); // end of ssrc-group
  13846. }
  13847. });
  13848. modify.up(); // end of description
  13849. modify.up(); // end of content
  13850. });
  13851. return modified;
  13852. };
  13853. module.exports = SDPDiffer;
  13854. },{"./SDPUtil":58}],58:[function(require,module,exports){
  13855. SDPUtil = {
  13856. filter_special_chars: function (text) {
  13857. return text.replace(/[\\\/\{,\}\+]/g, "");
  13858. },
  13859. iceparams: function (mediadesc, sessiondesc) {
  13860. var data = null;
  13861. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13862. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13863. data = {
  13864. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13865. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13866. };
  13867. }
  13868. return data;
  13869. },
  13870. parse_iceufrag: function (line) {
  13871. return line.substring(12);
  13872. },
  13873. build_iceufrag: function (frag) {
  13874. return 'a=ice-ufrag:' + frag;
  13875. },
  13876. parse_icepwd: function (line) {
  13877. return line.substring(10);
  13878. },
  13879. build_icepwd: function (pwd) {
  13880. return 'a=ice-pwd:' + pwd;
  13881. },
  13882. parse_mid: function (line) {
  13883. return line.substring(6);
  13884. },
  13885. parse_mline: function (line) {
  13886. var parts = line.substring(2).split(' '),
  13887. data = {};
  13888. data.media = parts.shift();
  13889. data.port = parts.shift();
  13890. data.proto = parts.shift();
  13891. if (parts[parts.length - 1] === '') { // trailing whitespace
  13892. parts.pop();
  13893. }
  13894. data.fmt = parts;
  13895. return data;
  13896. },
  13897. build_mline: function (mline) {
  13898. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13899. },
  13900. parse_rtpmap: function (line) {
  13901. var parts = line.substring(9).split(' '),
  13902. data = {};
  13903. data.id = parts.shift();
  13904. parts = parts[0].split('/');
  13905. data.name = parts.shift();
  13906. data.clockrate = parts.shift();
  13907. data.channels = parts.length ? parts.shift() : '1';
  13908. return data;
  13909. },
  13910. /**
  13911. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13912. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13913. * @returns [SCTP port number, protocol, streams]
  13914. */
  13915. parse_sctpmap: function (line)
  13916. {
  13917. var parts = line.substring(10).split(' ');
  13918. var sctpPort = parts[0];
  13919. var protocol = parts[1];
  13920. // Stream count is optional
  13921. var streamCount = parts.length > 2 ? parts[2] : null;
  13922. return [sctpPort, protocol, streamCount];// SCTP port
  13923. },
  13924. build_rtpmap: function (el) {
  13925. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13926. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13927. line += '/' + el.getAttribute('channels');
  13928. }
  13929. return line;
  13930. },
  13931. parse_crypto: function (line) {
  13932. var parts = line.substring(9).split(' '),
  13933. data = {};
  13934. data.tag = parts.shift();
  13935. data['crypto-suite'] = parts.shift();
  13936. data['key-params'] = parts.shift();
  13937. if (parts.length) {
  13938. data['session-params'] = parts.join(' ');
  13939. }
  13940. return data;
  13941. },
  13942. parse_fingerprint: function (line) { // RFC 4572
  13943. var parts = line.substring(14).split(' '),
  13944. data = {};
  13945. data.hash = parts.shift();
  13946. data.fingerprint = parts.shift();
  13947. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13948. return data;
  13949. },
  13950. parse_fmtp: function (line) {
  13951. var parts = line.split(' '),
  13952. i, key, value,
  13953. data = [];
  13954. parts.shift();
  13955. parts = parts.join(' ').split(';');
  13956. for (i = 0; i < parts.length; i++) {
  13957. key = parts[i].split('=')[0];
  13958. while (key.length && key[0] == ' ') {
  13959. key = key.substring(1);
  13960. }
  13961. value = parts[i].split('=')[1];
  13962. if (key && value) {
  13963. data.push({name: key, value: value});
  13964. } else if (key) {
  13965. // rfc 4733 (DTMF) style stuff
  13966. data.push({name: '', value: key});
  13967. }
  13968. }
  13969. return data;
  13970. },
  13971. parse_icecandidate: function (line) {
  13972. var candidate = {},
  13973. elems = line.split(' ');
  13974. candidate.foundation = elems[0].substring(12);
  13975. candidate.component = elems[1];
  13976. candidate.protocol = elems[2].toLowerCase();
  13977. candidate.priority = elems[3];
  13978. candidate.ip = elems[4];
  13979. candidate.port = elems[5];
  13980. // elems[6] => "typ"
  13981. candidate.type = elems[7];
  13982. candidate.generation = 0; // default value, may be overwritten below
  13983. for (var i = 8; i < elems.length; i += 2) {
  13984. switch (elems[i]) {
  13985. case 'raddr':
  13986. candidate['rel-addr'] = elems[i + 1];
  13987. break;
  13988. case 'rport':
  13989. candidate['rel-port'] = elems[i + 1];
  13990. break;
  13991. case 'generation':
  13992. candidate.generation = elems[i + 1];
  13993. break;
  13994. case 'tcptype':
  13995. candidate.tcptype = elems[i + 1];
  13996. break;
  13997. default: // TODO
  13998. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13999. }
  14000. }
  14001. candidate.network = '1';
  14002. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14003. return candidate;
  14004. },
  14005. build_icecandidate: function (cand) {
  14006. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  14007. line += ' ';
  14008. switch (cand.type) {
  14009. case 'srflx':
  14010. case 'prflx':
  14011. case 'relay':
  14012. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  14013. line += 'raddr';
  14014. line += ' ';
  14015. line += cand['rel-addr'];
  14016. line += ' ';
  14017. line += 'rport';
  14018. line += ' ';
  14019. line += cand['rel-port'];
  14020. line += ' ';
  14021. }
  14022. break;
  14023. }
  14024. if (cand.hasOwnAttribute('tcptype')) {
  14025. line += 'tcptype';
  14026. line += ' ';
  14027. line += cand.tcptype;
  14028. line += ' ';
  14029. }
  14030. line += 'generation';
  14031. line += ' ';
  14032. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  14033. return line;
  14034. },
  14035. parse_ssrc: function (desc) {
  14036. // proprietary mapping of a=ssrc lines
  14037. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  14038. // and parse according to that
  14039. var lines = desc.split('\r\n'),
  14040. data = {};
  14041. for (var i = 0; i < lines.length; i++) {
  14042. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  14043. var idx = lines[i].indexOf(' ');
  14044. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  14045. }
  14046. }
  14047. return data;
  14048. },
  14049. parse_rtcpfb: function (line) {
  14050. var parts = line.substr(10).split(' ');
  14051. var data = {};
  14052. data.pt = parts.shift();
  14053. data.type = parts.shift();
  14054. data.params = parts;
  14055. return data;
  14056. },
  14057. parse_extmap: function (line) {
  14058. var parts = line.substr(9).split(' ');
  14059. var data = {};
  14060. data.value = parts.shift();
  14061. if (data.value.indexOf('/') != -1) {
  14062. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  14063. data.value = data.value.substr(0, data.value.indexOf('/'));
  14064. } else {
  14065. data.direction = 'both';
  14066. }
  14067. data.uri = parts.shift();
  14068. data.params = parts;
  14069. return data;
  14070. },
  14071. find_line: function (haystack, needle, sessionpart) {
  14072. var lines = haystack.split('\r\n');
  14073. for (var i = 0; i < lines.length; i++) {
  14074. if (lines[i].substring(0, needle.length) == needle) {
  14075. return lines[i];
  14076. }
  14077. }
  14078. if (!sessionpart) {
  14079. return false;
  14080. }
  14081. // search session part
  14082. lines = sessionpart.split('\r\n');
  14083. for (var j = 0; j < lines.length; j++) {
  14084. if (lines[j].substring(0, needle.length) == needle) {
  14085. return lines[j];
  14086. }
  14087. }
  14088. return false;
  14089. },
  14090. find_lines: function (haystack, needle, sessionpart) {
  14091. var lines = haystack.split('\r\n'),
  14092. needles = [];
  14093. for (var i = 0; i < lines.length; i++) {
  14094. if (lines[i].substring(0, needle.length) == needle)
  14095. needles.push(lines[i]);
  14096. }
  14097. if (needles.length || !sessionpart) {
  14098. return needles;
  14099. }
  14100. // search session part
  14101. lines = sessionpart.split('\r\n');
  14102. for (var j = 0; j < lines.length; j++) {
  14103. if (lines[j].substring(0, needle.length) == needle) {
  14104. needles.push(lines[j]);
  14105. }
  14106. }
  14107. return needles;
  14108. },
  14109. candidateToJingle: function (line) {
  14110. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  14111. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  14112. if (line.indexOf('candidate:') === 0) {
  14113. line = 'a=' + line;
  14114. } else if (line.substring(0, 12) != 'a=candidate:') {
  14115. console.log('parseCandidate called with a line that is not a candidate line');
  14116. console.log(line);
  14117. return null;
  14118. }
  14119. if (line.substring(line.length - 2) == '\r\n') // chomp it
  14120. line = line.substring(0, line.length - 2);
  14121. var candidate = {},
  14122. elems = line.split(' '),
  14123. i;
  14124. if (elems[6] != 'typ') {
  14125. console.log('did not find typ in the right place');
  14126. console.log(line);
  14127. return null;
  14128. }
  14129. candidate.foundation = elems[0].substring(12);
  14130. candidate.component = elems[1];
  14131. candidate.protocol = elems[2].toLowerCase();
  14132. candidate.priority = elems[3];
  14133. candidate.ip = elems[4];
  14134. candidate.port = elems[5];
  14135. // elems[6] => "typ"
  14136. candidate.type = elems[7];
  14137. candidate.generation = '0'; // default, may be overwritten below
  14138. for (i = 8; i < elems.length; i += 2) {
  14139. switch (elems[i]) {
  14140. case 'raddr':
  14141. candidate['rel-addr'] = elems[i + 1];
  14142. break;
  14143. case 'rport':
  14144. candidate['rel-port'] = elems[i + 1];
  14145. break;
  14146. case 'generation':
  14147. candidate.generation = elems[i + 1];
  14148. break;
  14149. case 'tcptype':
  14150. candidate.tcptype = elems[i + 1];
  14151. break;
  14152. default: // TODO
  14153. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14154. }
  14155. }
  14156. candidate.network = '1';
  14157. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14158. return candidate;
  14159. },
  14160. candidateFromJingle: function (cand) {
  14161. var line = 'a=candidate:';
  14162. line += cand.getAttribute('foundation');
  14163. line += ' ';
  14164. line += cand.getAttribute('component');
  14165. line += ' ';
  14166. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  14167. line += ' ';
  14168. line += cand.getAttribute('priority');
  14169. line += ' ';
  14170. line += cand.getAttribute('ip');
  14171. line += ' ';
  14172. line += cand.getAttribute('port');
  14173. line += ' ';
  14174. line += 'typ';
  14175. line += ' ' + cand.getAttribute('type');
  14176. line += ' ';
  14177. switch (cand.getAttribute('type')) {
  14178. case 'srflx':
  14179. case 'prflx':
  14180. case 'relay':
  14181. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  14182. line += 'raddr';
  14183. line += ' ';
  14184. line += cand.getAttribute('rel-addr');
  14185. line += ' ';
  14186. line += 'rport';
  14187. line += ' ';
  14188. line += cand.getAttribute('rel-port');
  14189. line += ' ';
  14190. }
  14191. break;
  14192. }
  14193. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  14194. line += 'tcptype';
  14195. line += ' ';
  14196. line += cand.getAttribute('tcptype');
  14197. line += ' ';
  14198. }
  14199. line += 'generation';
  14200. line += ' ';
  14201. line += cand.getAttribute('generation') || '0';
  14202. return line + '\r\n';
  14203. }
  14204. };
  14205. module.exports = SDPUtil;
  14206. },{}],59:[function(require,module,exports){
  14207. var RTC = require('../RTC/RTC');
  14208. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  14209. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14210. var SSRCReplacement = require("./LocalSSRCReplacement");
  14211. function TraceablePeerConnection(ice_config, constraints, session) {
  14212. var self = this;
  14213. var RTCPeerConnectionType = null;
  14214. if (RTCBrowserType.isFirefox()) {
  14215. RTCPeerConnectionType = mozRTCPeerConnection;
  14216. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  14217. RTCPeerConnectionType = RTCPeerConnection;
  14218. } else {
  14219. RTCPeerConnectionType = webkitRTCPeerConnection;
  14220. }
  14221. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  14222. this.updateLog = [];
  14223. this.stats = {};
  14224. this.statsinterval = null;
  14225. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  14226. var Interop = require('sdp-interop').Interop;
  14227. this.interop = new Interop();
  14228. var Simulcast = require('sdp-simulcast');
  14229. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  14230. // override as desired
  14231. this.trace = function (what, info) {
  14232. /*console.warn('WTRACE', what, info);
  14233. if (info && RTCBrowserType.isIExplorer()) {
  14234. if (info.length > 1024) {
  14235. console.warn('WTRACE', what, info.substr(1024));
  14236. }
  14237. if (info.length > 2048) {
  14238. console.warn('WTRACE', what, info.substr(2048));
  14239. }
  14240. }*/
  14241. self.updateLog.push({
  14242. time: new Date(),
  14243. type: what,
  14244. value: info || ""
  14245. });
  14246. };
  14247. this.onicecandidate = null;
  14248. this.peerconnection.onicecandidate = function (event) {
  14249. // FIXME: this causes stack overflow with Temasys Plugin
  14250. if (!RTCBrowserType.isTemasysPluginUsed())
  14251. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  14252. if (self.onicecandidate !== null) {
  14253. self.onicecandidate(event);
  14254. }
  14255. };
  14256. this.onaddstream = null;
  14257. this.peerconnection.onaddstream = function (event) {
  14258. self.trace('onaddstream', event.stream.id);
  14259. if (self.onaddstream !== null) {
  14260. self.onaddstream(event);
  14261. }
  14262. };
  14263. this.onremovestream = null;
  14264. this.peerconnection.onremovestream = function (event) {
  14265. self.trace('onremovestream', event.stream.id);
  14266. if (self.onremovestream !== null) {
  14267. self.onremovestream(event);
  14268. }
  14269. };
  14270. this.onsignalingstatechange = null;
  14271. this.peerconnection.onsignalingstatechange = function (event) {
  14272. self.trace('onsignalingstatechange', self.signalingState);
  14273. if (self.onsignalingstatechange !== null) {
  14274. self.onsignalingstatechange(event);
  14275. }
  14276. };
  14277. this.oniceconnectionstatechange = null;
  14278. this.peerconnection.oniceconnectionstatechange = function (event) {
  14279. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14280. if (self.oniceconnectionstatechange !== null) {
  14281. self.oniceconnectionstatechange(event);
  14282. }
  14283. };
  14284. this.onnegotiationneeded = null;
  14285. this.peerconnection.onnegotiationneeded = function (event) {
  14286. self.trace('onnegotiationneeded');
  14287. if (self.onnegotiationneeded !== null) {
  14288. self.onnegotiationneeded(event);
  14289. }
  14290. };
  14291. self.ondatachannel = null;
  14292. this.peerconnection.ondatachannel = function (event) {
  14293. self.trace('ondatachannel', event);
  14294. if (self.ondatachannel !== null) {
  14295. self.ondatachannel(event);
  14296. }
  14297. };
  14298. // XXX: do all non-firefox browsers which we support also support this?
  14299. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  14300. this.statsinterval = window.setInterval(function() {
  14301. self.peerconnection.getStats(function(stats) {
  14302. var results = stats.result();
  14303. var now = new Date();
  14304. for (var i = 0; i < results.length; ++i) {
  14305. results[i].names().forEach(function (name) {
  14306. var id = results[i].id + '-' + name;
  14307. if (!self.stats[id]) {
  14308. self.stats[id] = {
  14309. startTime: now,
  14310. endTime: now,
  14311. values: [],
  14312. times: []
  14313. };
  14314. }
  14315. self.stats[id].values.push(results[i].stat(name));
  14316. self.stats[id].times.push(now.getTime());
  14317. if (self.stats[id].values.length > self.maxstats) {
  14318. self.stats[id].values.shift();
  14319. self.stats[id].times.shift();
  14320. }
  14321. self.stats[id].endTime = now;
  14322. });
  14323. }
  14324. });
  14325. }, 1000);
  14326. }
  14327. }
  14328. /**
  14329. * Returns a string representation of a SessionDescription object.
  14330. */
  14331. var dumpSDP = function(description) {
  14332. if (typeof description === 'undefined' || description == null) {
  14333. return '';
  14334. }
  14335. return 'type: ' + description.type + '\r\n' + description.sdp;
  14336. };
  14337. /**
  14338. * Takes a SessionDescription object and returns a "normalized" version.
  14339. * Currently it only takes care of ordering the a=ssrc lines.
  14340. */
  14341. var normalizePlanB = function(desc) {
  14342. if (typeof desc !== 'object' || desc === null ||
  14343. typeof desc.sdp !== 'string') {
  14344. console.warn('An empty description was passed as an argument.');
  14345. return desc;
  14346. }
  14347. var transform = require('sdp-transform');
  14348. var session = transform.parse(desc.sdp);
  14349. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  14350. Array.isArray(session.media)) {
  14351. session.media.forEach(function (mLine) {
  14352. // Chrome appears to be picky about the order in which a=ssrc lines
  14353. // are listed in an m-line when rtx is enabled (and thus there are
  14354. // a=ssrc-group lines with FID semantics). Specifically if we have
  14355. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  14356. // the "a=ssrc:S1" lines, SRD fails.
  14357. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  14358. // first.
  14359. var firstSsrcs = [];
  14360. var newSsrcLines = [];
  14361. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  14362. mLine.ssrcGroups.forEach(function (group) {
  14363. if (typeof group.semantics !== 'undefined' &&
  14364. group.semantics === 'FID') {
  14365. if (typeof group.ssrcs !== 'undefined') {
  14366. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14367. }
  14368. }
  14369. });
  14370. }
  14371. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14372. for (var i = 0; i<mLine.ssrcs.length; i++){
  14373. if (typeof mLine.ssrcs[i] === 'object'
  14374. && typeof mLine.ssrcs[i].id !== 'undefined'
  14375. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14376. newSsrcLines.push(mLine.ssrcs[i]);
  14377. delete mLine.ssrcs[i];
  14378. }
  14379. }
  14380. for (var i = 0; i<mLine.ssrcs.length; i++){
  14381. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14382. newSsrcLines.push(mLine.ssrcs[i]);
  14383. }
  14384. }
  14385. mLine.ssrcs = newSsrcLines;
  14386. }
  14387. });
  14388. }
  14389. var resStr = transform.write(session);
  14390. return new RTCSessionDescription({
  14391. type: desc.type,
  14392. sdp: resStr
  14393. });
  14394. };
  14395. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14396. TraceablePeerConnection.prototype.__defineGetter__(
  14397. 'signalingState',
  14398. function() { return this.peerconnection.signalingState; });
  14399. TraceablePeerConnection.prototype.__defineGetter__(
  14400. 'iceConnectionState',
  14401. function() { return this.peerconnection.iceConnectionState; });
  14402. TraceablePeerConnection.prototype.__defineGetter__(
  14403. 'localDescription',
  14404. function() {
  14405. var desc = this.peerconnection.localDescription;
  14406. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  14407. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14408. // if we're running on FF, transform to Plan B first.
  14409. if (RTCBrowserType.usesUnifiedPlan()) {
  14410. desc = this.interop.toPlanB(desc);
  14411. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14412. }
  14413. return desc;
  14414. });
  14415. TraceablePeerConnection.prototype.__defineGetter__(
  14416. 'remoteDescription',
  14417. function() {
  14418. var desc = this.peerconnection.remoteDescription;
  14419. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14420. // if we're running on FF, transform to Plan B first.
  14421. if (RTCBrowserType.usesUnifiedPlan()) {
  14422. desc = this.interop.toPlanB(desc);
  14423. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14424. }
  14425. return desc;
  14426. });
  14427. }
  14428. TraceablePeerConnection.prototype.addStream = function (stream) {
  14429. this.trace('addStream', stream.id);
  14430. try
  14431. {
  14432. this.peerconnection.addStream(stream);
  14433. }
  14434. catch (e)
  14435. {
  14436. console.error(e);
  14437. }
  14438. };
  14439. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14440. this.trace('removeStream', stream.id);
  14441. if(stopStreams) {
  14442. stream.getAudioTracks().forEach(function (track) {
  14443. // stop() not supported with IE
  14444. if (track.stop) {
  14445. track.stop();
  14446. }
  14447. });
  14448. stream.getVideoTracks().forEach(function (track) {
  14449. // stop() not supported with IE
  14450. if (track.stop) {
  14451. track.stop();
  14452. }
  14453. });
  14454. if (stream.stop) {
  14455. stream.stop();
  14456. }
  14457. }
  14458. try {
  14459. // FF doesn't support this yet.
  14460. if (this.peerconnection.removeStream)
  14461. this.peerconnection.removeStream(stream);
  14462. } catch (e) {
  14463. console.error(e);
  14464. }
  14465. };
  14466. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14467. this.trace('createDataChannel', label, opts);
  14468. return this.peerconnection.createDataChannel(label, opts);
  14469. };
  14470. TraceablePeerConnection.prototype.setLocalDescription
  14471. = function (description, successCallback, failureCallback) {
  14472. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14473. // if we're running on FF, transform to Plan A first.
  14474. if (RTCBrowserType.usesUnifiedPlan()) {
  14475. description = this.interop.toUnifiedPlan(description);
  14476. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14477. }
  14478. var self = this;
  14479. this.peerconnection.setLocalDescription(description,
  14480. function () {
  14481. self.trace('setLocalDescriptionOnSuccess');
  14482. successCallback();
  14483. },
  14484. function (err) {
  14485. self.trace('setLocalDescriptionOnFailure', err);
  14486. failureCallback(err);
  14487. }
  14488. );
  14489. /*
  14490. if (this.statsinterval === null && this.maxstats > 0) {
  14491. // start gathering stats
  14492. }
  14493. */
  14494. };
  14495. TraceablePeerConnection.prototype.setRemoteDescription
  14496. = function (description, successCallback, failureCallback) {
  14497. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14498. // TODO the focus should squeze or explode the remote simulcast
  14499. description = this.simulcast.mungeRemoteDescription(description);
  14500. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14501. // if we're running on FF, transform to Plan A first.
  14502. if (RTCBrowserType.usesUnifiedPlan()) {
  14503. description = this.interop.toUnifiedPlan(description);
  14504. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14505. }
  14506. if (RTCBrowserType.usesPlanB()) {
  14507. description = normalizePlanB(description);
  14508. }
  14509. var self = this;
  14510. this.peerconnection.setRemoteDescription(description,
  14511. function () {
  14512. self.trace('setRemoteDescriptionOnSuccess');
  14513. successCallback();
  14514. },
  14515. function (err) {
  14516. self.trace('setRemoteDescriptionOnFailure', err);
  14517. failureCallback(err);
  14518. }
  14519. );
  14520. /*
  14521. if (this.statsinterval === null && this.maxstats > 0) {
  14522. // start gathering stats
  14523. }
  14524. */
  14525. };
  14526. TraceablePeerConnection.prototype.close = function () {
  14527. this.trace('stop');
  14528. if (this.statsinterval !== null) {
  14529. window.clearInterval(this.statsinterval);
  14530. this.statsinterval = null;
  14531. }
  14532. this.peerconnection.close();
  14533. };
  14534. TraceablePeerConnection.prototype.createOffer
  14535. = function (successCallback, failureCallback, constraints) {
  14536. var self = this;
  14537. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14538. this.peerconnection.createOffer(
  14539. function (offer) {
  14540. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14541. // NOTE this is not tested because in meet the focus generates the
  14542. // offer.
  14543. // if we're running on FF, transform to Plan B first.
  14544. if (RTCBrowserType.usesUnifiedPlan()) {
  14545. offer = self.interop.toPlanB(offer);
  14546. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14547. }
  14548. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  14549. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14550. offer = self.simulcast.mungeLocalDescription(offer);
  14551. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14552. }
  14553. successCallback(offer);
  14554. },
  14555. function(err) {
  14556. self.trace('createOfferOnFailure', err);
  14557. failureCallback(err);
  14558. },
  14559. constraints
  14560. );
  14561. };
  14562. TraceablePeerConnection.prototype.createAnswer
  14563. = function (successCallback, failureCallback, constraints) {
  14564. var self = this;
  14565. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14566. this.peerconnection.createAnswer(
  14567. function (answer) {
  14568. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  14569. // if we're running on FF, transform to Plan A first.
  14570. if (RTCBrowserType.usesUnifiedPlan()) {
  14571. answer = self.interop.toPlanB(answer);
  14572. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  14573. }
  14574. // munge local video SSRC
  14575. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  14576. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14577. answer = self.simulcast.mungeLocalDescription(answer);
  14578. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  14579. }
  14580. successCallback(answer);
  14581. },
  14582. function(err) {
  14583. self.trace('createAnswerOnFailure', err);
  14584. failureCallback(err);
  14585. },
  14586. constraints
  14587. );
  14588. };
  14589. TraceablePeerConnection.prototype.addIceCandidate
  14590. = function (candidate, successCallback, failureCallback) {
  14591. //var self = this;
  14592. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14593. this.peerconnection.addIceCandidate(candidate);
  14594. /* maybe later
  14595. this.peerconnection.addIceCandidate(candidate,
  14596. function () {
  14597. self.trace('addIceCandidateOnSuccess');
  14598. successCallback();
  14599. },
  14600. function (err) {
  14601. self.trace('addIceCandidateOnFailure', err);
  14602. failureCallback(err);
  14603. }
  14604. );
  14605. */
  14606. };
  14607. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14608. // TODO: Is this the correct way to handle Opera, Temasys?
  14609. if (RTCBrowserType.isFirefox()) {
  14610. // ignore for now...
  14611. if(!errback)
  14612. errback = function () {};
  14613. this.peerconnection.getStats(null, callback, errback);
  14614. } else {
  14615. this.peerconnection.getStats(callback);
  14616. }
  14617. };
  14618. module.exports = TraceablePeerConnection;
  14619. },{"../../service/xmpp/XMPPEvents":169,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"./LocalSSRCReplacement":55,"sdp-interop":92,"sdp-simulcast":99,"sdp-transform":106}],60:[function(require,module,exports){
  14620. /* global $, $iq, APP, config, messageHandler,
  14621. roomName, sessionTerminated, Strophe, Util */
  14622. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14623. var Settings = require("../settings/Settings");
  14624. var AuthenticationEvents
  14625. = require("../../service/authentication/AuthenticationEvents");
  14626. /**
  14627. * Contains logic responsible for enabling/disabling functionality available
  14628. * only to moderator users.
  14629. */
  14630. var connection = null;
  14631. var focusUserJid;
  14632. function createExpBackoffTimer(step) {
  14633. var count = 1;
  14634. return function (reset) {
  14635. // Reset call
  14636. if (reset) {
  14637. count = 1;
  14638. return;
  14639. }
  14640. // Calculate next timeout
  14641. var timeout = Math.pow(2, count - 1);
  14642. count += 1;
  14643. return timeout * step;
  14644. };
  14645. }
  14646. var getNextTimeout = createExpBackoffTimer(1000);
  14647. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14648. // External authentication stuff
  14649. var externalAuthEnabled = false;
  14650. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14651. // it will be enabled automatically if focus detects the component through
  14652. // service discovery.
  14653. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14654. var eventEmitter = null;
  14655. var Moderator = {
  14656. isModerator: function () {
  14657. return connection && connection.emuc.isModerator();
  14658. },
  14659. isPeerModerator: function (peerJid) {
  14660. return connection &&
  14661. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14662. },
  14663. isExternalAuthEnabled: function () {
  14664. return externalAuthEnabled;
  14665. },
  14666. isSipGatewayEnabled: function () {
  14667. return sipGatewayEnabled;
  14668. },
  14669. setConnection: function (con) {
  14670. connection = con;
  14671. },
  14672. init: function (xmpp, emitter) {
  14673. this.xmppService = xmpp;
  14674. eventEmitter = emitter;
  14675. // Message listener that talks to POPUP window
  14676. function listener(event) {
  14677. if (event.data && event.data.sessionId) {
  14678. if (event.origin !== window.location.origin) {
  14679. console.warn("Ignoring sessionId from different origin: " +
  14680. event.origin);
  14681. return;
  14682. }
  14683. localStorage.setItem('sessionId', event.data.sessionId);
  14684. // After popup is closed we will authenticate
  14685. }
  14686. }
  14687. // Register
  14688. if (window.addEventListener) {
  14689. window.addEventListener("message", listener, false);
  14690. } else {
  14691. window.attachEvent("onmessage", listener);
  14692. }
  14693. },
  14694. onMucMemberLeft: function (jid) {
  14695. console.info("Someone left is it focus ? " + jid);
  14696. var resource = Strophe.getResourceFromJid(jid);
  14697. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14698. console.info(
  14699. "Focus has left the room - leaving conference");
  14700. //hangUp();
  14701. // We'd rather reload to have everything re-initialized
  14702. // FIXME: show some message before reload
  14703. location.reload();
  14704. }
  14705. },
  14706. setFocusUserJid: function (focusJid) {
  14707. if (!focusUserJid) {
  14708. focusUserJid = focusJid;
  14709. console.info("Focus jid set to: " + focusUserJid);
  14710. }
  14711. },
  14712. getFocusUserJid: function () {
  14713. return focusUserJid;
  14714. },
  14715. getFocusComponent: function () {
  14716. // Get focus component address
  14717. var focusComponent = config.hosts.focus;
  14718. // If not specified use default: 'focus.domain'
  14719. if (!focusComponent) {
  14720. focusComponent = 'focus.' + config.hosts.domain;
  14721. }
  14722. return focusComponent;
  14723. },
  14724. createConferenceIq: function (roomName) {
  14725. // Generate create conference IQ
  14726. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14727. // Session Id used for authentication
  14728. var sessionId = localStorage.getItem('sessionId');
  14729. var machineUID = Settings.getSettings().uid;
  14730. console.info(
  14731. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14732. elem.c('conference', {
  14733. xmlns: 'http://jitsi.org/protocol/focus',
  14734. room: roomName,
  14735. 'machine-uid': machineUID
  14736. });
  14737. if (sessionId) {
  14738. elem.attrs({ 'session-id': sessionId});
  14739. }
  14740. if (config.hosts.bridge !== undefined) {
  14741. elem.c(
  14742. 'property',
  14743. { name: 'bridge', value: config.hosts.bridge})
  14744. .up();
  14745. }
  14746. // Tell the focus we have Jigasi configured
  14747. if (config.hosts.call_control !== undefined) {
  14748. elem.c(
  14749. 'property',
  14750. { name: 'call_control', value: config.hosts.call_control})
  14751. .up();
  14752. }
  14753. if (config.channelLastN !== undefined) {
  14754. elem.c(
  14755. 'property',
  14756. { name: 'channelLastN', value: config.channelLastN})
  14757. .up();
  14758. }
  14759. if (config.adaptiveLastN !== undefined) {
  14760. elem.c(
  14761. 'property',
  14762. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14763. .up();
  14764. }
  14765. if (config.adaptiveSimulcast !== undefined) {
  14766. elem.c(
  14767. 'property',
  14768. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14769. .up();
  14770. }
  14771. if (config.openSctp !== undefined) {
  14772. elem.c(
  14773. 'property',
  14774. { name: 'openSctp', value: config.openSctp})
  14775. .up();
  14776. }
  14777. if(config.startAudioMuted !== undefined)
  14778. {
  14779. elem.c(
  14780. 'property',
  14781. { name: 'startAudioMuted', value: config.startAudioMuted})
  14782. .up();
  14783. }
  14784. if(config.startVideoMuted !== undefined)
  14785. {
  14786. elem.c(
  14787. 'property',
  14788. { name: 'startVideoMuted', value: config.startVideoMuted})
  14789. .up();
  14790. }
  14791. elem.c(
  14792. 'property',
  14793. { name: 'simulcastMode', value: 'rewriting'})
  14794. .up();
  14795. elem.up();
  14796. return elem;
  14797. },
  14798. parseSessionId: function (resultIq) {
  14799. var sessionId = $(resultIq).find('conference').attr('session-id');
  14800. if (sessionId) {
  14801. console.info('Received sessionId: ' + sessionId);
  14802. localStorage.setItem('sessionId', sessionId);
  14803. }
  14804. },
  14805. parseConfigOptions: function (resultIq) {
  14806. Moderator.setFocusUserJid(
  14807. $(resultIq).find('conference').attr('focusjid'));
  14808. var authenticationEnabled
  14809. = $(resultIq).find(
  14810. '>conference>property' +
  14811. '[name=\'authentication\'][value=\'true\']').length > 0;
  14812. console.info("Authentication enabled: " + authenticationEnabled);
  14813. externalAuthEnabled = $(resultIq).find(
  14814. '>conference>property' +
  14815. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14816. console.info('External authentication enabled: ' + externalAuthEnabled);
  14817. if (!externalAuthEnabled) {
  14818. // We expect to receive sessionId in 'internal' authentication mode
  14819. Moderator.parseSessionId(resultIq);
  14820. }
  14821. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14822. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14823. authenticationEnabled, authIdentity);
  14824. // Check if focus has auto-detected Jigasi component(this will be also
  14825. // included if we have passed our host from the config)
  14826. if ($(resultIq).find(
  14827. '>conference>property' +
  14828. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14829. sipGatewayEnabled = true;
  14830. }
  14831. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14832. },
  14833. // FIXME: we need to show the fact that we're waiting for the focus
  14834. // to the user(or that focus is not available)
  14835. allocateConferenceFocus: function (roomName, callback) {
  14836. // Try to use focus user JID from the config
  14837. Moderator.setFocusUserJid(config.focusUserJid);
  14838. // Send create conference IQ
  14839. var iq = Moderator.createConferenceIq(roomName);
  14840. var self = this;
  14841. connection.sendIQ(
  14842. iq,
  14843. function (result) {
  14844. // Setup config options
  14845. Moderator.parseConfigOptions(result);
  14846. if ('true' === $(result).find('conference').attr('ready')) {
  14847. // Reset both timers
  14848. getNextTimeout(true);
  14849. getNextErrorTimeout(true);
  14850. // Exec callback
  14851. callback();
  14852. } else {
  14853. var waitMs = getNextTimeout();
  14854. console.info("Waiting for the focus... " + waitMs);
  14855. // Reset error timeout
  14856. getNextErrorTimeout(true);
  14857. window.setTimeout(
  14858. function () {
  14859. Moderator.allocateConferenceFocus(
  14860. roomName, callback);
  14861. }, waitMs);
  14862. }
  14863. },
  14864. function (error) {
  14865. // Invalid session ? remove and try again
  14866. // without session ID to get a new one
  14867. var invalidSession
  14868. = $(error).find('>error>session-invalid').length;
  14869. if (invalidSession) {
  14870. console.info("Session expired! - removing");
  14871. localStorage.removeItem("sessionId");
  14872. }
  14873. if ($(error).find('>error>graceful-shutdown').length) {
  14874. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14875. return;
  14876. }
  14877. // Check for error returned by the reservation system
  14878. var reservationErr = $(error).find('>error>reservation-error');
  14879. if (reservationErr.length) {
  14880. // Trigger error event
  14881. var errorCode = reservationErr.attr('error-code');
  14882. var errorMsg;
  14883. if ($(error).find('>error>text')) {
  14884. errorMsg = $(error).find('>error>text').text();
  14885. }
  14886. eventEmitter.emit(
  14887. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14888. return;
  14889. }
  14890. // Not authorized to create new room
  14891. if ($(error).find('>error>not-authorized').length) {
  14892. console.warn("Unauthorized to start the conference", error);
  14893. var toDomain
  14894. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14895. if (toDomain !== config.hosts.anonymousdomain) {
  14896. // FIXME: "is external" should come either from
  14897. // the focus or config.js
  14898. externalAuthEnabled = true;
  14899. }
  14900. eventEmitter.emit(
  14901. XMPPEvents.AUTHENTICATION_REQUIRED,
  14902. function () {
  14903. Moderator.allocateConferenceFocus(
  14904. roomName, callback);
  14905. });
  14906. return;
  14907. }
  14908. var waitMs = getNextErrorTimeout();
  14909. console.error("Focus error, retry after " + waitMs, error);
  14910. // Show message
  14911. var focusComponent = Moderator.getFocusComponent();
  14912. var retrySec = waitMs / 1000;
  14913. // FIXME: message is duplicated ?
  14914. // Do not show in case of session invalid
  14915. // which means just a retry
  14916. if (!invalidSession) {
  14917. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  14918. focusComponent, retrySec);
  14919. }
  14920. // Reset response timeout
  14921. getNextTimeout(true);
  14922. window.setTimeout(
  14923. function () {
  14924. Moderator.allocateConferenceFocus(roomName, callback);
  14925. }, waitMs);
  14926. }
  14927. );
  14928. },
  14929. getLoginUrl: function (roomName, urlCallback) {
  14930. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14931. iq.c('login-url', {
  14932. xmlns: 'http://jitsi.org/protocol/focus',
  14933. room: roomName,
  14934. 'machine-uid': Settings.getSettings().uid
  14935. });
  14936. connection.sendIQ(
  14937. iq,
  14938. function (result) {
  14939. var url = $(result).find('login-url').attr('url');
  14940. url = url = decodeURIComponent(url);
  14941. if (url) {
  14942. console.info("Got auth url: " + url);
  14943. urlCallback(url);
  14944. } else {
  14945. console.error(
  14946. "Failed to get auth url from the focus", result);
  14947. }
  14948. },
  14949. function (error) {
  14950. console.error("Get auth url error", error);
  14951. }
  14952. );
  14953. },
  14954. getPopupLoginUrl: function (roomName, urlCallback) {
  14955. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14956. iq.c('login-url', {
  14957. xmlns: 'http://jitsi.org/protocol/focus',
  14958. room: roomName,
  14959. 'machine-uid': Settings.getSettings().uid,
  14960. popup: true
  14961. });
  14962. connection.sendIQ(
  14963. iq,
  14964. function (result) {
  14965. var url = $(result).find('login-url').attr('url');
  14966. url = url = decodeURIComponent(url);
  14967. if (url) {
  14968. console.info("Got POPUP auth url: " + url);
  14969. urlCallback(url);
  14970. } else {
  14971. console.error(
  14972. "Failed to get POPUP auth url from the focus", result);
  14973. }
  14974. },
  14975. function (error) {
  14976. console.error('Get POPUP auth url error', error);
  14977. }
  14978. );
  14979. },
  14980. logout: function (callback) {
  14981. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14982. var sessionId = localStorage.getItem('sessionId');
  14983. if (!sessionId) {
  14984. callback();
  14985. return;
  14986. }
  14987. iq.c('logout', {
  14988. xmlns: 'http://jitsi.org/protocol/focus',
  14989. 'session-id': sessionId
  14990. });
  14991. connection.sendIQ(
  14992. iq,
  14993. function (result) {
  14994. var logoutUrl = $(result).find('logout').attr('logout-url');
  14995. if (logoutUrl) {
  14996. logoutUrl = decodeURIComponent(logoutUrl);
  14997. }
  14998. console.info("Log out OK, url: " + logoutUrl, result);
  14999. localStorage.removeItem('sessionId');
  15000. callback(logoutUrl);
  15001. },
  15002. function (error) {
  15003. console.error("Logout error", error);
  15004. }
  15005. );
  15006. }
  15007. };
  15008. module.exports = Moderator;
  15009. },{"../../service/authentication/AuthenticationEvents":164,"../../service/xmpp/XMPPEvents":169,"../settings/Settings":47}],61:[function(require,module,exports){
  15010. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  15011. Toolbar, Util */
  15012. var Moderator = require("./moderator");
  15013. var recordingToken = null;
  15014. var recordingEnabled;
  15015. /**
  15016. * Whether to use a jirecon component for recording, or use the videobridge
  15017. * through COLIBRI.
  15018. */
  15019. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  15020. /**
  15021. * The ID of the jirecon recording session. Jirecon generates it when we
  15022. * initially start recording, and it needs to be used in subsequent requests
  15023. * to jirecon.
  15024. */
  15025. var jireconRid = null;
  15026. /**
  15027. * The callback to update the recording button. Currently used from colibri
  15028. * after receiving a pending status.
  15029. */
  15030. var recordingStateChangeCallback = null;
  15031. function setRecordingToken(token) {
  15032. recordingToken = token;
  15033. }
  15034. function setRecordingJirecon(state, token, callback, connection) {
  15035. if (state == recordingEnabled){
  15036. return;
  15037. }
  15038. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  15039. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  15040. action: (state === 'on') ? 'start' : 'stop',
  15041. mucjid: connection.emuc.roomjid});
  15042. if (state === 'off'){
  15043. iq.attrs({rid: jireconRid});
  15044. }
  15045. console.log('Start recording');
  15046. connection.sendIQ(
  15047. iq,
  15048. function (result) {
  15049. // TODO wait for an IQ with the real status, since this is
  15050. // provisional?
  15051. jireconRid = $(result).find('recording').attr('rid');
  15052. console.log('Recording ' + ((state === 'on') ? 'started' : 'stopped') +
  15053. '(jirecon)' + result);
  15054. recordingEnabled = state;
  15055. if (state === 'off'){
  15056. jireconRid = null;
  15057. }
  15058. callback(state);
  15059. },
  15060. function (error) {
  15061. console.log('Failed to start recording, error: ', error);
  15062. callback(recordingEnabled);
  15063. });
  15064. }
  15065. // Sends a COLIBRI message which enables or disables (according to 'state')
  15066. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  15067. // with the new recording state, according to the IQ.
  15068. function setRecordingColibri(state, token, callback, connection) {
  15069. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  15070. elem.c('conference', {
  15071. xmlns: 'http://jitsi.org/protocol/colibri'
  15072. });
  15073. elem.c('recording', {state: state, token: token});
  15074. connection.sendIQ(elem,
  15075. function (result) {
  15076. console.log('Set recording "', state, '". Result:', result);
  15077. var recordingElem = $(result).find('>conference>recording');
  15078. var newState = recordingElem.attr('state');
  15079. recordingEnabled = newState;
  15080. callback(newState);
  15081. if (newState === 'pending' && recordingStateChangeCallback == null) {
  15082. recordingStateChangeCallback = callback;
  15083. connection.addHandler(function(iq){
  15084. var state = $(iq).find('recording').attr('state');
  15085. if (state)
  15086. recordingStateChangeCallback(state);
  15087. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  15088. }
  15089. },
  15090. function (error) {
  15091. console.warn(error);
  15092. callback(recordingEnabled);
  15093. }
  15094. );
  15095. }
  15096. function setRecording(state, token, callback, connection) {
  15097. if (useJirecon){
  15098. setRecordingJirecon(state, token, callback, connection);
  15099. } else {
  15100. setRecordingColibri(state, token, callback, connection);
  15101. }
  15102. }
  15103. var Recording = {
  15104. toggleRecording: function (tokenEmptyCallback, recordingStateChangeCallback, connection) {
  15105. if (!Moderator.isModerator()) {
  15106. console.log(
  15107. 'non-focus, or conference not yet organized:' +
  15108. ' not enabling recording');
  15109. return;
  15110. }
  15111. var self = this;
  15112. // Jirecon does not (currently) support a token.
  15113. if (!recordingToken && !useJirecon) {
  15114. tokenEmptyCallback(function (value) {
  15115. setRecordingToken(value);
  15116. self.toggleRecording(tokenEmptyCallback, recordingStateChangeCallback, connection);
  15117. });
  15118. return;
  15119. }
  15120. var oldState = recordingEnabled;
  15121. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  15122. setRecording(newState,
  15123. recordingToken,
  15124. function (state) {
  15125. console.log("New recording state: ", state);
  15126. if (state === oldState) {
  15127. // FIXME: new focus:
  15128. // this will not work when moderator changes
  15129. // during active session. Then it will assume that
  15130. // recording status has changed to true, but it might have
  15131. // been already true(and we only received actual status from
  15132. // the focus).
  15133. //
  15134. // SO we start with status null, so that it is initialized
  15135. // here and will fail only after second click, so if invalid
  15136. // token was used we have to press the button twice before
  15137. // current status will be fetched and token will be reset.
  15138. //
  15139. // Reliable way would be to return authentication error.
  15140. // Or status update when moderator connects.
  15141. // Or we have to stop recording session when current
  15142. // moderator leaves the room.
  15143. // Failed to change, reset the token because it might
  15144. // have been wrong
  15145. setRecordingToken(null);
  15146. }
  15147. recordingStateChangeCallback(state);
  15148. },
  15149. connection
  15150. );
  15151. }
  15152. };
  15153. module.exports = Recording;
  15154. },{"./moderator":60}],62:[function(require,module,exports){
  15155. /* jshint -W117 */
  15156. /* a simple MUC connection plugin
  15157. * can only handle a single MUC room
  15158. */
  15159. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15160. var Moderator = require("./moderator");
  15161. module.exports = function(XMPP, eventEmitter) {
  15162. Strophe.addConnectionPlugin('emuc', {
  15163. connection: null,
  15164. roomjid: null,
  15165. myroomjid: null,
  15166. members: {},
  15167. list_members: [], // so we can elect a new focus
  15168. presMap: {},
  15169. preziMap: {},
  15170. joined: false,
  15171. isOwner: false,
  15172. role: null,
  15173. focusMucJid: null,
  15174. bridgeIsDown: false,
  15175. init: function (conn) {
  15176. this.connection = conn;
  15177. },
  15178. initPresenceMap: function (myroomjid) {
  15179. this.presMap['to'] = myroomjid;
  15180. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  15181. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  15182. this.addAudioInfoToPresence(true);
  15183. }
  15184. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  15185. this.addVideoInfoToPresence(true);
  15186. }
  15187. },
  15188. doJoin: function (jid, password) {
  15189. this.myroomjid = jid;
  15190. console.info("Joined MUC as " + this.myroomjid);
  15191. this.initPresenceMap(this.myroomjid);
  15192. if (!this.roomjid) {
  15193. this.roomjid = Strophe.getBareJidFromJid(jid);
  15194. // add handlers (just once)
  15195. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  15196. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  15197. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  15198. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  15199. }
  15200. if (password !== undefined) {
  15201. this.presMap['password'] = password;
  15202. }
  15203. this.sendPresence();
  15204. },
  15205. doLeave: function () {
  15206. console.log("do leave", this.myroomjid);
  15207. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  15208. this.presMap.length = 0;
  15209. this.connection.send(pres);
  15210. },
  15211. createNonAnonymousRoom: function () {
  15212. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15213. var getForm = $iq({type: 'get', to: this.roomjid})
  15214. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15215. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15216. var self = this;
  15217. this.connection.sendIQ(getForm, function (form) {
  15218. if (!$(form).find(
  15219. '>query>x[xmlns="jabber:x:data"]' +
  15220. '>field[var="muc#roomconfig_whois"]').length) {
  15221. console.error('non-anonymous rooms not supported');
  15222. return;
  15223. }
  15224. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15225. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15226. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15227. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15228. .c('value')
  15229. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15230. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15231. .c('value').t('anyone').up().up();
  15232. self.connection.sendIQ(formSubmit);
  15233. }, function (error) {
  15234. console.error("Error getting room configuration form");
  15235. });
  15236. },
  15237. onPresence: function (pres) {
  15238. var from = pres.getAttribute('from');
  15239. // What is this for? A workaround for something?
  15240. if (pres.getAttribute('type')) {
  15241. return true;
  15242. }
  15243. // Parse etherpad tag.
  15244. var etherpad = $(pres).find('>etherpad');
  15245. if (etherpad.length) {
  15246. if (config.etherpad_base) {
  15247. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15248. }
  15249. }
  15250. var url;
  15251. // Parse prezi tag.
  15252. var presentation = $(pres).find('>prezi');
  15253. if (presentation.length) {
  15254. url = presentation.attr('url');
  15255. var current = presentation.find('>current').text();
  15256. console.log('presentation info received from', from, url);
  15257. if (this.preziMap[from] == null) {
  15258. this.preziMap[from] = url;
  15259. $(document).trigger('presentationadded.muc', [from, url, current]);
  15260. }
  15261. else {
  15262. $(document).trigger('gotoslide.muc', [from, url, current]);
  15263. }
  15264. }
  15265. else if (this.preziMap[from] != null) {
  15266. url = this.preziMap[from];
  15267. delete this.preziMap[from];
  15268. $(document).trigger('presentationremoved.muc', [from, url]);
  15269. }
  15270. // Parse audio info tag.
  15271. var audioMuted = $(pres).find('>audiomuted');
  15272. if (audioMuted.length) {
  15273. eventEmitter.emit(XMPPEvents.PARTICIPANT_AUDIO_MUTED,
  15274. from, (audioMuted.text() === "true"));
  15275. }
  15276. // Parse video info tag.
  15277. var videoMuted = $(pres).find('>videomuted');
  15278. if (videoMuted.length) {
  15279. eventEmitter.emit(XMPPEvents.PARTICIPANT_VIDEO_MUTED,
  15280. from, (videoMuted.text() === "true"));
  15281. }
  15282. var startMuted = $(pres).find('>startmuted');
  15283. if (startMuted.length && Moderator.isPeerModerator(from)) {
  15284. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15285. startMuted.attr("audio") === "true",
  15286. startMuted.attr("video") === "true");
  15287. }
  15288. var devices = $(pres).find('>devices');
  15289. if(devices.length)
  15290. {
  15291. var audio = devices.find('>audio');
  15292. var video = devices.find('>video');
  15293. var devicesValues = {audio: false, video: false};
  15294. if(audio.length && audio.text() === "true")
  15295. {
  15296. devicesValues.audio = true;
  15297. }
  15298. if(video.length && video.text() === "true")
  15299. {
  15300. devicesValues.video = true;
  15301. }
  15302. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15303. Strophe.getResourceFromJid(from), devicesValues);
  15304. }
  15305. var videoType = $(pres).find('>videoType');
  15306. if (videoType.length)
  15307. {
  15308. if (videoType.text().length)
  15309. {
  15310. eventEmitter.emit(XMPPEvents.PARTICIPANT_VIDEO_TYPE_CHANGED,
  15311. Strophe.getResourceFromJid(from), videoType.text());
  15312. }
  15313. }
  15314. var stats = $(pres).find('>stats');
  15315. if (stats.length) {
  15316. var statsObj = {};
  15317. Strophe.forEachChild(stats[0], "stat", function (el) {
  15318. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15319. });
  15320. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15321. }
  15322. // Parse status.
  15323. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15324. this.isOwner = true;
  15325. this.createNonAnonymousRoom();
  15326. }
  15327. // Parse roles.
  15328. var member = {};
  15329. member.show = $(pres).find('>show').text();
  15330. member.status = $(pres).find('>status').text();
  15331. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15332. member.affiliation = tmp.attr('affiliation');
  15333. member.role = tmp.attr('role');
  15334. // Focus recognition
  15335. member.jid = tmp.attr('jid');
  15336. member.isFocus = false;
  15337. if (member.jid
  15338. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15339. member.isFocus = true;
  15340. }
  15341. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15342. member.displayName = (nicktag.length > 0 ? nicktag.text() : null);
  15343. if (from == this.myroomjid) {
  15344. if (member.affiliation == 'owner') this.isOwner = true;
  15345. if (this.role !== member.role) {
  15346. this.role = member.role;
  15347. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15348. from, member, pres, Moderator.isModerator());
  15349. }
  15350. if (!this.joined) {
  15351. this.joined = true;
  15352. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15353. this.list_members.push(from);
  15354. }
  15355. } else if (this.members[from] === undefined) {
  15356. // new participant
  15357. this.members[from] = member;
  15358. this.list_members.push(from);
  15359. console.log('entered', from, member);
  15360. if (member.isFocus) {
  15361. this.focusMucJid = from;
  15362. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15363. }
  15364. else {
  15365. var id = $(pres).find('>userId').text();
  15366. var email = $(pres).find('>email');
  15367. if (email.length > 0) {
  15368. id = email.text();
  15369. }
  15370. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15371. }
  15372. } else {
  15373. // Presence update for existing participant
  15374. // Watch role change:
  15375. if (this.members[from].role != member.role) {
  15376. this.members[from].role = member.role;
  15377. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15378. member.role, member.displayName);
  15379. }
  15380. }
  15381. // Always trigger presence to update bindings
  15382. this.parsePresence(from, member, pres);
  15383. // Trigger status message update
  15384. if (member.status) {
  15385. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15386. }
  15387. return true;
  15388. },
  15389. onPresenceUnavailable: function (pres) {
  15390. var from = pres.getAttribute('from');
  15391. // room destroyed ?
  15392. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15393. '>destroy').length) {
  15394. var reason;
  15395. var reasonSelect = $(pres).find(
  15396. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15397. '>destroy>reason');
  15398. if (reasonSelect.length) {
  15399. reason = reasonSelect.text();
  15400. }
  15401. XMPP.disposeConference(false);
  15402. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15403. return true;
  15404. }
  15405. // Status code 110 indicates that this notification is "self-presence".
  15406. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15407. delete this.members[from];
  15408. this.list_members.splice(this.list_members.indexOf(from), 1);
  15409. this.onParticipantLeft(from);
  15410. }
  15411. // If the status code is 110 this means we're leaving and we would like
  15412. // to remove everyone else from our view, so we trigger the event.
  15413. else if (this.list_members.length > 1) {
  15414. for (var i = 0; i < this.list_members.length; i++) {
  15415. var member = this.list_members[i];
  15416. delete this.members[i];
  15417. this.list_members.splice(i, 1);
  15418. this.onParticipantLeft(member);
  15419. }
  15420. }
  15421. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15422. $(document).trigger('kicked.muc', [from]);
  15423. if (this.myroomjid === from) {
  15424. XMPP.disposeConference(false);
  15425. eventEmitter.emit(XMPPEvents.KICKED);
  15426. }
  15427. }
  15428. return true;
  15429. },
  15430. onPresenceError: function (pres) {
  15431. var from = pres.getAttribute('from');
  15432. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15433. console.log('on password required', from);
  15434. var self = this;
  15435. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15436. self.doJoin(from, value);
  15437. });
  15438. } else if ($(pres).find(
  15439. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15440. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15441. if (toDomain === config.hosts.anonymousdomain) {
  15442. // enter the room by replying with 'not-authorized'. This would
  15443. // result in reconnection from authorized domain.
  15444. // We're either missing Jicofo/Prosody config for anonymous
  15445. // domains or something is wrong.
  15446. // XMPP.promptLogin();
  15447. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15448. } else {
  15449. console.warn('onPresError ', pres);
  15450. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15451. }
  15452. } else {
  15453. console.warn('onPresError ', pres);
  15454. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15455. }
  15456. return true;
  15457. },
  15458. sendMessage: function (body, nickname) {
  15459. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15460. msg.c('body', body).up();
  15461. if (nickname) {
  15462. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15463. }
  15464. this.connection.send(msg);
  15465. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15466. },
  15467. setSubject: function (subject) {
  15468. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15469. msg.c('subject', subject);
  15470. this.connection.send(msg);
  15471. console.log("topic changed to " + subject);
  15472. },
  15473. onMessage: function (msg) {
  15474. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15475. var from = msg.getAttribute('from');
  15476. var nick =
  15477. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15478. .text() ||
  15479. Strophe.getResourceFromJid(from);
  15480. var txt = $(msg).find('>body').text();
  15481. var type = msg.getAttribute("type");
  15482. if (type == "error") {
  15483. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15484. $(msg).find('>text').text(), txt);
  15485. return true;
  15486. }
  15487. var subject = $(msg).find('>subject');
  15488. if (subject.length) {
  15489. var subjectText = subject.text();
  15490. if (subjectText || subjectText == "") {
  15491. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15492. console.log("Subject is changed to " + subjectText);
  15493. }
  15494. }
  15495. // xep-0203 delay
  15496. var stamp = $(msg).find('>delay').attr('stamp');
  15497. if (!stamp) {
  15498. // or xep-0091 delay, UTC timestamp
  15499. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15500. if (stamp) {
  15501. // the format is CCYYMMDDThh:mm:ss
  15502. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15503. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15504. }
  15505. }
  15506. if (txt) {
  15507. console.log('chat', nick, txt);
  15508. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15509. from, nick, txt, this.myroomjid, stamp);
  15510. }
  15511. return true;
  15512. },
  15513. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15514. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15515. var ob = this;
  15516. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15517. function (res) {
  15518. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15519. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15520. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15521. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15522. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15523. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15524. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15525. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15526. ob.connection.sendIQ(formsubmit,
  15527. onSuccess,
  15528. onError);
  15529. } else {
  15530. onNotSupported();
  15531. }
  15532. }, onError);
  15533. },
  15534. kick: function (jid) {
  15535. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15536. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15537. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15538. .c('reason').t('You have been kicked.').up().up().up();
  15539. this.connection.sendIQ(
  15540. kickIQ,
  15541. function (result) {
  15542. console.log('Kick participant with jid: ', jid, result);
  15543. },
  15544. function (error) {
  15545. console.log('Kick participant error: ', error);
  15546. });
  15547. },
  15548. sendPresence: function () {
  15549. if (!this.presMap['to']) {
  15550. // Too early to send presence - not initialized
  15551. return;
  15552. }
  15553. var pres = $pres({to: this.presMap['to'] });
  15554. pres.c('x', {xmlns: this.presMap['xns']});
  15555. if (this.presMap['password']) {
  15556. pres.c('password').t(this.presMap['password']).up();
  15557. }
  15558. pres.up();
  15559. // Send XEP-0115 'c' stanza that contains our capabilities info
  15560. if (this.connection.caps) {
  15561. this.connection.caps.node = config.clientNode;
  15562. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15563. }
  15564. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15565. .t(navigator.userAgent).up();
  15566. if (this.presMap['bridgeIsDown']) {
  15567. pres.c('bridgeIsDown').up();
  15568. }
  15569. if (this.presMap['email']) {
  15570. pres.c('email').t(this.presMap['email']).up();
  15571. }
  15572. if (this.presMap['userId']) {
  15573. pres.c('userId').t(this.presMap['userId']).up();
  15574. }
  15575. if (this.presMap['displayName']) {
  15576. // XEP-0172
  15577. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15578. .t(this.presMap['displayName']).up();
  15579. }
  15580. if(this.presMap["devices"])
  15581. {
  15582. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15583. .c('video').t(this.presMap['devices'].video).up().up();
  15584. }
  15585. if (this.presMap['audions']) {
  15586. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15587. .t(this.presMap['audiomuted']).up();
  15588. }
  15589. if (this.presMap['videons']) {
  15590. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15591. .t(this.presMap['videomuted']).up();
  15592. }
  15593. if (this.presMap['videoTypeNs']) {
  15594. pres.c('videoType', { xmlns: this.presMap['videoTypeNs'] })
  15595. .t(this.presMap['videoType']).up();
  15596. }
  15597. if (this.presMap['statsns']) {
  15598. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15599. for (var stat in this.presMap["stats"])
  15600. if (this.presMap["stats"][stat] != null)
  15601. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15602. pres.up();
  15603. }
  15604. if (this.presMap['prezins']) {
  15605. pres.c('prezi',
  15606. {xmlns: this.presMap['prezins'],
  15607. 'url': this.presMap['preziurl']})
  15608. .c('current').t(this.presMap['prezicurrent']).up().up();
  15609. }
  15610. if(this.presMap["startMuted"] !== undefined)
  15611. {
  15612. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15613. video: this.presMap["startMuted"].video,
  15614. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15615. delete this.presMap["startMuted"];
  15616. }
  15617. pres.up();
  15618. this.connection.send(pres);
  15619. },
  15620. addDisplayNameToPresence: function (displayName) {
  15621. this.presMap['displayName'] = displayName;
  15622. },
  15623. addDevicesToPresence: function (devices) {
  15624. this.presMap['devices'] = devices;
  15625. },
  15626. /**
  15627. * Adds the info about the type of our video stream.
  15628. * @param videoType 'camera' or 'screen'
  15629. */
  15630. addVideoTypeToPresence: function (videoType) {
  15631. this.presMap['videoTypeNs'] = 'http://jitsi.org/jitmeet/video';
  15632. this.presMap['videoType'] = videoType;
  15633. },
  15634. addPreziToPresence: function (url, currentSlide) {
  15635. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15636. this.presMap['preziurl'] = url;
  15637. this.presMap['prezicurrent'] = currentSlide;
  15638. },
  15639. removePreziFromPresence: function () {
  15640. delete this.presMap['prezins'];
  15641. delete this.presMap['preziurl'];
  15642. delete this.presMap['prezicurrent'];
  15643. },
  15644. addCurrentSlideToPresence: function (currentSlide) {
  15645. this.presMap['prezicurrent'] = currentSlide;
  15646. },
  15647. getPrezi: function (roomjid) {
  15648. return this.preziMap[roomjid];
  15649. },
  15650. addAudioInfoToPresence: function (isMuted) {
  15651. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15652. this.presMap['audiomuted'] = isMuted.toString();
  15653. },
  15654. addVideoInfoToPresence: function (isMuted) {
  15655. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15656. this.presMap['videomuted'] = isMuted.toString();
  15657. },
  15658. addConnectionInfoToPresence: function (stats) {
  15659. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15660. this.presMap['stats'] = stats;
  15661. },
  15662. findJidFromResource: function (resourceJid) {
  15663. if (resourceJid &&
  15664. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15665. return this.myroomjid;
  15666. }
  15667. var peerJid = null;
  15668. Object.keys(this.members).some(function (jid) {
  15669. peerJid = jid;
  15670. return Strophe.getResourceFromJid(jid) === resourceJid;
  15671. });
  15672. return peerJid;
  15673. },
  15674. addBridgeIsDownToPresence: function () {
  15675. this.presMap['bridgeIsDown'] = true;
  15676. },
  15677. addEmailToPresence: function (email) {
  15678. this.presMap['email'] = email;
  15679. },
  15680. addUserIdToPresence: function (userId) {
  15681. this.presMap['userId'] = userId;
  15682. },
  15683. addStartMutedToPresence: function (audio, video) {
  15684. this.presMap["startMuted"] = {audio: audio, video: video};
  15685. },
  15686. isModerator: function () {
  15687. return this.role === 'moderator';
  15688. },
  15689. getMemberRole: function (peerJid) {
  15690. if (this.members[peerJid]) {
  15691. return this.members[peerJid].role;
  15692. }
  15693. return null;
  15694. },
  15695. onParticipantLeft: function (jid) {
  15696. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15697. this.connection.jingle.terminateByJid(jid);
  15698. if (this.getPrezi(jid)) {
  15699. $(document).trigger('presentationremoved.muc',
  15700. [jid, this.getPrezi(jid)]);
  15701. }
  15702. Moderator.onMucMemberLeft(jid);
  15703. },
  15704. parsePresence: function (from, member, pres) {
  15705. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  15706. this.bridgeIsDown = true;
  15707. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15708. }
  15709. if(member.isFocus)
  15710. return;
  15711. var displayName = !config.displayJids
  15712. ? member.displayName : Strophe.getResourceFromJid(from);
  15713. if (displayName && displayName.length > 0) {
  15714. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15715. }
  15716. var id = $(pres).find('>userID').text();
  15717. var email = $(pres).find('>email');
  15718. if (email.length > 0) {
  15719. id = email.text();
  15720. }
  15721. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15722. }
  15723. });
  15724. };
  15725. },{"../../service/xmpp/XMPPEvents":169,"./moderator":60}],63:[function(require,module,exports){
  15726. /* jshint -W117 */
  15727. var JingleSession = require("./JingleSessionPC");
  15728. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15729. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15730. module.exports = function(XMPP, eventEmitter) {
  15731. Strophe.addConnectionPlugin('jingle', {
  15732. connection: null,
  15733. sessions: {},
  15734. jid2session: {},
  15735. ice_config: {iceServers: []},
  15736. pc_constraints: {},
  15737. activecall: null,
  15738. media_constraints: {
  15739. mandatory: {
  15740. 'OfferToReceiveAudio': true,
  15741. 'OfferToReceiveVideo': true
  15742. }
  15743. // MozDontOfferDataChannel: true when this is firefox
  15744. },
  15745. init: function (conn) {
  15746. this.connection = conn;
  15747. if (this.connection.disco) {
  15748. // http://xmpp.org/extensions/xep-0167.html#support
  15749. // http://xmpp.org/extensions/xep-0176.html#support
  15750. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15751. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15752. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15753. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15754. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15755. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15756. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15757. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15758. || RTCBrowserType.isTemasysPluginUsed()) {
  15759. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15760. }
  15761. // this is dealt with by SDP O/A so we don't need to announce this
  15762. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15763. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15764. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15765. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15766. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15767. }
  15768. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15769. },
  15770. onJingle: function (iq) {
  15771. var sid = $(iq).find('jingle').attr('sid');
  15772. var action = $(iq).find('jingle').attr('action');
  15773. var fromJid = iq.getAttribute('from');
  15774. // send ack first
  15775. var ack = $iq({type: 'result',
  15776. to: fromJid,
  15777. id: iq.getAttribute('id')
  15778. });
  15779. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15780. var sess = this.sessions[sid];
  15781. if ('session-initiate' != action) {
  15782. if (sess === null) {
  15783. ack.type = 'error';
  15784. ack.c('error', {type: 'cancel'})
  15785. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15786. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15787. this.connection.send(ack);
  15788. return true;
  15789. }
  15790. // local jid is not checked
  15791. if (fromJid != sess.peerjid) {
  15792. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15793. ack.type = 'error';
  15794. ack.c('error', {type: 'cancel'})
  15795. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15796. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15797. this.connection.send(ack);
  15798. return true;
  15799. }
  15800. } else if (sess !== undefined) {
  15801. // existing session with same session id
  15802. // this might be out-of-order if the sess.peerjid is the same as from
  15803. ack.type = 'error';
  15804. ack.c('error', {type: 'cancel'})
  15805. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15806. console.warn('duplicate session id', sid);
  15807. this.connection.send(ack);
  15808. return true;
  15809. }
  15810. // FIXME: check for a defined action
  15811. this.connection.send(ack);
  15812. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15813. switch (action) {
  15814. case 'session-initiate':
  15815. var startMuted = $(iq).find('jingle>startmuted');
  15816. if (startMuted && startMuted.length > 0) {
  15817. var audioMuted = startMuted.attr("audio");
  15818. var videoMuted = startMuted.attr("video");
  15819. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  15820. audioMuted === "true", videoMuted === "true");
  15821. }
  15822. sess = new JingleSession(
  15823. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15824. this.connection, XMPP, eventEmitter);
  15825. // configure session
  15826. sess.media_constraints = this.media_constraints;
  15827. sess.pc_constraints = this.pc_constraints;
  15828. sess.ice_config = this.ice_config;
  15829. sess.initialize(fromJid, false);
  15830. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15831. sess.setOffer($(iq).find('>jingle'));
  15832. this.sessions[sess.sid] = sess;
  15833. this.jid2session[sess.peerjid] = sess;
  15834. // the callback should either
  15835. // .sendAnswer and .accept
  15836. // or .sendTerminate -- not necessarily synchronous
  15837. // TODO: do we check activecall == null?
  15838. this.connection.jingle.activecall = sess;
  15839. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15840. // TODO: check affiliation and/or role
  15841. console.log('emuc data for', sess.peerjid,
  15842. this.connection.emuc.members[sess.peerjid]);
  15843. sess.sendAnswer();
  15844. sess.accept();
  15845. break;
  15846. case 'session-accept':
  15847. sess.setAnswer($(iq).find('>jingle'));
  15848. sess.accept();
  15849. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15850. break;
  15851. case 'session-terminate':
  15852. // If this is not the focus sending the terminate, we have
  15853. // nothing more to do here.
  15854. if (Object.keys(this.sessions).length < 1
  15855. || !(this.sessions[Object.keys(this.sessions)[0]]
  15856. instanceof JingleSession))
  15857. {
  15858. break;
  15859. }
  15860. console.log('terminating...', sess.sid);
  15861. sess.terminate();
  15862. this.terminate(sess.sid);
  15863. if ($(iq).find('>jingle>reason').length) {
  15864. $(document).trigger('callterminated.jingle', [
  15865. sess.sid,
  15866. sess.peerjid,
  15867. $(iq).find('>jingle>reason>:first')[0].tagName,
  15868. $(iq).find('>jingle>reason>text').text()
  15869. ]);
  15870. } else {
  15871. $(document).trigger('callterminated.jingle',
  15872. [sess.sid, sess.peerjid]);
  15873. }
  15874. break;
  15875. case 'transport-info':
  15876. sess.addIceCandidate($(iq).find('>jingle>content'));
  15877. break;
  15878. case 'session-info':
  15879. var affected;
  15880. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15881. $(document).trigger('ringing.jingle', [sess.sid]);
  15882. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15883. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15884. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15885. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15886. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15887. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15888. }
  15889. break;
  15890. case 'addsource': // FIXME: proprietary, un-jingleish
  15891. case 'source-add': // FIXME: proprietary
  15892. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15893. break;
  15894. case 'removesource': // FIXME: proprietary, un-jingleish
  15895. case 'source-remove': // FIXME: proprietary
  15896. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15897. break;
  15898. default:
  15899. console.warn('jingle action not implemented', action);
  15900. break;
  15901. }
  15902. return true;
  15903. },
  15904. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15905. var sess = new JingleSession(myjid || this.connection.jid,
  15906. Math.random().toString(36).substr(2, 12), // random string
  15907. this.connection, XMPP, eventEmitter);
  15908. // configure session
  15909. sess.media_constraints = this.media_constraints;
  15910. sess.pc_constraints = this.pc_constraints;
  15911. sess.ice_config = this.ice_config;
  15912. sess.initialize(peerjid, true);
  15913. this.sessions[sess.sid] = sess;
  15914. this.jid2session[sess.peerjid] = sess;
  15915. sess.sendOffer();
  15916. return sess;
  15917. },
  15918. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  15919. if (sid === null || sid === undefined) {
  15920. for (sid in this.sessions) {
  15921. if (this.sessions[sid].state != 'ended') {
  15922. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15923. this.sessions[sid].terminate();
  15924. }
  15925. delete this.jid2session[this.sessions[sid].peerjid];
  15926. delete this.sessions[sid];
  15927. }
  15928. } else if (this.sessions.hasOwnProperty(sid)) {
  15929. if (this.sessions[sid].state != 'ended') {
  15930. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15931. this.sessions[sid].terminate();
  15932. }
  15933. delete this.jid2session[this.sessions[sid].peerjid];
  15934. delete this.sessions[sid];
  15935. }
  15936. },
  15937. // Used to terminate a session when an unavailable presence is received.
  15938. terminateByJid: function (jid) {
  15939. if (this.jid2session.hasOwnProperty(jid)) {
  15940. var sess = this.jid2session[jid];
  15941. if (sess) {
  15942. sess.terminate();
  15943. console.log('peer went away silently', jid);
  15944. delete this.sessions[sess.sid];
  15945. delete this.jid2session[jid];
  15946. $(document).trigger('callterminated.jingle',
  15947. [sess.sid, jid], 'gone');
  15948. }
  15949. }
  15950. },
  15951. terminateRemoteByJid: function (jid, reason) {
  15952. if (this.jid2session.hasOwnProperty(jid)) {
  15953. var sess = this.jid2session[jid];
  15954. if (sess) {
  15955. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15956. sess.terminate();
  15957. console.log('terminate peer with jid', sess.sid, jid);
  15958. delete this.sessions[sess.sid];
  15959. delete this.jid2session[jid];
  15960. $(document).trigger('callterminated.jingle',
  15961. [sess.sid, jid, 'kicked']);
  15962. }
  15963. }
  15964. },
  15965. getStunAndTurnCredentials: function () {
  15966. // get stun and turn configuration from server via xep-0215
  15967. // uses time-limited credentials as described in
  15968. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15969. //
  15970. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15971. // for a prosody module which implements this
  15972. //
  15973. // currently, this doesn't work with updateIce and therefore credentials with a long
  15974. // validity have to be fetched before creating the peerconnection
  15975. // TODO: implement refresh via updateIce as described in
  15976. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15977. var self = this;
  15978. this.connection.sendIQ(
  15979. $iq({type: 'get', to: this.connection.domain})
  15980. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15981. function (res) {
  15982. var iceservers = [];
  15983. $(res).find('>services>service').each(function (idx, el) {
  15984. el = $(el);
  15985. var dict = {};
  15986. var type = el.attr('type');
  15987. switch (type) {
  15988. case 'stun':
  15989. dict.url = 'stun:' + el.attr('host');
  15990. if (el.attr('port')) {
  15991. dict.url += ':' + el.attr('port');
  15992. }
  15993. iceservers.push(dict);
  15994. break;
  15995. case 'turn':
  15996. case 'turns':
  15997. dict.url = type + ':';
  15998. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15999. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  16000. dict.url += el.attr('username') + '@';
  16001. } else {
  16002. dict.username = el.attr('username'); // only works in M28
  16003. }
  16004. }
  16005. dict.url += el.attr('host');
  16006. if (el.attr('port') && el.attr('port') != '3478') {
  16007. dict.url += ':' + el.attr('port');
  16008. }
  16009. if (el.attr('transport') && el.attr('transport') != 'udp') {
  16010. dict.url += '?transport=' + el.attr('transport');
  16011. }
  16012. if (el.attr('password')) {
  16013. dict.credential = el.attr('password');
  16014. }
  16015. iceservers.push(dict);
  16016. break;
  16017. }
  16018. });
  16019. self.ice_config.iceServers = iceservers;
  16020. },
  16021. function (err) {
  16022. console.warn('getting turn credentials failed', err);
  16023. console.warn('is mod_turncredentials or similar installed?');
  16024. }
  16025. );
  16026. // implement push?
  16027. },
  16028. /**
  16029. * Returns the data saved in 'updateLog' in a format to be logged.
  16030. */
  16031. getLog: function () {
  16032. var data = {};
  16033. var self = this;
  16034. Object.keys(this.sessions).forEach(function (sid) {
  16035. var session = self.sessions[sid];
  16036. if (session.peerconnection && session.peerconnection.updateLog) {
  16037. // FIXME: should probably be a .dump call
  16038. data["jingle_" + session.sid] = {
  16039. updateLog: session.peerconnection.updateLog,
  16040. stats: session.peerconnection.stats,
  16041. url: window.location.href
  16042. };
  16043. }
  16044. });
  16045. return data;
  16046. }
  16047. });
  16048. };
  16049. },{"../../service/xmpp/XMPPEvents":169,"../RTC/RTCBrowserType":8,"./JingleSessionPC":54}],64:[function(require,module,exports){
  16050. /* global Strophe */
  16051. module.exports = function () {
  16052. Strophe.addConnectionPlugin('logger', {
  16053. // logs raw stanzas and makes them available for download as JSON
  16054. connection: null,
  16055. log: [],
  16056. init: function (conn) {
  16057. this.connection = conn;
  16058. this.connection.rawInput = this.log_incoming.bind(this);
  16059. this.connection.rawOutput = this.log_outgoing.bind(this);
  16060. },
  16061. log_incoming: function (stanza) {
  16062. this.log.push([new Date().getTime(), 'incoming', stanza]);
  16063. },
  16064. log_outgoing: function (stanza) {
  16065. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  16066. }
  16067. });
  16068. };
  16069. },{}],65:[function(require,module,exports){
  16070. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  16071. setAudioMuted, Strophe */
  16072. /**
  16073. * Moderate connection plugin.
  16074. */
  16075. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16076. module.exports = function (XMPP, eventEmitter) {
  16077. Strophe.addConnectionPlugin('moderate', {
  16078. connection: null,
  16079. init: function (conn) {
  16080. this.connection = conn;
  16081. this.connection.addHandler(this.onMute.bind(this),
  16082. 'http://jitsi.org/jitmeet/audio',
  16083. 'iq',
  16084. 'set',
  16085. null,
  16086. null);
  16087. },
  16088. setMute: function (jid, mute) {
  16089. console.info("set mute", mute);
  16090. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  16091. .c('mute', {
  16092. xmlns: 'http://jitsi.org/jitmeet/audio',
  16093. jid: jid
  16094. })
  16095. .t(mute.toString())
  16096. .up();
  16097. this.connection.sendIQ(
  16098. iqToFocus,
  16099. function (result) {
  16100. console.log('set mute', result);
  16101. },
  16102. function (error) {
  16103. console.log('set mute error', error);
  16104. });
  16105. },
  16106. onMute: function (iq) {
  16107. var from = iq.getAttribute('from');
  16108. if (from !== this.connection.emuc.focusMucJid) {
  16109. console.warn("Ignored mute from non focus peer");
  16110. return false;
  16111. }
  16112. var mute = $(iq).find('mute');
  16113. if (mute.length) {
  16114. var doMuteAudio = mute.text() === "true";
  16115. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  16116. XMPP.forceMuted = doMuteAudio;
  16117. }
  16118. return true;
  16119. },
  16120. eject: function (jid) {
  16121. // We're not the focus, so can't terminate
  16122. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  16123. this.connection.emuc.kick(jid);
  16124. }
  16125. });
  16126. }
  16127. },{"../../service/xmpp/XMPPEvents":169}],66:[function(require,module,exports){
  16128. /* jshint -W117 */
  16129. module.exports = function() {
  16130. Strophe.addConnectionPlugin('rayo',
  16131. {
  16132. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  16133. connection: null,
  16134. init: function (conn) {
  16135. this.connection = conn;
  16136. if (this.connection.disco) {
  16137. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  16138. }
  16139. this.connection.addHandler(
  16140. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  16141. },
  16142. onRayo: function (iq) {
  16143. console.info("Rayo IQ", iq);
  16144. },
  16145. dial: function (to, from, roomName, roomPass) {
  16146. var self = this;
  16147. var req = $iq(
  16148. {
  16149. type: 'set',
  16150. to: this.connection.emuc.focusMucJid
  16151. }
  16152. );
  16153. req.c('dial',
  16154. {
  16155. xmlns: this.RAYO_XMLNS,
  16156. to: to,
  16157. from: from
  16158. });
  16159. req.c('header',
  16160. {
  16161. name: 'JvbRoomName',
  16162. value: roomName
  16163. }).up();
  16164. if (roomPass !== null && roomPass.length) {
  16165. req.c('header',
  16166. {
  16167. name: 'JvbRoomPassword',
  16168. value: roomPass
  16169. }).up();
  16170. }
  16171. this.connection.sendIQ(
  16172. req,
  16173. function (result) {
  16174. console.info('Dial result ', result);
  16175. var resource = $(result).find('ref').attr('uri');
  16176. this.call_resource = resource.substr('xmpp:'.length);
  16177. console.info(
  16178. "Received call resource: " + this.call_resource);
  16179. },
  16180. function (error) {
  16181. console.info('Dial error ', error);
  16182. }
  16183. );
  16184. },
  16185. hang_up: function () {
  16186. if (!this.call_resource) {
  16187. console.warn("No call in progress");
  16188. return;
  16189. }
  16190. var self = this;
  16191. var req = $iq(
  16192. {
  16193. type: 'set',
  16194. to: this.call_resource
  16195. }
  16196. );
  16197. req.c('hangup',
  16198. {
  16199. xmlns: this.RAYO_XMLNS
  16200. });
  16201. this.connection.sendIQ(
  16202. req,
  16203. function (result) {
  16204. console.info('Hangup result ', result);
  16205. self.call_resource = null;
  16206. },
  16207. function (error) {
  16208. console.info('Hangup error ', error);
  16209. self.call_resource = null;
  16210. }
  16211. );
  16212. }
  16213. }
  16214. );
  16215. };
  16216. },{}],67:[function(require,module,exports){
  16217. /**
  16218. * Strophe logger implementation. Logs from level WARN and above.
  16219. */
  16220. module.exports = function () {
  16221. Strophe.log = function (level, msg) {
  16222. switch (level) {
  16223. case Strophe.LogLevel.WARN:
  16224. console.warn("Strophe: " + msg);
  16225. break;
  16226. case Strophe.LogLevel.ERROR:
  16227. case Strophe.LogLevel.FATAL:
  16228. console.error("Strophe: " + msg);
  16229. break;
  16230. }
  16231. };
  16232. Strophe.getStatusString = function (status) {
  16233. switch (status) {
  16234. case Strophe.Status.ERROR:
  16235. return "ERROR";
  16236. case Strophe.Status.CONNECTING:
  16237. return "CONNECTING";
  16238. case Strophe.Status.CONNFAIL:
  16239. return "CONNFAIL";
  16240. case Strophe.Status.AUTHENTICATING:
  16241. return "AUTHENTICATING";
  16242. case Strophe.Status.AUTHFAIL:
  16243. return "AUTHFAIL";
  16244. case Strophe.Status.CONNECTED:
  16245. return "CONNECTED";
  16246. case Strophe.Status.DISCONNECTED:
  16247. return "DISCONNECTED";
  16248. case Strophe.Status.DISCONNECTING:
  16249. return "DISCONNECTING";
  16250. case Strophe.Status.ATTACHED:
  16251. return "ATTACHED";
  16252. default:
  16253. return "unknown";
  16254. }
  16255. };
  16256. };
  16257. },{}],68:[function(require,module,exports){
  16258. /* global $, APP, config, Strophe*/
  16259. var Moderator = require("./moderator");
  16260. var EventEmitter = require("events");
  16261. var Recording = require("./recording");
  16262. var SDP = require("./SDP");
  16263. var Settings = require("../settings/Settings");
  16264. var Pako = require("pako");
  16265. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16266. var RTCEvents = require("../../service/RTC/RTCEvents");
  16267. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16268. var retry = require('retry');
  16269. var eventEmitter = new EventEmitter();
  16270. var connection = null;
  16271. var authenticatedUser = false;
  16272. function connect(jid, password) {
  16273. var faultTolerantConnect = retry.operation({
  16274. retries: 3
  16275. });
  16276. // fault tolerant connect
  16277. faultTolerantConnect.attempt(function () {
  16278. connection = XMPP.createConnection();
  16279. Moderator.setConnection(connection);
  16280. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16281. if (config.useIPv6) {
  16282. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16283. if (!connection.jingle.pc_constraints.optional)
  16284. connection.jingle.pc_constraints.optional = [];
  16285. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16286. }
  16287. // Include user info in MUC presence
  16288. var settings = Settings.getSettings();
  16289. if (settings.email) {
  16290. connection.emuc.addEmailToPresence(settings.email);
  16291. }
  16292. if (settings.uid) {
  16293. connection.emuc.addUserIdToPresence(settings.uid);
  16294. }
  16295. if (settings.displayName) {
  16296. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16297. }
  16298. // connection.connect() starts the connection process.
  16299. //
  16300. // As the connection process proceeds, the user supplied callback will
  16301. // be triggered multiple times with status updates. The callback should
  16302. // take two arguments - the status code and the error condition.
  16303. //
  16304. // The status code will be one of the values in the Strophe.Status
  16305. // constants. The error condition will be one of the conditions defined
  16306. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16307. //
  16308. // The Parameters wait, hold and route are optional and only relevant
  16309. // for BOSH connections. Please see XEP 124 for a more detailed
  16310. // explanation of the optional parameters.
  16311. //
  16312. // Connection status constants for use by the connection handler
  16313. // callback.
  16314. //
  16315. // Status.ERROR - An error has occurred (websockets specific)
  16316. // Status.CONNECTING - The connection is currently being made
  16317. // Status.CONNFAIL - The connection attempt failed
  16318. // Status.AUTHENTICATING - The connection is authenticating
  16319. // Status.AUTHFAIL - The authentication attempt failed
  16320. // Status.CONNECTED - The connection has succeeded
  16321. // Status.DISCONNECTED - The connection has been terminated
  16322. // Status.DISCONNECTING - The connection is currently being terminated
  16323. // Status.ATTACHED - The connection has been attached
  16324. var anonymousConnectionFailed = false;
  16325. var connectionFailed = false;
  16326. var lastErrorMsg;
  16327. connection.connect(jid, password, function (status, msg) {
  16328. console.log('Strophe status changed to',
  16329. Strophe.getStatusString(status), msg);
  16330. if (status === Strophe.Status.CONNECTED) {
  16331. if (config.useStunTurn) {
  16332. connection.jingle.getStunAndTurnCredentials();
  16333. }
  16334. console.info("My Jabber ID: " + connection.jid);
  16335. if (password)
  16336. authenticatedUser = true;
  16337. maybeDoJoin();
  16338. } else if (status === Strophe.Status.CONNFAIL) {
  16339. if (msg === 'x-strophe-bad-non-anon-jid') {
  16340. anonymousConnectionFailed = true;
  16341. } else {
  16342. connectionFailed = true;
  16343. }
  16344. lastErrorMsg = msg;
  16345. } else if (status === Strophe.Status.DISCONNECTED) {
  16346. if (anonymousConnectionFailed) {
  16347. // prompt user for username and password
  16348. XMPP.promptLogin();
  16349. } else {
  16350. // Strophe already has built-in HTTP/BOSH error handling and
  16351. // request retry logic. Requests are resent automatically
  16352. // until their error count reaches 5. Strophe.js disconnects
  16353. // if the error count is > 5. We are not replicating this
  16354. // here.
  16355. //
  16356. // The "problem" is that failed HTTP/BOSH requests don't
  16357. // trigger a callback with a status update, so when a
  16358. // callback with status Strophe.Status.DISCONNECTED arrives,
  16359. // we can't be sure if it's a graceful disconnect or if it's
  16360. // triggered by some HTTP/BOSH error.
  16361. //
  16362. // But that's a minor issue in Jitsi Meet as we never
  16363. // disconnect anyway, not even when the user closes the
  16364. // browser window (which is kind of wrong, but the point is
  16365. // that we should never ever get disconnected).
  16366. //
  16367. // On the other hand, failed connections due to XMPP layer
  16368. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16369. //
  16370. // Here we implement retry logic for failed connections due
  16371. // to XMPP layer errors and we display an error to the user
  16372. // if we get disconnected from the XMPP server permanently.
  16373. // If the connection failed, retry.
  16374. if (connectionFailed &&
  16375. faultTolerantConnect.retry("connection-failed")) {
  16376. return;
  16377. }
  16378. // If we failed to connect to the XMPP server, fire an event
  16379. // to let all the interested module now about it.
  16380. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16381. msg ? msg : lastErrorMsg);
  16382. }
  16383. } else if (status === Strophe.Status.AUTHFAIL) {
  16384. // wrong password or username, prompt user
  16385. XMPP.promptLogin();
  16386. }
  16387. });
  16388. });
  16389. }
  16390. function maybeDoJoin() {
  16391. if (connection && connection.connected &&
  16392. Strophe.getResourceFromJid(connection.jid) &&
  16393. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16394. // .connected is true while connecting?
  16395. doJoin();
  16396. }
  16397. }
  16398. function doJoin() {
  16399. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  16400. }
  16401. function initStrophePlugins()
  16402. {
  16403. require("./strophe.emuc")(XMPP, eventEmitter);
  16404. require("./strophe.jingle")(XMPP, eventEmitter);
  16405. require("./strophe.moderate")(XMPP, eventEmitter);
  16406. require("./strophe.util")();
  16407. require("./strophe.rayo")();
  16408. require("./strophe.logger")();
  16409. }
  16410. /**
  16411. * If given <tt>localStream</tt> is video one this method will advertise it's
  16412. * video type in MUC presence.
  16413. * @param localStream new or modified <tt>LocalStream</tt>.
  16414. */
  16415. function broadcastLocalVideoType(localStream) {
  16416. if (localStream.videoType)
  16417. XMPP.addToPresence('videoType', localStream.videoType);
  16418. }
  16419. function registerListeners() {
  16420. APP.RTC.addStreamListener(
  16421. function (localStream) {
  16422. maybeDoJoin();
  16423. broadcastLocalVideoType(localStream);
  16424. },
  16425. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  16426. );
  16427. APP.RTC.addStreamListener(
  16428. broadcastLocalVideoType,
  16429. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  16430. );
  16431. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16432. XMPP.addToPresence("devices", devices);
  16433. });
  16434. }
  16435. var unload = (function () {
  16436. var unloaded = false;
  16437. return function () {
  16438. if (unloaded) { return; }
  16439. unloaded = true;
  16440. if (connection && connection.connected) {
  16441. // ensure signout
  16442. $.ajax({
  16443. type: 'POST',
  16444. url: config.bosh,
  16445. async: false,
  16446. cache: false,
  16447. contentType: 'application/xml',
  16448. data: "<body rid='" +
  16449. (connection.rid || connection._proto.rid) +
  16450. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16451. (connection.sid || connection._proto.sid) +
  16452. "' type='terminate'>" +
  16453. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16454. "</body>",
  16455. success: function (data) {
  16456. console.log('signed out');
  16457. console.log(data);
  16458. },
  16459. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16460. console.log('signout error',
  16461. textStatus + ' (' + errorThrown + ')');
  16462. }
  16463. });
  16464. }
  16465. XMPP.disposeConference(true);
  16466. };
  16467. })();
  16468. function setupEvents() {
  16469. // In recent versions of FF the 'beforeunload' event is not fired when the
  16470. // window or the tab is closed. It is only fired when we leave the page
  16471. // (change URL). If this participant doesn't unload properly, then it
  16472. // becomes a ghost for the rest of the participants that stay in the
  16473. // conference. Thankfully handling the 'unload' event in addition to the
  16474. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  16475. // method at least once.
  16476. //
  16477. // The 'unload' method can safely be run multiple times, it will actually do
  16478. // something only the first time that it's run, so we're don't have to worry
  16479. // about browsers that fire both events.
  16480. $(window).bind('beforeunload', unload);
  16481. $(window).bind('unload', unload);
  16482. }
  16483. var XMPP = {
  16484. getConnection: function(){ return connection; },
  16485. sessionTerminated: false,
  16486. /**
  16487. * XMPP connection status
  16488. */
  16489. Status: Strophe.Status,
  16490. /**
  16491. * Remembers if we were muted by the focus.
  16492. * @type {boolean}
  16493. */
  16494. forceMuted: false,
  16495. start: function () {
  16496. setupEvents();
  16497. initStrophePlugins();
  16498. registerListeners();
  16499. Moderator.init(this, eventEmitter);
  16500. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16501. // Force authenticated domain if room is appended with '?login=true'
  16502. if (config.hosts.anonymousdomain &&
  16503. window.location.search.indexOf("login=true") !== -1) {
  16504. configDomain = config.hosts.domain;
  16505. }
  16506. var jid = configDomain || window.location.hostname;
  16507. connect(jid, null);
  16508. },
  16509. createConnection: function () {
  16510. var bosh = config.bosh || '/http-bind';
  16511. return new Strophe.Connection(bosh);
  16512. },
  16513. getStatusString: function (status) {
  16514. return Strophe.getStatusString(status);
  16515. },
  16516. promptLogin: function () {
  16517. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16518. },
  16519. joinRoom: function(roomName, useNicks, nick) {
  16520. var roomjid = roomName;
  16521. if (useNicks) {
  16522. if (nick) {
  16523. roomjid += '/' + nick;
  16524. } else {
  16525. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16526. }
  16527. } else {
  16528. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16529. if(!authenticatedUser)
  16530. tmpJid = tmpJid.substr(0, 8);
  16531. roomjid += '/' + tmpJid;
  16532. }
  16533. connection.emuc.doJoin(roomjid);
  16534. },
  16535. myJid: function () {
  16536. if(!connection)
  16537. return null;
  16538. return connection.emuc.myroomjid;
  16539. },
  16540. myResource: function () {
  16541. if(!connection || ! connection.emuc.myroomjid)
  16542. return null;
  16543. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16544. },
  16545. disposeConference: function (onUnload) {
  16546. var handler = connection.jingle.activecall;
  16547. if (handler && handler.peerconnection) {
  16548. // FIXME: probably removing streams is not required and close() should
  16549. // be enough
  16550. if (APP.RTC.localAudio) {
  16551. handler.peerconnection.removeStream(
  16552. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16553. }
  16554. if (APP.RTC.localVideo) {
  16555. handler.peerconnection.removeStream(
  16556. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16557. }
  16558. handler.peerconnection.close();
  16559. }
  16560. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16561. connection.jingle.activecall = null;
  16562. if (!onUnload) {
  16563. this.sessionTerminated = true;
  16564. connection.emuc.doLeave();
  16565. }
  16566. },
  16567. addListener: function(type, listener) {
  16568. eventEmitter.on(type, listener);
  16569. },
  16570. removeListener: function (type, listener) {
  16571. eventEmitter.removeListener(type, listener);
  16572. },
  16573. allocateConferenceFocus: function(roomName, callback) {
  16574. Moderator.allocateConferenceFocus(roomName, callback);
  16575. },
  16576. getLoginUrl: function (roomName, callback) {
  16577. Moderator.getLoginUrl(roomName, callback);
  16578. },
  16579. getPopupLoginUrl: function (roomName, callback) {
  16580. Moderator.getPopupLoginUrl(roomName, callback);
  16581. },
  16582. isModerator: function () {
  16583. return Moderator.isModerator();
  16584. },
  16585. isSipGatewayEnabled: function () {
  16586. return Moderator.isSipGatewayEnabled();
  16587. },
  16588. isExternalAuthEnabled: function () {
  16589. return Moderator.isExternalAuthEnabled();
  16590. },
  16591. isConferenceInProgress: function () {
  16592. return connection && connection.jingle.activecall &&
  16593. connection.jingle.activecall.peerconnection;
  16594. },
  16595. switchStreams: function (stream, oldStream, callback, isAudio) {
  16596. if (this.isConferenceInProgress()) {
  16597. // FIXME: will block switchInProgress on true value in case of exception
  16598. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16599. } else {
  16600. // We are done immediately
  16601. console.warn("No conference handler or conference not started yet");
  16602. callback();
  16603. }
  16604. },
  16605. sendVideoInfoPresence: function (mute) {
  16606. if(!connection)
  16607. return;
  16608. connection.emuc.addVideoInfoToPresence(mute);
  16609. connection.emuc.sendPresence();
  16610. },
  16611. setVideoMute: function (mute, callback, options) {
  16612. if(!connection)
  16613. return;
  16614. var self = this;
  16615. var localCallback = function (mute) {
  16616. self.sendVideoInfoPresence(mute);
  16617. return callback(mute);
  16618. };
  16619. if(connection.jingle.activecall)
  16620. {
  16621. connection.jingle.activecall.setVideoMute(
  16622. mute, localCallback, options);
  16623. }
  16624. else {
  16625. localCallback(mute);
  16626. }
  16627. },
  16628. setAudioMute: function (mute, callback) {
  16629. if (!(connection && APP.RTC.localAudio)) {
  16630. return false;
  16631. }
  16632. if (this.forceMuted && !mute) {
  16633. console.info("Asking focus for unmute");
  16634. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16635. // FIXME: wait for result before resetting muted status
  16636. this.forceMuted = false;
  16637. }
  16638. if (mute == APP.RTC.localAudio.isMuted()) {
  16639. // Nothing to do
  16640. return true;
  16641. }
  16642. APP.RTC.localAudio.setMute(mute);
  16643. this.sendAudioInfoPresence(mute, callback);
  16644. return true;
  16645. },
  16646. sendAudioInfoPresence: function(mute, callback) {
  16647. if(connection) {
  16648. connection.emuc.addAudioInfoToPresence(mute);
  16649. connection.emuc.sendPresence();
  16650. }
  16651. callback();
  16652. return true;
  16653. },
  16654. toggleRecording: function (tokenEmptyCallback,
  16655. recordingStateChangeCallback) {
  16656. Recording.toggleRecording(tokenEmptyCallback,
  16657. recordingStateChangeCallback, connection);
  16658. },
  16659. addToPresence: function (name, value, dontSend) {
  16660. switch (name) {
  16661. case "displayName":
  16662. connection.emuc.addDisplayNameToPresence(value);
  16663. break;
  16664. case "prezi":
  16665. connection.emuc.addPreziToPresence(value, 0);
  16666. break;
  16667. case "preziSlide":
  16668. connection.emuc.addCurrentSlideToPresence(value);
  16669. break;
  16670. case "connectionQuality":
  16671. connection.emuc.addConnectionInfoToPresence(value);
  16672. break;
  16673. case "email":
  16674. connection.emuc.addEmailToPresence(value);
  16675. break;
  16676. case "devices":
  16677. connection.emuc.addDevicesToPresence(value);
  16678. break;
  16679. case "videoType":
  16680. connection.emuc.addVideoTypeToPresence(value);
  16681. break;
  16682. case "startMuted":
  16683. if(!Moderator.isModerator())
  16684. return;
  16685. connection.emuc.addStartMutedToPresence(value[0],
  16686. value[1]);
  16687. break;
  16688. default :
  16689. console.log("Unknown tag for presence: " + name);
  16690. return;
  16691. }
  16692. if (!dontSend)
  16693. connection.emuc.sendPresence();
  16694. },
  16695. /**
  16696. * Sends 'data' as a log message to the focus. Returns true iff a message
  16697. * was sent.
  16698. * @param data
  16699. * @returns {boolean} true iff a message was sent.
  16700. */
  16701. sendLogs: function (data) {
  16702. if(!connection.emuc.focusMucJid)
  16703. return false;
  16704. var deflate = true;
  16705. var content = JSON.stringify(data);
  16706. if (deflate) {
  16707. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16708. }
  16709. content = Base64.encode(content);
  16710. // XEP-0337-ish
  16711. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16712. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16713. id: 'PeerConnectionStats'});
  16714. message.c('message').t(content).up();
  16715. if (deflate) {
  16716. message.c('tag', {name: "deflated", value: "true"}).up();
  16717. }
  16718. message.up();
  16719. connection.send(message);
  16720. return true;
  16721. },
  16722. // Gets the logs from strophe.jingle.
  16723. getJingleLog: function () {
  16724. return connection.jingle ? connection.jingle.getLog() : {};
  16725. },
  16726. // Gets the logs from strophe.
  16727. getXmppLog: function () {
  16728. return connection.logger ? connection.logger.log : null;
  16729. },
  16730. getPrezi: function () {
  16731. return connection.emuc.getPrezi(this.myJid());
  16732. },
  16733. removePreziFromPresence: function () {
  16734. connection.emuc.removePreziFromPresence();
  16735. connection.emuc.sendPresence();
  16736. },
  16737. sendChatMessage: function (message, nickname) {
  16738. connection.emuc.sendMessage(message, nickname);
  16739. },
  16740. setSubject: function (topic) {
  16741. connection.emuc.setSubject(topic);
  16742. },
  16743. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16744. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16745. },
  16746. dial: function (to, from, roomName,roomPass) {
  16747. connection.rayo.dial(to, from, roomName,roomPass);
  16748. },
  16749. setMute: function (jid, mute) {
  16750. connection.moderate.setMute(jid, mute);
  16751. },
  16752. eject: function (jid) {
  16753. connection.moderate.eject(jid);
  16754. },
  16755. logout: function (callback) {
  16756. Moderator.logout(callback);
  16757. },
  16758. findJidFromResource: function (resource) {
  16759. return connection.emuc.findJidFromResource(resource);
  16760. },
  16761. getMembers: function () {
  16762. return connection.emuc.members;
  16763. },
  16764. getJidFromSSRC: function (ssrc) {
  16765. if (!this.isConferenceInProgress())
  16766. return null;
  16767. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16768. },
  16769. // Returns true iff we have joined the MUC.
  16770. isMUCJoined: function () {
  16771. return connection.emuc.joined;
  16772. },
  16773. getSessions: function () {
  16774. return connection.jingle.sessions;
  16775. },
  16776. removeStream: function (stream) {
  16777. if (!this.isConferenceInProgress())
  16778. return;
  16779. connection.jingle.activecall.peerconnection.removeStream(stream);
  16780. }
  16781. };
  16782. module.exports = XMPP;
  16783. },{"../../service/RTC/RTCEvents":160,"../../service/RTC/StreamEventTypes":162,"../../service/xmpp/XMPPEvents":169,"../settings/Settings":47,"./SDP":56,"./moderator":60,"./recording":61,"./strophe.emuc":62,"./strophe.jingle":63,"./strophe.logger":64,"./strophe.moderate":65,"./strophe.rayo":66,"./strophe.util":67,"events":170,"pako":72,"retry":88}],69:[function(require,module,exports){
  16784. (function (process){
  16785. /*!
  16786. * async
  16787. * https://github.com/caolan/async
  16788. *
  16789. * Copyright 2010-2014 Caolan McMahon
  16790. * Released under the MIT license
  16791. */
  16792. /*jshint onevar: false, indent:4 */
  16793. /*global setImmediate: false, setTimeout: false, console: false */
  16794. (function () {
  16795. var async = {};
  16796. // global on the server, window in the browser
  16797. var root, previous_async;
  16798. root = this;
  16799. if (root != null) {
  16800. previous_async = root.async;
  16801. }
  16802. async.noConflict = function () {
  16803. root.async = previous_async;
  16804. return async;
  16805. };
  16806. function only_once(fn) {
  16807. var called = false;
  16808. return function() {
  16809. if (called) throw new Error("Callback was already called.");
  16810. called = true;
  16811. fn.apply(root, arguments);
  16812. }
  16813. }
  16814. //// cross-browser compatiblity functions ////
  16815. var _toString = Object.prototype.toString;
  16816. var _isArray = Array.isArray || function (obj) {
  16817. return _toString.call(obj) === '[object Array]';
  16818. };
  16819. var _each = function (arr, iterator) {
  16820. if (arr.forEach) {
  16821. return arr.forEach(iterator);
  16822. }
  16823. for (var i = 0; i < arr.length; i += 1) {
  16824. iterator(arr[i], i, arr);
  16825. }
  16826. };
  16827. var _map = function (arr, iterator) {
  16828. if (arr.map) {
  16829. return arr.map(iterator);
  16830. }
  16831. var results = [];
  16832. _each(arr, function (x, i, a) {
  16833. results.push(iterator(x, i, a));
  16834. });
  16835. return results;
  16836. };
  16837. var _reduce = function (arr, iterator, memo) {
  16838. if (arr.reduce) {
  16839. return arr.reduce(iterator, memo);
  16840. }
  16841. _each(arr, function (x, i, a) {
  16842. memo = iterator(memo, x, i, a);
  16843. });
  16844. return memo;
  16845. };
  16846. var _keys = function (obj) {
  16847. if (Object.keys) {
  16848. return Object.keys(obj);
  16849. }
  16850. var keys = [];
  16851. for (var k in obj) {
  16852. if (obj.hasOwnProperty(k)) {
  16853. keys.push(k);
  16854. }
  16855. }
  16856. return keys;
  16857. };
  16858. //// exported async module functions ////
  16859. //// nextTick implementation with browser-compatible fallback ////
  16860. if (typeof process === 'undefined' || !(process.nextTick)) {
  16861. if (typeof setImmediate === 'function') {
  16862. async.nextTick = function (fn) {
  16863. // not a direct alias for IE10 compatibility
  16864. setImmediate(fn);
  16865. };
  16866. async.setImmediate = async.nextTick;
  16867. }
  16868. else {
  16869. async.nextTick = function (fn) {
  16870. setTimeout(fn, 0);
  16871. };
  16872. async.setImmediate = async.nextTick;
  16873. }
  16874. }
  16875. else {
  16876. async.nextTick = process.nextTick;
  16877. if (typeof setImmediate !== 'undefined') {
  16878. async.setImmediate = function (fn) {
  16879. // not a direct alias for IE10 compatibility
  16880. setImmediate(fn);
  16881. };
  16882. }
  16883. else {
  16884. async.setImmediate = async.nextTick;
  16885. }
  16886. }
  16887. async.each = function (arr, iterator, callback) {
  16888. callback = callback || function () {};
  16889. if (!arr.length) {
  16890. return callback();
  16891. }
  16892. var completed = 0;
  16893. _each(arr, function (x) {
  16894. iterator(x, only_once(done) );
  16895. });
  16896. function done(err) {
  16897. if (err) {
  16898. callback(err);
  16899. callback = function () {};
  16900. }
  16901. else {
  16902. completed += 1;
  16903. if (completed >= arr.length) {
  16904. callback();
  16905. }
  16906. }
  16907. }
  16908. };
  16909. async.forEach = async.each;
  16910. async.eachSeries = function (arr, iterator, callback) {
  16911. callback = callback || function () {};
  16912. if (!arr.length) {
  16913. return callback();
  16914. }
  16915. var completed = 0;
  16916. var iterate = function () {
  16917. iterator(arr[completed], function (err) {
  16918. if (err) {
  16919. callback(err);
  16920. callback = function () {};
  16921. }
  16922. else {
  16923. completed += 1;
  16924. if (completed >= arr.length) {
  16925. callback();
  16926. }
  16927. else {
  16928. iterate();
  16929. }
  16930. }
  16931. });
  16932. };
  16933. iterate();
  16934. };
  16935. async.forEachSeries = async.eachSeries;
  16936. async.eachLimit = function (arr, limit, iterator, callback) {
  16937. var fn = _eachLimit(limit);
  16938. fn.apply(null, [arr, iterator, callback]);
  16939. };
  16940. async.forEachLimit = async.eachLimit;
  16941. var _eachLimit = function (limit) {
  16942. return function (arr, iterator, callback) {
  16943. callback = callback || function () {};
  16944. if (!arr.length || limit <= 0) {
  16945. return callback();
  16946. }
  16947. var completed = 0;
  16948. var started = 0;
  16949. var running = 0;
  16950. (function replenish () {
  16951. if (completed >= arr.length) {
  16952. return callback();
  16953. }
  16954. while (running < limit && started < arr.length) {
  16955. started += 1;
  16956. running += 1;
  16957. iterator(arr[started - 1], function (err) {
  16958. if (err) {
  16959. callback(err);
  16960. callback = function () {};
  16961. }
  16962. else {
  16963. completed += 1;
  16964. running -= 1;
  16965. if (completed >= arr.length) {
  16966. callback();
  16967. }
  16968. else {
  16969. replenish();
  16970. }
  16971. }
  16972. });
  16973. }
  16974. })();
  16975. };
  16976. };
  16977. var doParallel = function (fn) {
  16978. return function () {
  16979. var args = Array.prototype.slice.call(arguments);
  16980. return fn.apply(null, [async.each].concat(args));
  16981. };
  16982. };
  16983. var doParallelLimit = function(limit, fn) {
  16984. return function () {
  16985. var args = Array.prototype.slice.call(arguments);
  16986. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16987. };
  16988. };
  16989. var doSeries = function (fn) {
  16990. return function () {
  16991. var args = Array.prototype.slice.call(arguments);
  16992. return fn.apply(null, [async.eachSeries].concat(args));
  16993. };
  16994. };
  16995. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16996. arr = _map(arr, function (x, i) {
  16997. return {index: i, value: x};
  16998. });
  16999. if (!callback) {
  17000. eachfn(arr, function (x, callback) {
  17001. iterator(x.value, function (err) {
  17002. callback(err);
  17003. });
  17004. });
  17005. } else {
  17006. var results = [];
  17007. eachfn(arr, function (x, callback) {
  17008. iterator(x.value, function (err, v) {
  17009. results[x.index] = v;
  17010. callback(err);
  17011. });
  17012. }, function (err) {
  17013. callback(err, results);
  17014. });
  17015. }
  17016. };
  17017. async.map = doParallel(_asyncMap);
  17018. async.mapSeries = doSeries(_asyncMap);
  17019. async.mapLimit = function (arr, limit, iterator, callback) {
  17020. return _mapLimit(limit)(arr, iterator, callback);
  17021. };
  17022. var _mapLimit = function(limit) {
  17023. return doParallelLimit(limit, _asyncMap);
  17024. };
  17025. // reduce only has a series version, as doing reduce in parallel won't
  17026. // work in many situations.
  17027. async.reduce = function (arr, memo, iterator, callback) {
  17028. async.eachSeries(arr, function (x, callback) {
  17029. iterator(memo, x, function (err, v) {
  17030. memo = v;
  17031. callback(err);
  17032. });
  17033. }, function (err) {
  17034. callback(err, memo);
  17035. });
  17036. };
  17037. // inject alias
  17038. async.inject = async.reduce;
  17039. // foldl alias
  17040. async.foldl = async.reduce;
  17041. async.reduceRight = function (arr, memo, iterator, callback) {
  17042. var reversed = _map(arr, function (x) {
  17043. return x;
  17044. }).reverse();
  17045. async.reduce(reversed, memo, iterator, callback);
  17046. };
  17047. // foldr alias
  17048. async.foldr = async.reduceRight;
  17049. var _filter = function (eachfn, arr, iterator, callback) {
  17050. var results = [];
  17051. arr = _map(arr, function (x, i) {
  17052. return {index: i, value: x};
  17053. });
  17054. eachfn(arr, function (x, callback) {
  17055. iterator(x.value, function (v) {
  17056. if (v) {
  17057. results.push(x);
  17058. }
  17059. callback();
  17060. });
  17061. }, function (err) {
  17062. callback(_map(results.sort(function (a, b) {
  17063. return a.index - b.index;
  17064. }), function (x) {
  17065. return x.value;
  17066. }));
  17067. });
  17068. };
  17069. async.filter = doParallel(_filter);
  17070. async.filterSeries = doSeries(_filter);
  17071. // select alias
  17072. async.select = async.filter;
  17073. async.selectSeries = async.filterSeries;
  17074. var _reject = function (eachfn, arr, iterator, callback) {
  17075. var results = [];
  17076. arr = _map(arr, function (x, i) {
  17077. return {index: i, value: x};
  17078. });
  17079. eachfn(arr, function (x, callback) {
  17080. iterator(x.value, function (v) {
  17081. if (!v) {
  17082. results.push(x);
  17083. }
  17084. callback();
  17085. });
  17086. }, function (err) {
  17087. callback(_map(results.sort(function (a, b) {
  17088. return a.index - b.index;
  17089. }), function (x) {
  17090. return x.value;
  17091. }));
  17092. });
  17093. };
  17094. async.reject = doParallel(_reject);
  17095. async.rejectSeries = doSeries(_reject);
  17096. var _detect = function (eachfn, arr, iterator, main_callback) {
  17097. eachfn(arr, function (x, callback) {
  17098. iterator(x, function (result) {
  17099. if (result) {
  17100. main_callback(x);
  17101. main_callback = function () {};
  17102. }
  17103. else {
  17104. callback();
  17105. }
  17106. });
  17107. }, function (err) {
  17108. main_callback();
  17109. });
  17110. };
  17111. async.detect = doParallel(_detect);
  17112. async.detectSeries = doSeries(_detect);
  17113. async.some = function (arr, iterator, main_callback) {
  17114. async.each(arr, function (x, callback) {
  17115. iterator(x, function (v) {
  17116. if (v) {
  17117. main_callback(true);
  17118. main_callback = function () {};
  17119. }
  17120. callback();
  17121. });
  17122. }, function (err) {
  17123. main_callback(false);
  17124. });
  17125. };
  17126. // any alias
  17127. async.any = async.some;
  17128. async.every = function (arr, iterator, main_callback) {
  17129. async.each(arr, function (x, callback) {
  17130. iterator(x, function (v) {
  17131. if (!v) {
  17132. main_callback(false);
  17133. main_callback = function () {};
  17134. }
  17135. callback();
  17136. });
  17137. }, function (err) {
  17138. main_callback(true);
  17139. });
  17140. };
  17141. // all alias
  17142. async.all = async.every;
  17143. async.sortBy = function (arr, iterator, callback) {
  17144. async.map(arr, function (x, callback) {
  17145. iterator(x, function (err, criteria) {
  17146. if (err) {
  17147. callback(err);
  17148. }
  17149. else {
  17150. callback(null, {value: x, criteria: criteria});
  17151. }
  17152. });
  17153. }, function (err, results) {
  17154. if (err) {
  17155. return callback(err);
  17156. }
  17157. else {
  17158. var fn = function (left, right) {
  17159. var a = left.criteria, b = right.criteria;
  17160. return a < b ? -1 : a > b ? 1 : 0;
  17161. };
  17162. callback(null, _map(results.sort(fn), function (x) {
  17163. return x.value;
  17164. }));
  17165. }
  17166. });
  17167. };
  17168. async.auto = function (tasks, callback) {
  17169. callback = callback || function () {};
  17170. var keys = _keys(tasks);
  17171. var remainingTasks = keys.length
  17172. if (!remainingTasks) {
  17173. return callback();
  17174. }
  17175. var results = {};
  17176. var listeners = [];
  17177. var addListener = function (fn) {
  17178. listeners.unshift(fn);
  17179. };
  17180. var removeListener = function (fn) {
  17181. for (var i = 0; i < listeners.length; i += 1) {
  17182. if (listeners[i] === fn) {
  17183. listeners.splice(i, 1);
  17184. return;
  17185. }
  17186. }
  17187. };
  17188. var taskComplete = function () {
  17189. remainingTasks--
  17190. _each(listeners.slice(0), function (fn) {
  17191. fn();
  17192. });
  17193. };
  17194. addListener(function () {
  17195. if (!remainingTasks) {
  17196. var theCallback = callback;
  17197. // prevent final callback from calling itself if it errors
  17198. callback = function () {};
  17199. theCallback(null, results);
  17200. }
  17201. });
  17202. _each(keys, function (k) {
  17203. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17204. var taskCallback = function (err) {
  17205. var args = Array.prototype.slice.call(arguments, 1);
  17206. if (args.length <= 1) {
  17207. args = args[0];
  17208. }
  17209. if (err) {
  17210. var safeResults = {};
  17211. _each(_keys(results), function(rkey) {
  17212. safeResults[rkey] = results[rkey];
  17213. });
  17214. safeResults[k] = args;
  17215. callback(err, safeResults);
  17216. // stop subsequent errors hitting callback multiple times
  17217. callback = function () {};
  17218. }
  17219. else {
  17220. results[k] = args;
  17221. async.setImmediate(taskComplete);
  17222. }
  17223. };
  17224. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17225. var ready = function () {
  17226. return _reduce(requires, function (a, x) {
  17227. return (a && results.hasOwnProperty(x));
  17228. }, true) && !results.hasOwnProperty(k);
  17229. };
  17230. if (ready()) {
  17231. task[task.length - 1](taskCallback, results);
  17232. }
  17233. else {
  17234. var listener = function () {
  17235. if (ready()) {
  17236. removeListener(listener);
  17237. task[task.length - 1](taskCallback, results);
  17238. }
  17239. };
  17240. addListener(listener);
  17241. }
  17242. });
  17243. };
  17244. async.retry = function(times, task, callback) {
  17245. var DEFAULT_TIMES = 5;
  17246. var attempts = [];
  17247. // Use defaults if times not passed
  17248. if (typeof times === 'function') {
  17249. callback = task;
  17250. task = times;
  17251. times = DEFAULT_TIMES;
  17252. }
  17253. // Make sure times is a number
  17254. times = parseInt(times, 10) || DEFAULT_TIMES;
  17255. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17256. var retryAttempt = function(task, finalAttempt) {
  17257. return function(seriesCallback) {
  17258. task(function(err, result){
  17259. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17260. }, wrappedResults);
  17261. };
  17262. };
  17263. while (times) {
  17264. attempts.push(retryAttempt(task, !(times-=1)));
  17265. }
  17266. async.series(attempts, function(done, data){
  17267. data = data[data.length - 1];
  17268. (wrappedCallback || callback)(data.err, data.result);
  17269. });
  17270. }
  17271. // If a callback is passed, run this as a controll flow
  17272. return callback ? wrappedTask() : wrappedTask
  17273. };
  17274. async.waterfall = function (tasks, callback) {
  17275. callback = callback || function () {};
  17276. if (!_isArray(tasks)) {
  17277. var err = new Error('First argument to waterfall must be an array of functions');
  17278. return callback(err);
  17279. }
  17280. if (!tasks.length) {
  17281. return callback();
  17282. }
  17283. var wrapIterator = function (iterator) {
  17284. return function (err) {
  17285. if (err) {
  17286. callback.apply(null, arguments);
  17287. callback = function () {};
  17288. }
  17289. else {
  17290. var args = Array.prototype.slice.call(arguments, 1);
  17291. var next = iterator.next();
  17292. if (next) {
  17293. args.push(wrapIterator(next));
  17294. }
  17295. else {
  17296. args.push(callback);
  17297. }
  17298. async.setImmediate(function () {
  17299. iterator.apply(null, args);
  17300. });
  17301. }
  17302. };
  17303. };
  17304. wrapIterator(async.iterator(tasks))();
  17305. };
  17306. var _parallel = function(eachfn, tasks, callback) {
  17307. callback = callback || function () {};
  17308. if (_isArray(tasks)) {
  17309. eachfn.map(tasks, function (fn, callback) {
  17310. if (fn) {
  17311. fn(function (err) {
  17312. var args = Array.prototype.slice.call(arguments, 1);
  17313. if (args.length <= 1) {
  17314. args = args[0];
  17315. }
  17316. callback.call(null, err, args);
  17317. });
  17318. }
  17319. }, callback);
  17320. }
  17321. else {
  17322. var results = {};
  17323. eachfn.each(_keys(tasks), function (k, callback) {
  17324. tasks[k](function (err) {
  17325. var args = Array.prototype.slice.call(arguments, 1);
  17326. if (args.length <= 1) {
  17327. args = args[0];
  17328. }
  17329. results[k] = args;
  17330. callback(err);
  17331. });
  17332. }, function (err) {
  17333. callback(err, results);
  17334. });
  17335. }
  17336. };
  17337. async.parallel = function (tasks, callback) {
  17338. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17339. };
  17340. async.parallelLimit = function(tasks, limit, callback) {
  17341. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17342. };
  17343. async.series = function (tasks, callback) {
  17344. callback = callback || function () {};
  17345. if (_isArray(tasks)) {
  17346. async.mapSeries(tasks, function (fn, callback) {
  17347. if (fn) {
  17348. fn(function (err) {
  17349. var args = Array.prototype.slice.call(arguments, 1);
  17350. if (args.length <= 1) {
  17351. args = args[0];
  17352. }
  17353. callback.call(null, err, args);
  17354. });
  17355. }
  17356. }, callback);
  17357. }
  17358. else {
  17359. var results = {};
  17360. async.eachSeries(_keys(tasks), function (k, callback) {
  17361. tasks[k](function (err) {
  17362. var args = Array.prototype.slice.call(arguments, 1);
  17363. if (args.length <= 1) {
  17364. args = args[0];
  17365. }
  17366. results[k] = args;
  17367. callback(err);
  17368. });
  17369. }, function (err) {
  17370. callback(err, results);
  17371. });
  17372. }
  17373. };
  17374. async.iterator = function (tasks) {
  17375. var makeCallback = function (index) {
  17376. var fn = function () {
  17377. if (tasks.length) {
  17378. tasks[index].apply(null, arguments);
  17379. }
  17380. return fn.next();
  17381. };
  17382. fn.next = function () {
  17383. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17384. };
  17385. return fn;
  17386. };
  17387. return makeCallback(0);
  17388. };
  17389. async.apply = function (fn) {
  17390. var args = Array.prototype.slice.call(arguments, 1);
  17391. return function () {
  17392. return fn.apply(
  17393. null, args.concat(Array.prototype.slice.call(arguments))
  17394. );
  17395. };
  17396. };
  17397. var _concat = function (eachfn, arr, fn, callback) {
  17398. var r = [];
  17399. eachfn(arr, function (x, cb) {
  17400. fn(x, function (err, y) {
  17401. r = r.concat(y || []);
  17402. cb(err);
  17403. });
  17404. }, function (err) {
  17405. callback(err, r);
  17406. });
  17407. };
  17408. async.concat = doParallel(_concat);
  17409. async.concatSeries = doSeries(_concat);
  17410. async.whilst = function (test, iterator, callback) {
  17411. if (test()) {
  17412. iterator(function (err) {
  17413. if (err) {
  17414. return callback(err);
  17415. }
  17416. async.whilst(test, iterator, callback);
  17417. });
  17418. }
  17419. else {
  17420. callback();
  17421. }
  17422. };
  17423. async.doWhilst = function (iterator, test, callback) {
  17424. iterator(function (err) {
  17425. if (err) {
  17426. return callback(err);
  17427. }
  17428. var args = Array.prototype.slice.call(arguments, 1);
  17429. if (test.apply(null, args)) {
  17430. async.doWhilst(iterator, test, callback);
  17431. }
  17432. else {
  17433. callback();
  17434. }
  17435. });
  17436. };
  17437. async.until = function (test, iterator, callback) {
  17438. if (!test()) {
  17439. iterator(function (err) {
  17440. if (err) {
  17441. return callback(err);
  17442. }
  17443. async.until(test, iterator, callback);
  17444. });
  17445. }
  17446. else {
  17447. callback();
  17448. }
  17449. };
  17450. async.doUntil = function (iterator, test, callback) {
  17451. iterator(function (err) {
  17452. if (err) {
  17453. return callback(err);
  17454. }
  17455. var args = Array.prototype.slice.call(arguments, 1);
  17456. if (!test.apply(null, args)) {
  17457. async.doUntil(iterator, test, callback);
  17458. }
  17459. else {
  17460. callback();
  17461. }
  17462. });
  17463. };
  17464. async.queue = function (worker, concurrency) {
  17465. if (concurrency === undefined) {
  17466. concurrency = 1;
  17467. }
  17468. function _insert(q, data, pos, callback) {
  17469. if (!q.started){
  17470. q.started = true;
  17471. }
  17472. if (!_isArray(data)) {
  17473. data = [data];
  17474. }
  17475. if(data.length == 0) {
  17476. // call drain immediately if there are no tasks
  17477. return async.setImmediate(function() {
  17478. if (q.drain) {
  17479. q.drain();
  17480. }
  17481. });
  17482. }
  17483. _each(data, function(task) {
  17484. var item = {
  17485. data: task,
  17486. callback: typeof callback === 'function' ? callback : null
  17487. };
  17488. if (pos) {
  17489. q.tasks.unshift(item);
  17490. } else {
  17491. q.tasks.push(item);
  17492. }
  17493. if (q.saturated && q.tasks.length === q.concurrency) {
  17494. q.saturated();
  17495. }
  17496. async.setImmediate(q.process);
  17497. });
  17498. }
  17499. var workers = 0;
  17500. var q = {
  17501. tasks: [],
  17502. concurrency: concurrency,
  17503. saturated: null,
  17504. empty: null,
  17505. drain: null,
  17506. started: false,
  17507. paused: false,
  17508. push: function (data, callback) {
  17509. _insert(q, data, false, callback);
  17510. },
  17511. kill: function () {
  17512. q.drain = null;
  17513. q.tasks = [];
  17514. },
  17515. unshift: function (data, callback) {
  17516. _insert(q, data, true, callback);
  17517. },
  17518. process: function () {
  17519. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17520. var task = q.tasks.shift();
  17521. if (q.empty && q.tasks.length === 0) {
  17522. q.empty();
  17523. }
  17524. workers += 1;
  17525. var next = function () {
  17526. workers -= 1;
  17527. if (task.callback) {
  17528. task.callback.apply(task, arguments);
  17529. }
  17530. if (q.drain && q.tasks.length + workers === 0) {
  17531. q.drain();
  17532. }
  17533. q.process();
  17534. };
  17535. var cb = only_once(next);
  17536. worker(task.data, cb);
  17537. }
  17538. },
  17539. length: function () {
  17540. return q.tasks.length;
  17541. },
  17542. running: function () {
  17543. return workers;
  17544. },
  17545. idle: function() {
  17546. return q.tasks.length + workers === 0;
  17547. },
  17548. pause: function () {
  17549. if (q.paused === true) { return; }
  17550. q.paused = true;
  17551. q.process();
  17552. },
  17553. resume: function () {
  17554. if (q.paused === false) { return; }
  17555. q.paused = false;
  17556. q.process();
  17557. }
  17558. };
  17559. return q;
  17560. };
  17561. async.priorityQueue = function (worker, concurrency) {
  17562. function _compareTasks(a, b){
  17563. return a.priority - b.priority;
  17564. };
  17565. function _binarySearch(sequence, item, compare) {
  17566. var beg = -1,
  17567. end = sequence.length - 1;
  17568. while (beg < end) {
  17569. var mid = beg + ((end - beg + 1) >>> 1);
  17570. if (compare(item, sequence[mid]) >= 0) {
  17571. beg = mid;
  17572. } else {
  17573. end = mid - 1;
  17574. }
  17575. }
  17576. return beg;
  17577. }
  17578. function _insert(q, data, priority, callback) {
  17579. if (!q.started){
  17580. q.started = true;
  17581. }
  17582. if (!_isArray(data)) {
  17583. data = [data];
  17584. }
  17585. if(data.length == 0) {
  17586. // call drain immediately if there are no tasks
  17587. return async.setImmediate(function() {
  17588. if (q.drain) {
  17589. q.drain();
  17590. }
  17591. });
  17592. }
  17593. _each(data, function(task) {
  17594. var item = {
  17595. data: task,
  17596. priority: priority,
  17597. callback: typeof callback === 'function' ? callback : null
  17598. };
  17599. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17600. if (q.saturated && q.tasks.length === q.concurrency) {
  17601. q.saturated();
  17602. }
  17603. async.setImmediate(q.process);
  17604. });
  17605. }
  17606. // Start with a normal queue
  17607. var q = async.queue(worker, concurrency);
  17608. // Override push to accept second parameter representing priority
  17609. q.push = function (data, priority, callback) {
  17610. _insert(q, data, priority, callback);
  17611. };
  17612. // Remove unshift function
  17613. delete q.unshift;
  17614. return q;
  17615. };
  17616. async.cargo = function (worker, payload) {
  17617. var working = false,
  17618. tasks = [];
  17619. var cargo = {
  17620. tasks: tasks,
  17621. payload: payload,
  17622. saturated: null,
  17623. empty: null,
  17624. drain: null,
  17625. drained: true,
  17626. push: function (data, callback) {
  17627. if (!_isArray(data)) {
  17628. data = [data];
  17629. }
  17630. _each(data, function(task) {
  17631. tasks.push({
  17632. data: task,
  17633. callback: typeof callback === 'function' ? callback : null
  17634. });
  17635. cargo.drained = false;
  17636. if (cargo.saturated && tasks.length === payload) {
  17637. cargo.saturated();
  17638. }
  17639. });
  17640. async.setImmediate(cargo.process);
  17641. },
  17642. process: function process() {
  17643. if (working) return;
  17644. if (tasks.length === 0) {
  17645. if(cargo.drain && !cargo.drained) cargo.drain();
  17646. cargo.drained = true;
  17647. return;
  17648. }
  17649. var ts = typeof payload === 'number'
  17650. ? tasks.splice(0, payload)
  17651. : tasks.splice(0, tasks.length);
  17652. var ds = _map(ts, function (task) {
  17653. return task.data;
  17654. });
  17655. if(cargo.empty) cargo.empty();
  17656. working = true;
  17657. worker(ds, function () {
  17658. working = false;
  17659. var args = arguments;
  17660. _each(ts, function (data) {
  17661. if (data.callback) {
  17662. data.callback.apply(null, args);
  17663. }
  17664. });
  17665. process();
  17666. });
  17667. },
  17668. length: function () {
  17669. return tasks.length;
  17670. },
  17671. running: function () {
  17672. return working;
  17673. }
  17674. };
  17675. return cargo;
  17676. };
  17677. var _console_fn = function (name) {
  17678. return function (fn) {
  17679. var args = Array.prototype.slice.call(arguments, 1);
  17680. fn.apply(null, args.concat([function (err) {
  17681. var args = Array.prototype.slice.call(arguments, 1);
  17682. if (typeof console !== 'undefined') {
  17683. if (err) {
  17684. if (console.error) {
  17685. console.error(err);
  17686. }
  17687. }
  17688. else if (console[name]) {
  17689. _each(args, function (x) {
  17690. console[name](x);
  17691. });
  17692. }
  17693. }
  17694. }]));
  17695. };
  17696. };
  17697. async.log = _console_fn('log');
  17698. async.dir = _console_fn('dir');
  17699. /*async.info = _console_fn('info');
  17700. async.warn = _console_fn('warn');
  17701. async.error = _console_fn('error');*/
  17702. async.memoize = function (fn, hasher) {
  17703. var memo = {};
  17704. var queues = {};
  17705. hasher = hasher || function (x) {
  17706. return x;
  17707. };
  17708. var memoized = function () {
  17709. var args = Array.prototype.slice.call(arguments);
  17710. var callback = args.pop();
  17711. var key = hasher.apply(null, args);
  17712. if (key in memo) {
  17713. async.nextTick(function () {
  17714. callback.apply(null, memo[key]);
  17715. });
  17716. }
  17717. else if (key in queues) {
  17718. queues[key].push(callback);
  17719. }
  17720. else {
  17721. queues[key] = [callback];
  17722. fn.apply(null, args.concat([function () {
  17723. memo[key] = arguments;
  17724. var q = queues[key];
  17725. delete queues[key];
  17726. for (var i = 0, l = q.length; i < l; i++) {
  17727. q[i].apply(null, arguments);
  17728. }
  17729. }]));
  17730. }
  17731. };
  17732. memoized.memo = memo;
  17733. memoized.unmemoized = fn;
  17734. return memoized;
  17735. };
  17736. async.unmemoize = function (fn) {
  17737. return function () {
  17738. return (fn.unmemoized || fn).apply(null, arguments);
  17739. };
  17740. };
  17741. async.times = function (count, iterator, callback) {
  17742. var counter = [];
  17743. for (var i = 0; i < count; i++) {
  17744. counter.push(i);
  17745. }
  17746. return async.map(counter, iterator, callback);
  17747. };
  17748. async.timesSeries = function (count, iterator, callback) {
  17749. var counter = [];
  17750. for (var i = 0; i < count; i++) {
  17751. counter.push(i);
  17752. }
  17753. return async.mapSeries(counter, iterator, callback);
  17754. };
  17755. async.seq = function (/* functions... */) {
  17756. var fns = arguments;
  17757. return function () {
  17758. var that = this;
  17759. var args = Array.prototype.slice.call(arguments);
  17760. var callback = args.pop();
  17761. async.reduce(fns, args, function (newargs, fn, cb) {
  17762. fn.apply(that, newargs.concat([function () {
  17763. var err = arguments[0];
  17764. var nextargs = Array.prototype.slice.call(arguments, 1);
  17765. cb(err, nextargs);
  17766. }]))
  17767. },
  17768. function (err, results) {
  17769. callback.apply(that, [err].concat(results));
  17770. });
  17771. };
  17772. };
  17773. async.compose = function (/* functions... */) {
  17774. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17775. };
  17776. var _applyEach = function (eachfn, fns /*args...*/) {
  17777. var go = function () {
  17778. var that = this;
  17779. var args = Array.prototype.slice.call(arguments);
  17780. var callback = args.pop();
  17781. return eachfn(fns, function (fn, cb) {
  17782. fn.apply(that, args.concat([cb]));
  17783. },
  17784. callback);
  17785. };
  17786. if (arguments.length > 2) {
  17787. var args = Array.prototype.slice.call(arguments, 2);
  17788. return go.apply(this, args);
  17789. }
  17790. else {
  17791. return go;
  17792. }
  17793. };
  17794. async.applyEach = doParallel(_applyEach);
  17795. async.applyEachSeries = doSeries(_applyEach);
  17796. async.forever = function (fn, callback) {
  17797. function next(err) {
  17798. if (err) {
  17799. if (callback) {
  17800. return callback(err);
  17801. }
  17802. throw err;
  17803. }
  17804. fn(next);
  17805. }
  17806. next();
  17807. };
  17808. // Node.js
  17809. if (typeof module !== 'undefined' && module.exports) {
  17810. module.exports = async;
  17811. }
  17812. // AMD / RequireJS
  17813. else if (typeof define !== 'undefined' && define.amd) {
  17814. define([], function () {
  17815. return async;
  17816. });
  17817. }
  17818. // included directly via <script> tag
  17819. else {
  17820. root.async = async;
  17821. }
  17822. }());
  17823. }).call(this,require('_process'))
  17824. },{"_process":171}],70:[function(require,module,exports){
  17825. // i18next, v1.7.7
  17826. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17827. // Distributed under MIT license
  17828. // http://i18next.com
  17829. (function() {
  17830. // add indexOf to non ECMA-262 standard compliant browsers
  17831. if (!Array.prototype.indexOf) {
  17832. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17833. "use strict";
  17834. if (this == null) {
  17835. throw new TypeError();
  17836. }
  17837. var t = Object(this);
  17838. var len = t.length >>> 0;
  17839. if (len === 0) {
  17840. return -1;
  17841. }
  17842. var n = 0;
  17843. if (arguments.length > 0) {
  17844. n = Number(arguments[1]);
  17845. if (n != n) { // shortcut for verifying if it's NaN
  17846. n = 0;
  17847. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17848. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17849. }
  17850. }
  17851. if (n >= len) {
  17852. return -1;
  17853. }
  17854. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17855. for (; k < len; k++) {
  17856. if (k in t && t[k] === searchElement) {
  17857. return k;
  17858. }
  17859. }
  17860. return -1;
  17861. }
  17862. }
  17863. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17864. if (!Array.prototype.lastIndexOf) {
  17865. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17866. "use strict";
  17867. if (this == null) {
  17868. throw new TypeError();
  17869. }
  17870. var t = Object(this);
  17871. var len = t.length >>> 0;
  17872. if (len === 0) {
  17873. return -1;
  17874. }
  17875. var n = len;
  17876. if (arguments.length > 1) {
  17877. n = Number(arguments[1]);
  17878. if (n != n) {
  17879. n = 0;
  17880. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17881. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17882. }
  17883. }
  17884. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17885. for (; k >= 0; k--) {
  17886. if (k in t && t[k] === searchElement) {
  17887. return k;
  17888. }
  17889. }
  17890. return -1;
  17891. };
  17892. }
  17893. // Add string trim for IE8.
  17894. if (typeof String.prototype.trim !== 'function') {
  17895. String.prototype.trim = function() {
  17896. return this.replace(/^\s+|\s+$/g, '');
  17897. }
  17898. }
  17899. var root = this
  17900. , $ = root.jQuery || root.Zepto
  17901. , i18n = {}
  17902. , resStore = {}
  17903. , currentLng
  17904. , replacementCounter = 0
  17905. , languages = []
  17906. , initialized = false
  17907. , sync = {};
  17908. // Export the i18next object for **CommonJS**.
  17909. // If we're not in CommonJS, add `i18n` to the
  17910. // global object or to jquery.
  17911. if (typeof module !== 'undefined' && module.exports) {
  17912. if (!$) {
  17913. try {
  17914. $ = require('jquery');
  17915. } catch(e) {
  17916. // just ignore
  17917. }
  17918. }
  17919. if ($) {
  17920. $.i18n = $.i18n || i18n;
  17921. }
  17922. module.exports = i18n;
  17923. } else {
  17924. if ($) {
  17925. $.i18n = $.i18n || i18n;
  17926. }
  17927. root.i18n = root.i18n || i18n;
  17928. }
  17929. sync = {
  17930. load: function(lngs, options, cb) {
  17931. if (options.useLocalStorage) {
  17932. sync._loadLocal(lngs, options, function(err, store) {
  17933. var missingLngs = [];
  17934. for (var i = 0, len = lngs.length; i < len; i++) {
  17935. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17936. }
  17937. if (missingLngs.length > 0) {
  17938. sync._fetch(missingLngs, options, function(err, fetched) {
  17939. f.extend(store, fetched);
  17940. sync._storeLocal(fetched);
  17941. cb(null, store);
  17942. });
  17943. } else {
  17944. cb(null, store);
  17945. }
  17946. });
  17947. } else {
  17948. sync._fetch(lngs, options, function(err, store){
  17949. cb(null, store);
  17950. });
  17951. }
  17952. },
  17953. _loadLocal: function(lngs, options, cb) {
  17954. var store = {}
  17955. , nowMS = new Date().getTime();
  17956. if(window.localStorage) {
  17957. var todo = lngs.length;
  17958. f.each(lngs, function(key, lng) {
  17959. var local = window.localStorage.getItem('res_' + lng);
  17960. if (local) {
  17961. local = JSON.parse(local);
  17962. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17963. store[lng] = local;
  17964. }
  17965. }
  17966. todo--; // wait for all done befor callback
  17967. if (todo === 0) cb(null, store);
  17968. });
  17969. }
  17970. },
  17971. _storeLocal: function(store) {
  17972. if(window.localStorage) {
  17973. for (var m in store) {
  17974. store[m].i18nStamp = new Date().getTime();
  17975. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17976. }
  17977. }
  17978. return;
  17979. },
  17980. _fetch: function(lngs, options, cb) {
  17981. var ns = options.ns
  17982. , store = {};
  17983. if (!options.dynamicLoad) {
  17984. var todo = ns.namespaces.length * lngs.length
  17985. , errors;
  17986. // load each file individual
  17987. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17988. f.each(lngs, function(lngIndex, lngValue) {
  17989. // Call this once our translation has returned.
  17990. var loadComplete = function(err, data) {
  17991. if (err) {
  17992. errors = errors || [];
  17993. errors.push(err);
  17994. }
  17995. store[lngValue] = store[lngValue] || {};
  17996. store[lngValue][nsValue] = data;
  17997. todo--; // wait for all done befor callback
  17998. if (todo === 0) cb(errors, store);
  17999. };
  18000. if(typeof options.customLoad == 'function'){
  18001. // Use the specified custom callback.
  18002. options.customLoad(lngValue, nsValue, options, loadComplete);
  18003. } else {
  18004. //~ // Use our inbuilt sync.
  18005. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  18006. }
  18007. });
  18008. });
  18009. } else {
  18010. // Call this once our translation has returned.
  18011. var loadComplete = function(err, data) {
  18012. cb(null, data);
  18013. };
  18014. if(typeof options.customLoad == 'function'){
  18015. // Use the specified custom callback.
  18016. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  18017. } else {
  18018. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  18019. // load all needed stuff once
  18020. f.ajax({
  18021. url: url,
  18022. success: function(data, status, xhr) {
  18023. f.log('loaded: ' + url);
  18024. loadComplete(null, data);
  18025. },
  18026. error : function(xhr, status, error) {
  18027. f.log('failed loading: ' + url);
  18028. loadComplete('failed loading resource.json error: ' + error);
  18029. },
  18030. dataType: "json",
  18031. async : options.getAsync
  18032. });
  18033. }
  18034. }
  18035. },
  18036. _fetchOne: function(lng, ns, options, done) {
  18037. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  18038. f.ajax({
  18039. url: url,
  18040. success: function(data, status, xhr) {
  18041. f.log('loaded: ' + url);
  18042. done(null, data);
  18043. },
  18044. error : function(xhr, status, error) {
  18045. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  18046. // file loaded but invalid json, stop waste time !
  18047. f.error('There is a typo in: ' + url);
  18048. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  18049. f.log('Does not exist: ' + url);
  18050. } else {
  18051. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  18052. f.log(theStatus + ' when loading ' + url);
  18053. }
  18054. done(error, {});
  18055. },
  18056. dataType: "json",
  18057. async : options.getAsync
  18058. });
  18059. },
  18060. postMissing: function(lng, ns, key, defaultValue, lngs) {
  18061. var payload = {};
  18062. payload[key] = defaultValue;
  18063. var urls = [];
  18064. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  18065. for (var i = 0; i < o.fallbackLng.length; i++) {
  18066. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  18067. }
  18068. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  18069. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  18070. } else if (o.sendMissingTo === 'all') {
  18071. for (var i = 0, l = lngs.length; i < l; i++) {
  18072. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  18073. }
  18074. }
  18075. for (var y = 0, len = urls.length; y < len; y++) {
  18076. var item = urls[y];
  18077. f.ajax({
  18078. url: item.url,
  18079. type: o.sendType,
  18080. data: payload,
  18081. success: function(data, status, xhr) {
  18082. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  18083. // add key to resStore
  18084. var keys = key.split('.');
  18085. var x = 0;
  18086. var value = resStore[item.lng][ns];
  18087. while (keys[x]) {
  18088. if (x === keys.length - 1) {
  18089. value = value[keys[x]] = defaultValue;
  18090. } else {
  18091. value = value[keys[x]] = value[keys[x]] || {};
  18092. }
  18093. x++;
  18094. }
  18095. },
  18096. error : function(xhr, status, error) {
  18097. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  18098. },
  18099. dataType: "json",
  18100. async : o.postAsync
  18101. });
  18102. }
  18103. },
  18104. reload: reload
  18105. };
  18106. // defaults
  18107. var o = {
  18108. lng: undefined,
  18109. load: 'all',
  18110. preload: [],
  18111. lowerCaseLng: false,
  18112. returnObjectTrees: false,
  18113. fallbackLng: ['dev'],
  18114. fallbackNS: [],
  18115. detectLngQS: 'setLng',
  18116. detectLngFromLocalStorage: false,
  18117. ns: 'translation',
  18118. fallbackOnNull: true,
  18119. fallbackOnEmpty: false,
  18120. fallbackToDefaultNS: false,
  18121. nsseparator: ':',
  18122. keyseparator: '.',
  18123. selectorAttr: 'data-i18n',
  18124. debug: false,
  18125. resGetPath: 'locales/__lng__/__ns__.json',
  18126. resPostPath: 'locales/add/__lng__/__ns__',
  18127. getAsync: true,
  18128. postAsync: true,
  18129. resStore: undefined,
  18130. useLocalStorage: false,
  18131. localStorageExpirationTime: 7*24*60*60*1000,
  18132. dynamicLoad: false,
  18133. sendMissing: false,
  18134. sendMissingTo: 'fallback', // current | all
  18135. sendType: 'POST',
  18136. interpolationPrefix: '__',
  18137. interpolationSuffix: '__',
  18138. defaultVariables: false,
  18139. reusePrefix: '$t(',
  18140. reuseSuffix: ')',
  18141. pluralSuffix: '_plural',
  18142. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  18143. contextNotFound: ['context_not_found', Math.random()].join(''),
  18144. escapeInterpolation: false,
  18145. indefiniteSuffix: '_indefinite',
  18146. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  18147. setJqueryExt: true,
  18148. defaultValueFromContent: true,
  18149. useDataAttrOptions: false,
  18150. cookieExpirationTime: undefined,
  18151. useCookie: true,
  18152. cookieName: 'i18next',
  18153. cookieDomain: undefined,
  18154. objectTreeKeyHandler: undefined,
  18155. postProcess: undefined,
  18156. parseMissingKey: undefined,
  18157. missingKeyHandler: sync.postMissing,
  18158. shortcutFunction: 'sprintf' // or: defaultValue
  18159. };
  18160. function _extend(target, source) {
  18161. if (!source || typeof source === 'function') {
  18162. return target;
  18163. }
  18164. for (var attr in source) { target[attr] = source[attr]; }
  18165. return target;
  18166. }
  18167. function _deepExtend(target, source) {
  18168. for (var prop in source)
  18169. if (prop in target)
  18170. _deepExtend(target[prop], source[prop]);
  18171. else
  18172. target[prop] = source[prop];
  18173. return target;
  18174. }
  18175. function _each(object, callback, args) {
  18176. var name, i = 0,
  18177. length = object.length,
  18178. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  18179. if (args) {
  18180. if (isObj) {
  18181. for (name in object) {
  18182. if (callback.apply(object[name], args) === false) {
  18183. break;
  18184. }
  18185. }
  18186. } else {
  18187. for ( ; i < length; ) {
  18188. if (callback.apply(object[i++], args) === false) {
  18189. break;
  18190. }
  18191. }
  18192. }
  18193. // A special, fast, case for the most common use of each
  18194. } else {
  18195. if (isObj) {
  18196. for (name in object) {
  18197. if (callback.call(object[name], name, object[name]) === false) {
  18198. break;
  18199. }
  18200. }
  18201. } else {
  18202. for ( ; i < length; ) {
  18203. if (callback.call(object[i], i, object[i++]) === false) {
  18204. break;
  18205. }
  18206. }
  18207. }
  18208. }
  18209. return object;
  18210. }
  18211. var _entityMap = {
  18212. "&": "&amp;",
  18213. "<": "&lt;",
  18214. ">": "&gt;",
  18215. '"': '&quot;',
  18216. "'": '&#39;',
  18217. "/": '&#x2F;'
  18218. };
  18219. function _escape(data) {
  18220. if (typeof data === 'string') {
  18221. return data.replace(/[&<>"'\/]/g, function (s) {
  18222. return _entityMap[s];
  18223. });
  18224. }else{
  18225. return data;
  18226. }
  18227. }
  18228. function _ajax(options) {
  18229. // v0.5.0 of https://github.com/goloroden/http.js
  18230. var getXhr = function (callback) {
  18231. // Use the native XHR object if the browser supports it.
  18232. if (window.XMLHttpRequest) {
  18233. return callback(null, new XMLHttpRequest());
  18234. } else if (window.ActiveXObject) {
  18235. // In Internet Explorer check for ActiveX versions of the XHR object.
  18236. try {
  18237. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18238. } catch (e) {
  18239. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18240. }
  18241. }
  18242. // If no XHR support was found, throw an error.
  18243. return callback(new Error());
  18244. };
  18245. var encodeUsingUrlEncoding = function (data) {
  18246. if(typeof data === 'string') {
  18247. return data;
  18248. }
  18249. var result = [];
  18250. for(var dataItem in data) {
  18251. if(data.hasOwnProperty(dataItem)) {
  18252. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18253. }
  18254. }
  18255. return result.join('&');
  18256. };
  18257. var utf8 = function (text) {
  18258. text = text.replace(/\r\n/g, '\n');
  18259. var result = '';
  18260. for(var i = 0; i < text.length; i++) {
  18261. var c = text.charCodeAt(i);
  18262. if(c < 128) {
  18263. result += String.fromCharCode(c);
  18264. } else if((c > 127) && (c < 2048)) {
  18265. result += String.fromCharCode((c >> 6) | 192);
  18266. result += String.fromCharCode((c & 63) | 128);
  18267. } else {
  18268. result += String.fromCharCode((c >> 12) | 224);
  18269. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18270. result += String.fromCharCode((c & 63) | 128);
  18271. }
  18272. }
  18273. return result;
  18274. };
  18275. var base64 = function (text) {
  18276. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18277. text = utf8(text);
  18278. var result = '',
  18279. chr1, chr2, chr3,
  18280. enc1, enc2, enc3, enc4,
  18281. i = 0;
  18282. do {
  18283. chr1 = text.charCodeAt(i++);
  18284. chr2 = text.charCodeAt(i++);
  18285. chr3 = text.charCodeAt(i++);
  18286. enc1 = chr1 >> 2;
  18287. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18288. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18289. enc4 = chr3 & 63;
  18290. if(isNaN(chr2)) {
  18291. enc3 = enc4 = 64;
  18292. } else if(isNaN(chr3)) {
  18293. enc4 = 64;
  18294. }
  18295. result +=
  18296. keyStr.charAt(enc1) +
  18297. keyStr.charAt(enc2) +
  18298. keyStr.charAt(enc3) +
  18299. keyStr.charAt(enc4);
  18300. chr1 = chr2 = chr3 = '';
  18301. enc1 = enc2 = enc3 = enc4 = '';
  18302. } while(i < text.length);
  18303. return result;
  18304. };
  18305. var mergeHeaders = function () {
  18306. // Use the first header object as base.
  18307. var result = arguments[0];
  18308. // Iterate through the remaining header objects and add them.
  18309. for(var i = 1; i < arguments.length; i++) {
  18310. var currentHeaders = arguments[i];
  18311. for(var header in currentHeaders) {
  18312. if(currentHeaders.hasOwnProperty(header)) {
  18313. result[header] = currentHeaders[header];
  18314. }
  18315. }
  18316. }
  18317. // Return the merged headers.
  18318. return result;
  18319. };
  18320. var ajax = function (method, url, options, callback) {
  18321. // Adjust parameters.
  18322. if(typeof options === 'function') {
  18323. callback = options;
  18324. options = {};
  18325. }
  18326. // Set default parameter values.
  18327. options.cache = options.cache || false;
  18328. options.data = options.data || {};
  18329. options.headers = options.headers || {};
  18330. options.jsonp = options.jsonp || false;
  18331. options.async = options.async === undefined ? true : options.async;
  18332. // Merge the various header objects.
  18333. var headers = mergeHeaders({
  18334. 'accept': '*/*',
  18335. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18336. }, ajax.headers, options.headers);
  18337. // Encode the data according to the content-type.
  18338. var payload;
  18339. if (headers['content-type'] === 'application/json') {
  18340. payload = JSON.stringify(options.data);
  18341. } else {
  18342. payload = encodeUsingUrlEncoding(options.data);
  18343. }
  18344. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18345. // if neccessary.
  18346. if(method === 'GET') {
  18347. // Setup the query string.
  18348. var queryString = [];
  18349. if(payload) {
  18350. queryString.push(payload);
  18351. payload = null;
  18352. }
  18353. // Handle caching.
  18354. if(!options.cache) {
  18355. queryString.push('_=' + (new Date()).getTime());
  18356. }
  18357. // If neccessary prepare the query string for a JSONP call.
  18358. if(options.jsonp) {
  18359. queryString.push('callback=' + options.jsonp);
  18360. queryString.push('jsonp=' + options.jsonp);
  18361. }
  18362. // Merge the query string and attach it to the url.
  18363. queryString = queryString.join('&');
  18364. if (queryString.length > 1) {
  18365. if (url.indexOf('?') > -1) {
  18366. url += '&' + queryString;
  18367. } else {
  18368. url += '?' + queryString;
  18369. }
  18370. }
  18371. // Make a JSONP call if neccessary.
  18372. if(options.jsonp) {
  18373. var head = document.getElementsByTagName('head')[0];
  18374. var script = document.createElement('script');
  18375. script.type = 'text/javascript';
  18376. script.src = url;
  18377. head.appendChild(script);
  18378. return;
  18379. }
  18380. }
  18381. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18382. getXhr(function (err, xhr) {
  18383. if(err) return callback(err);
  18384. // Open the request.
  18385. xhr.open(method, url, options.async);
  18386. // Set the request headers.
  18387. for(var header in headers) {
  18388. if(headers.hasOwnProperty(header)) {
  18389. xhr.setRequestHeader(header, headers[header]);
  18390. }
  18391. }
  18392. // Handle the request events.
  18393. xhr.onreadystatechange = function () {
  18394. if(xhr.readyState === 4) {
  18395. var data = xhr.responseText || '';
  18396. // If no callback is given, return.
  18397. if(!callback) {
  18398. return;
  18399. }
  18400. // Return an object that provides access to the data as text and JSON.
  18401. callback(xhr.status, {
  18402. text: function () {
  18403. return data;
  18404. },
  18405. json: function () {
  18406. try {
  18407. return JSON.parse(data)
  18408. } catch (e) {
  18409. f.error('Can not parse JSON. URL: ' + url);
  18410. return {};
  18411. }
  18412. }
  18413. });
  18414. }
  18415. };
  18416. // Actually send the XHR request.
  18417. xhr.send(payload);
  18418. });
  18419. };
  18420. // Define the external interface.
  18421. var http = {
  18422. authBasic: function (username, password) {
  18423. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18424. },
  18425. connect: function (url, options, callback) {
  18426. return ajax('CONNECT', url, options, callback);
  18427. },
  18428. del: function (url, options, callback) {
  18429. return ajax('DELETE', url, options, callback);
  18430. },
  18431. get: function (url, options, callback) {
  18432. return ajax('GET', url, options, callback);
  18433. },
  18434. head: function (url, options, callback) {
  18435. return ajax('HEAD', url, options, callback);
  18436. },
  18437. headers: function (headers) {
  18438. ajax.headers = headers || {};
  18439. },
  18440. isAllowed: function (url, verb, callback) {
  18441. this.options(url, function (status, data) {
  18442. callback(data.text().indexOf(verb) !== -1);
  18443. });
  18444. },
  18445. options: function (url, options, callback) {
  18446. return ajax('OPTIONS', url, options, callback);
  18447. },
  18448. patch: function (url, options, callback) {
  18449. return ajax('PATCH', url, options, callback);
  18450. },
  18451. post: function (url, options, callback) {
  18452. return ajax('POST', url, options, callback);
  18453. },
  18454. put: function (url, options, callback) {
  18455. return ajax('PUT', url, options, callback);
  18456. },
  18457. trace: function (url, options, callback) {
  18458. return ajax('TRACE', url, options, callback);
  18459. }
  18460. };
  18461. var methode = options.type ? options.type.toLowerCase() : 'get';
  18462. http[methode](options.url, options, function (status, data) {
  18463. // file: protocol always gives status code 0, so check for data
  18464. if (status === 200 || (status === 0 && data.text())) {
  18465. options.success(data.json(), status, null);
  18466. } else {
  18467. options.error(data.text(), status, null);
  18468. }
  18469. });
  18470. }
  18471. var _cookie = {
  18472. create: function(name,value,minutes,domain) {
  18473. var expires;
  18474. if (minutes) {
  18475. var date = new Date();
  18476. date.setTime(date.getTime()+(minutes*60*1000));
  18477. expires = "; expires="+date.toGMTString();
  18478. }
  18479. else expires = "";
  18480. domain = (domain)? "domain="+domain+";" : "";
  18481. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18482. },
  18483. read: function(name) {
  18484. var nameEQ = name + "=";
  18485. var ca = document.cookie.split(';');
  18486. for(var i=0;i < ca.length;i++) {
  18487. var c = ca[i];
  18488. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18489. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18490. }
  18491. return null;
  18492. },
  18493. remove: function(name) {
  18494. this.create(name,"",-1);
  18495. }
  18496. };
  18497. var cookie_noop = {
  18498. create: function(name,value,minutes,domain) {},
  18499. read: function(name) { return null; },
  18500. remove: function(name) {}
  18501. };
  18502. // move dependent functions to a container so that
  18503. // they can be overriden easier in no jquery environment (node.js)
  18504. var f = {
  18505. extend: $ ? $.extend : _extend,
  18506. deepExtend: _deepExtend,
  18507. each: $ ? $.each : _each,
  18508. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18509. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18510. detectLanguage: detectLanguage,
  18511. escape: _escape,
  18512. log: function(str) {
  18513. if (o.debug && typeof console !== "undefined") console.log(str);
  18514. },
  18515. error: function(str) {
  18516. if (typeof console !== "undefined") console.error(str);
  18517. },
  18518. getCountyIndexOfLng: function(lng) {
  18519. var lng_index = 0;
  18520. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18521. return lng_index;
  18522. },
  18523. toLanguages: function(lng) {
  18524. var log = this.log;
  18525. function applyCase(l) {
  18526. var ret = l;
  18527. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18528. var parts = l.split('-');
  18529. ret = o.lowerCaseLng ?
  18530. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18531. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18532. } else {
  18533. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18534. }
  18535. return ret;
  18536. }
  18537. var languages = [];
  18538. var whitelist = o.lngWhitelist || false;
  18539. var addLanguage = function(language){
  18540. //reject langs not whitelisted
  18541. if(!whitelist || whitelist.indexOf(language) > -1){
  18542. languages.push(language);
  18543. }else{
  18544. log('rejecting non-whitelisted language: ' + language);
  18545. }
  18546. };
  18547. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18548. var parts = lng.split('-');
  18549. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18550. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18551. } else {
  18552. addLanguage(applyCase(lng));
  18553. }
  18554. for (var i = 0; i < o.fallbackLng.length; i++) {
  18555. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18556. }
  18557. return languages;
  18558. },
  18559. regexEscape: function(str) {
  18560. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18561. },
  18562. regexReplacementEscape: function(strOrFn) {
  18563. if (typeof strOrFn === 'string') {
  18564. return strOrFn.replace(/\$/g, "$$$$");
  18565. } else {
  18566. return strOrFn;
  18567. }
  18568. },
  18569. localStorage: {
  18570. setItem: function(key, value) {
  18571. if (window.localStorage) {
  18572. try {
  18573. window.localStorage.setItem(key, value);
  18574. } catch (e) {
  18575. f.log('failed to set value for key "' + key + '" to localStorage.');
  18576. }
  18577. }
  18578. }
  18579. }
  18580. };
  18581. function init(options, cb) {
  18582. if (typeof options === 'function') {
  18583. cb = options;
  18584. options = {};
  18585. }
  18586. options = options || {};
  18587. // override defaults with passed in options
  18588. f.extend(o, options);
  18589. delete o.fixLng; /* passed in each time */
  18590. // override functions: .log(), .detectLanguage(), etc
  18591. if (o.functions) {
  18592. delete o.functions;
  18593. f.extend(f, options.functions);
  18594. }
  18595. // create namespace object if namespace is passed in as string
  18596. if (typeof o.ns == 'string') {
  18597. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18598. }
  18599. // fallback namespaces
  18600. if (typeof o.fallbackNS == 'string') {
  18601. o.fallbackNS = [o.fallbackNS];
  18602. }
  18603. // fallback languages
  18604. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18605. o.fallbackLng = [o.fallbackLng];
  18606. }
  18607. // escape prefix/suffix
  18608. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18609. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18610. if (!o.lng) o.lng = f.detectLanguage();
  18611. languages = f.toLanguages(o.lng);
  18612. currentLng = languages[0];
  18613. f.log('currentLng set to: ' + currentLng);
  18614. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18615. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18616. }
  18617. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18618. f.localStorage.setItem('i18next_lng', currentLng);
  18619. }
  18620. var lngTranslate = translate;
  18621. if (options.fixLng) {
  18622. lngTranslate = function(key, options) {
  18623. options = options || {};
  18624. options.lng = options.lng || lngTranslate.lng;
  18625. return translate(key, options);
  18626. };
  18627. lngTranslate.lng = currentLng;
  18628. }
  18629. pluralExtensions.setCurrentLng(currentLng);
  18630. // add JQuery extensions
  18631. if ($ && o.setJqueryExt) addJqueryFunct();
  18632. // jQuery deferred
  18633. var deferred;
  18634. if ($ && $.Deferred) {
  18635. deferred = $.Deferred();
  18636. }
  18637. // return immidiatly if res are passed in
  18638. if (o.resStore) {
  18639. resStore = o.resStore;
  18640. initialized = true;
  18641. if (cb) cb(lngTranslate);
  18642. if (deferred) deferred.resolve(lngTranslate);
  18643. if (deferred) return deferred.promise();
  18644. return;
  18645. }
  18646. // languages to load
  18647. var lngsToLoad = f.toLanguages(o.lng);
  18648. if (typeof o.preload === 'string') o.preload = [o.preload];
  18649. for (var i = 0, l = o.preload.length; i < l; i++) {
  18650. var pres = f.toLanguages(o.preload[i]);
  18651. for (var y = 0, len = pres.length; y < len; y++) {
  18652. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18653. lngsToLoad.push(pres[y]);
  18654. }
  18655. }
  18656. }
  18657. // else load them
  18658. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18659. resStore = store;
  18660. initialized = true;
  18661. if (cb) cb(lngTranslate);
  18662. if (deferred) deferred.resolve(lngTranslate);
  18663. });
  18664. if (deferred) return deferred.promise();
  18665. }
  18666. function preload(lngs, cb) {
  18667. if (typeof lngs === 'string') lngs = [lngs];
  18668. for (var i = 0, l = lngs.length; i < l; i++) {
  18669. if (o.preload.indexOf(lngs[i]) < 0) {
  18670. o.preload.push(lngs[i]);
  18671. }
  18672. }
  18673. return init(cb);
  18674. }
  18675. function addResourceBundle(lng, ns, resources, deep) {
  18676. if (typeof ns !== 'string') {
  18677. resources = ns;
  18678. ns = o.ns.defaultNs;
  18679. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18680. o.ns.namespaces.push(ns);
  18681. }
  18682. resStore[lng] = resStore[lng] || {};
  18683. resStore[lng][ns] = resStore[lng][ns] || {};
  18684. if (deep) {
  18685. f.deepExtend(resStore[lng][ns], resources);
  18686. } else {
  18687. f.extend(resStore[lng][ns], resources);
  18688. }
  18689. }
  18690. function hasResourceBundle(lng, ns) {
  18691. if (typeof ns !== 'string') {
  18692. ns = o.ns.defaultNs;
  18693. }
  18694. resStore[lng] = resStore[lng] || {};
  18695. var res = resStore[lng][ns] || {};
  18696. var hasValues = false;
  18697. for(var prop in res) {
  18698. if (res.hasOwnProperty(prop)) {
  18699. hasValues = true;
  18700. }
  18701. }
  18702. return hasValues;
  18703. }
  18704. function removeResourceBundle(lng, ns) {
  18705. if (typeof ns !== 'string') {
  18706. ns = o.ns.defaultNs;
  18707. }
  18708. resStore[lng] = resStore[lng] || {};
  18709. resStore[lng][ns] = {};
  18710. }
  18711. function addResource(lng, ns, key, value) {
  18712. if (typeof ns !== 'string') {
  18713. resource = ns;
  18714. ns = o.ns.defaultNs;
  18715. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18716. o.ns.namespaces.push(ns);
  18717. }
  18718. resStore[lng] = resStore[lng] || {};
  18719. resStore[lng][ns] = resStore[lng][ns] || {};
  18720. var keys = key.split(o.keyseparator);
  18721. var x = 0;
  18722. var node = resStore[lng][ns];
  18723. var origRef = node;
  18724. while (keys[x]) {
  18725. if (x == keys.length - 1)
  18726. node[keys[x]] = value;
  18727. else {
  18728. if (node[keys[x]] == null)
  18729. node[keys[x]] = {};
  18730. node = node[keys[x]];
  18731. }
  18732. x++;
  18733. }
  18734. }
  18735. function addResources(lng, ns, resources) {
  18736. if (typeof ns !== 'string') {
  18737. resource = ns;
  18738. ns = o.ns.defaultNs;
  18739. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18740. o.ns.namespaces.push(ns);
  18741. }
  18742. for (var m in resources) {
  18743. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18744. }
  18745. }
  18746. function setDefaultNamespace(ns) {
  18747. o.ns.defaultNs = ns;
  18748. }
  18749. function loadNamespace(namespace, cb) {
  18750. loadNamespaces([namespace], cb);
  18751. }
  18752. function loadNamespaces(namespaces, cb) {
  18753. var opts = {
  18754. dynamicLoad: o.dynamicLoad,
  18755. resGetPath: o.resGetPath,
  18756. getAsync: o.getAsync,
  18757. customLoad: o.customLoad,
  18758. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18759. };
  18760. // languages to load
  18761. var lngsToLoad = f.toLanguages(o.lng);
  18762. if (typeof o.preload === 'string') o.preload = [o.preload];
  18763. for (var i = 0, l = o.preload.length; i < l; i++) {
  18764. var pres = f.toLanguages(o.preload[i]);
  18765. for (var y = 0, len = pres.length; y < len; y++) {
  18766. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18767. lngsToLoad.push(pres[y]);
  18768. }
  18769. }
  18770. }
  18771. // check if we have to load
  18772. var lngNeedLoad = [];
  18773. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18774. var needLoad = false;
  18775. var resSet = resStore[lngsToLoad[a]];
  18776. if (resSet) {
  18777. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18778. if (!resSet[namespaces[b]]) needLoad = true;
  18779. }
  18780. } else {
  18781. needLoad = true;
  18782. }
  18783. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18784. }
  18785. if (lngNeedLoad.length) {
  18786. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18787. var todo = namespaces.length * lngNeedLoad.length;
  18788. // load each file individual
  18789. f.each(namespaces, function(nsIndex, nsValue) {
  18790. // append namespace to namespace array
  18791. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18792. o.ns.namespaces.push(nsValue);
  18793. }
  18794. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18795. resStore[lngValue] = resStore[lngValue] || {};
  18796. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18797. todo--; // wait for all done befor callback
  18798. if (todo === 0 && cb) {
  18799. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18800. cb();
  18801. }
  18802. });
  18803. });
  18804. });
  18805. } else {
  18806. if (cb) cb();
  18807. }
  18808. }
  18809. function setLng(lng, options, cb) {
  18810. if (typeof options === 'function') {
  18811. cb = options;
  18812. options = {};
  18813. } else if (!options) {
  18814. options = {};
  18815. }
  18816. options.lng = lng;
  18817. return init(options, cb);
  18818. }
  18819. function lng() {
  18820. return currentLng;
  18821. }
  18822. function reload(cb) {
  18823. resStore = {};
  18824. setLng(currentLng, cb);
  18825. }
  18826. function addJqueryFunct() {
  18827. // $.t shortcut
  18828. $.t = $.t || translate;
  18829. function parse(ele, key, options) {
  18830. if (key.length === 0) return;
  18831. var attr = 'text';
  18832. if (key.indexOf('[') === 0) {
  18833. var parts = key.split(']');
  18834. key = parts[1];
  18835. attr = parts[0].substr(1, parts[0].length-1);
  18836. }
  18837. if (key.indexOf(';') === key.length-1) {
  18838. key = key.substr(0, key.length-2);
  18839. }
  18840. var optionsToUse;
  18841. if (attr === 'html') {
  18842. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18843. ele.html($.t(key, optionsToUse));
  18844. } else if (attr === 'text') {
  18845. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18846. ele.text($.t(key, optionsToUse));
  18847. } else if (attr === 'prepend') {
  18848. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18849. ele.prepend($.t(key, optionsToUse));
  18850. } else if (attr === 'append') {
  18851. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18852. ele.append($.t(key, optionsToUse));
  18853. } else if (attr.indexOf("data-") === 0) {
  18854. var dataAttr = attr.substr(("data-").length);
  18855. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18856. var translated = $.t(key, optionsToUse);
  18857. //we change into the data cache
  18858. ele.data(dataAttr, translated);
  18859. //we change into the dom
  18860. ele.attr(attr, translated);
  18861. } else {
  18862. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18863. ele.attr(attr, $.t(key, optionsToUse));
  18864. }
  18865. }
  18866. function localize(ele, options) {
  18867. var key = ele.attr(o.selectorAttr);
  18868. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18869. if (!key) return;
  18870. var target = ele
  18871. , targetSelector = ele.data("i18n-target");
  18872. if (targetSelector) {
  18873. target = ele.find(targetSelector) || ele;
  18874. }
  18875. if (!options && o.useDataAttrOptions === true) {
  18876. options = ele.data("i18n-options");
  18877. }
  18878. options = options || {};
  18879. if (key.indexOf(';') >= 0) {
  18880. var keys = key.split(';');
  18881. $.each(keys, function(m, k) {
  18882. if (k !== '') parse(target, k, options);
  18883. });
  18884. } else {
  18885. parse(target, key, options);
  18886. }
  18887. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18888. }
  18889. // fn
  18890. $.fn.i18n = function (options) {
  18891. return this.each(function() {
  18892. // localize element itself
  18893. localize($(this), options);
  18894. // localize childs
  18895. var elements = $(this).find('[' + o.selectorAttr + ']');
  18896. elements.each(function() {
  18897. localize($(this), options);
  18898. });
  18899. });
  18900. };
  18901. }
  18902. function applyReplacement(str, replacementHash, nestedKey, options) {
  18903. if (!str) return str;
  18904. options = options || replacementHash; // first call uses replacement hash combined with options
  18905. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18906. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18907. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18908. , unEscapingSuffix = 'HTML'+suffix;
  18909. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18910. f.each(hash, function(key, value) {
  18911. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18912. if (typeof value === 'object' && value !== null) {
  18913. str = applyReplacement(str, value, nextKey, options);
  18914. } else {
  18915. if (options.escapeInterpolation || o.escapeInterpolation) {
  18916. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18917. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18918. } else {
  18919. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18920. }
  18921. // str = options.escapeInterpolation;
  18922. }
  18923. });
  18924. return str;
  18925. }
  18926. // append it to functions
  18927. f.applyReplacement = applyReplacement;
  18928. function applyReuse(translated, options) {
  18929. var comma = ',';
  18930. var options_open = '{';
  18931. var options_close = '}';
  18932. var opts = f.extend({}, options);
  18933. delete opts.postProcess;
  18934. while (translated.indexOf(o.reusePrefix) != -1) {
  18935. replacementCounter++;
  18936. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18937. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18938. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18939. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18940. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18941. if (index_of_end_of_closing <= index_of_opening) {
  18942. f.error('there is an missing closing in following translation value', translated);
  18943. return '';
  18944. }
  18945. if (token_without_symbols.indexOf(comma) != -1) {
  18946. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18947. 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) {
  18948. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18949. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18950. try {
  18951. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18952. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18953. } catch (e) {
  18954. }
  18955. }
  18956. }
  18957. var translated_token = _translate(token_without_symbols, opts);
  18958. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18959. }
  18960. return translated;
  18961. }
  18962. function hasContext(options) {
  18963. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18964. }
  18965. function needsPlural(options, lng) {
  18966. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18967. }
  18968. function needsIndefiniteArticle(options) {
  18969. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18970. }
  18971. function exists(key, options) {
  18972. options = options || {};
  18973. var notFound = _getDefaultValue(key, options)
  18974. , found = _find(key, options);
  18975. return found !== undefined || found === notFound;
  18976. }
  18977. function translate(key, options) {
  18978. options = options || {};
  18979. if (!initialized) {
  18980. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18981. return options.defaultValue || '';
  18982. };
  18983. replacementCounter = 0;
  18984. return _translate.apply(null, arguments);
  18985. }
  18986. function _getDefaultValue(key, options) {
  18987. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18988. }
  18989. function _injectSprintfProcessor() {
  18990. var values = [];
  18991. // mh: build array from second argument onwards
  18992. for (var i = 1; i < arguments.length; i++) {
  18993. values.push(arguments[i]);
  18994. }
  18995. return {
  18996. postProcess: 'sprintf',
  18997. sprintf: values
  18998. };
  18999. }
  19000. function _translate(potentialKeys, options) {
  19001. if (options && typeof options !== 'object') {
  19002. if (o.shortcutFunction === 'sprintf') {
  19003. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  19004. options = _injectSprintfProcessor.apply(null, arguments);
  19005. } else if (o.shortcutFunction === 'defaultValue') {
  19006. options = {
  19007. defaultValue: options
  19008. }
  19009. }
  19010. } else {
  19011. options = options || {};
  19012. }
  19013. if (typeof o.defaultVariables === 'object') {
  19014. options = f.extend({}, o.defaultVariables, options);
  19015. }
  19016. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  19017. if (typeof potentialKeys === 'string') {
  19018. potentialKeys = [potentialKeys];
  19019. }
  19020. var key = potentialKeys[0];
  19021. if (potentialKeys.length > 1) {
  19022. for (var i = 0; i < potentialKeys.length; i++) {
  19023. key = potentialKeys[i];
  19024. if (exists(key, options)) {
  19025. break;
  19026. }
  19027. }
  19028. }
  19029. var notFound = _getDefaultValue(key, options)
  19030. , found = _find(key, options)
  19031. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  19032. , ns = options.ns || o.ns.defaultNs
  19033. , parts;
  19034. // split ns and key
  19035. if (key.indexOf(o.nsseparator) > -1) {
  19036. parts = key.split(o.nsseparator);
  19037. ns = parts[0];
  19038. key = parts[1];
  19039. }
  19040. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  19041. if (options.lng) {
  19042. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  19043. } else {
  19044. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  19045. }
  19046. }
  19047. var postProcessor = options.postProcess || o.postProcess;
  19048. if (found !== undefined && postProcessor) {
  19049. if (postProcessors[postProcessor]) {
  19050. found = postProcessors[postProcessor](found, key, options);
  19051. }
  19052. }
  19053. // process notFound if function exists
  19054. var splitNotFound = notFound;
  19055. if (notFound.indexOf(o.nsseparator) > -1) {
  19056. parts = notFound.split(o.nsseparator);
  19057. splitNotFound = parts[1];
  19058. }
  19059. if (splitNotFound === key && o.parseMissingKey) {
  19060. notFound = o.parseMissingKey(notFound);
  19061. }
  19062. if (found === undefined) {
  19063. notFound = applyReplacement(notFound, options);
  19064. notFound = applyReuse(notFound, options);
  19065. if (postProcessor && postProcessors[postProcessor]) {
  19066. var val = _getDefaultValue(key, options);
  19067. found = postProcessors[postProcessor](val, key, options);
  19068. }
  19069. }
  19070. return (found !== undefined) ? found : notFound;
  19071. }
  19072. function _find(key, options) {
  19073. options = options || {};
  19074. var optionWithoutCount, translated
  19075. , notFound = _getDefaultValue(key, options)
  19076. , lngs = languages;
  19077. if (!resStore) { return notFound; } // no resStore to translate from
  19078. // CI mode
  19079. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  19080. // passed in lng
  19081. if (options.lngs) lngs = options.lngs;
  19082. if (options.lng) {
  19083. lngs = f.toLanguages(options.lng, options.fallbackLng);
  19084. if (!resStore[lngs[0]]) {
  19085. var oldAsync = o.getAsync;
  19086. o.getAsync = false;
  19087. i18n.sync.load(lngs, o, function(err, store) {
  19088. f.extend(resStore, store);
  19089. o.getAsync = oldAsync;
  19090. });
  19091. }
  19092. }
  19093. var ns = options.ns || o.ns.defaultNs;
  19094. if (key.indexOf(o.nsseparator) > -1) {
  19095. var parts = key.split(o.nsseparator);
  19096. ns = parts[0];
  19097. key = parts[1];
  19098. }
  19099. if (hasContext(options)) {
  19100. optionWithoutCount = f.extend({}, options);
  19101. delete optionWithoutCount.context;
  19102. optionWithoutCount.defaultValue = o.contextNotFound;
  19103. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  19104. translated = translate(contextKey, optionWithoutCount);
  19105. if (translated != o.contextNotFound) {
  19106. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  19107. } // else continue translation with original/nonContext key
  19108. }
  19109. if (needsPlural(options, lngs[0])) {
  19110. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  19111. delete optionWithoutCount.count;
  19112. delete optionWithoutCount.lng;
  19113. optionWithoutCount.defaultValue = o.pluralNotFound;
  19114. var pluralKey;
  19115. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  19116. pluralKey = ns + o.nsseparator + key;
  19117. } else {
  19118. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  19119. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  19120. if (pluralExtension >= 0) {
  19121. pluralKey = pluralKey + '_' + pluralExtension;
  19122. } else if (pluralExtension === 1) {
  19123. pluralKey = ns + o.nsseparator + key; // singular
  19124. }
  19125. }
  19126. translated = translate(pluralKey, optionWithoutCount);
  19127. if (translated != o.pluralNotFound) {
  19128. return applyReplacement(translated, {
  19129. count: options.count,
  19130. interpolationPrefix: options.interpolationPrefix,
  19131. interpolationSuffix: options.interpolationSuffix
  19132. }); // apply replacement for count only
  19133. } else if (lngs.length > 1) {
  19134. // remove failed lng
  19135. var clone = lngs.slice();
  19136. clone.shift();
  19137. options = f.extend(options, { lngs: clone });
  19138. delete options.lng;
  19139. // retry with fallbacks
  19140. translated = translate(ns + o.nsseparator + key, options);
  19141. if (translated != o.pluralNotFound) return translated;
  19142. } else {
  19143. return translated;
  19144. }
  19145. }
  19146. if (needsIndefiniteArticle(options)) {
  19147. var optionsWithoutIndef = f.extend({}, options);
  19148. delete optionsWithoutIndef.indefinite_article;
  19149. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  19150. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  19151. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  19152. translated = translate(indefiniteKey, optionsWithoutIndef);
  19153. if (translated != o.indefiniteNotFound) {
  19154. return translated;
  19155. }
  19156. }
  19157. var found;
  19158. var keys = key.split(o.keyseparator);
  19159. for (var i = 0, len = lngs.length; i < len; i++ ) {
  19160. if (found !== undefined) break;
  19161. var l = lngs[i];
  19162. var x = 0;
  19163. var value = resStore[l] && resStore[l][ns];
  19164. while (keys[x]) {
  19165. value = value && value[keys[x]];
  19166. x++;
  19167. }
  19168. if (value !== undefined) {
  19169. var valueType = Object.prototype.toString.apply(value);
  19170. if (typeof value === 'string') {
  19171. value = applyReplacement(value, options);
  19172. value = applyReuse(value, options);
  19173. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  19174. value = value.join('\n');
  19175. value = applyReplacement(value, options);
  19176. value = applyReuse(value, options);
  19177. } else if (value === null && o.fallbackOnNull === true) {
  19178. value = undefined;
  19179. } else if (value !== null) {
  19180. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  19181. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  19182. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  19183. } else {
  19184. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  19185. 'returned an object instead of string.';
  19186. f.log(value);
  19187. }
  19188. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  19189. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  19190. f.each(value, function(m) {
  19191. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  19192. });
  19193. value = copy;
  19194. }
  19195. }
  19196. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  19197. value = undefined;
  19198. found = value;
  19199. }
  19200. }
  19201. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19202. // set flag for fallback lookup - avoid recursion
  19203. options.isFallbackLookup = true;
  19204. if (o.fallbackNS.length) {
  19205. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19206. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19207. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19208. /* compare value without namespace */
  19209. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19210. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19211. if (foundValue !== notFoundValue) break;
  19212. }
  19213. }
  19214. } else {
  19215. found = _find(key, options); // fallback to default NS
  19216. }
  19217. options.isFallbackLookup = false;
  19218. }
  19219. return found;
  19220. }
  19221. function detectLanguage() {
  19222. var detectedLng;
  19223. var whitelist = o.lngWhitelist || [];
  19224. var userLngChoices = [];
  19225. // get from qs
  19226. var qsParm = [];
  19227. if (typeof window !== 'undefined') {
  19228. (function() {
  19229. var query = window.location.search.substring(1);
  19230. var params = query.split('&');
  19231. for (var i=0; i<params.length; i++) {
  19232. var pos = params[i].indexOf('=');
  19233. if (pos > 0) {
  19234. var key = params[i].substring(0,pos);
  19235. if (key == o.detectLngQS) {
  19236. userLngChoices.push(params[i].substring(pos+1));
  19237. }
  19238. }
  19239. }
  19240. })();
  19241. }
  19242. // get from cookie
  19243. if (o.useCookie && typeof document !== 'undefined') {
  19244. var c = f.cookie.read(o.cookieName);
  19245. if (c) userLngChoices.push(c);
  19246. }
  19247. // get from localStorage
  19248. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19249. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19250. }
  19251. // get from navigator
  19252. if (typeof navigator !== 'undefined') {
  19253. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19254. for (var i=0;i<navigator.languages.length;i++) {
  19255. userLngChoices.push(navigator.languages[i]);
  19256. }
  19257. }
  19258. if (navigator.userLanguage) {
  19259. userLngChoices.push(navigator.userLanguage);
  19260. }
  19261. if (navigator.language) {
  19262. userLngChoices.push(navigator.language);
  19263. }
  19264. }
  19265. (function() {
  19266. for (var i=0;i<userLngChoices.length;i++) {
  19267. var lng = userLngChoices[i];
  19268. if (lng.indexOf('-') > -1) {
  19269. var parts = lng.split('-');
  19270. lng = o.lowerCaseLng ?
  19271. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19272. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19273. }
  19274. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19275. detectedLng = lng;
  19276. break;
  19277. }
  19278. }
  19279. })();
  19280. //fallback
  19281. if (!detectedLng){
  19282. detectedLng = o.fallbackLng[0];
  19283. }
  19284. return detectedLng;
  19285. }
  19286. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19287. /* [code, name, numbers, pluralsType] */
  19288. var _rules = [
  19289. ["ach", "Acholi", [1,2], 1],
  19290. ["af", "Afrikaans",[1,2], 2],
  19291. ["ak", "Akan", [1,2], 1],
  19292. ["am", "Amharic", [1,2], 1],
  19293. ["an", "Aragonese",[1,2], 2],
  19294. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19295. ["arn", "Mapudungun",[1,2], 1],
  19296. ["ast", "Asturian", [1,2], 2],
  19297. ["ay", "Aymará", [1], 3],
  19298. ["az", "Azerbaijani",[1,2],2],
  19299. ["be", "Belarusian",[1,2,5],4],
  19300. ["bg", "Bulgarian",[1,2], 2],
  19301. ["bn", "Bengali", [1,2], 2],
  19302. ["bo", "Tibetan", [1], 3],
  19303. ["br", "Breton", [1,2], 1],
  19304. ["bs", "Bosnian", [1,2,5],4],
  19305. ["ca", "Catalan", [1,2], 2],
  19306. ["cgg", "Chiga", [1], 3],
  19307. ["cs", "Czech", [1,2,5],6],
  19308. ["csb", "Kashubian",[1,2,5],7],
  19309. ["cy", "Welsh", [1,2,3,8],8],
  19310. ["da", "Danish", [1,2], 2],
  19311. ["de", "German", [1,2], 2],
  19312. ["dev", "Development Fallback", [1,2], 2],
  19313. ["dz", "Dzongkha", [1], 3],
  19314. ["el", "Greek", [1,2], 2],
  19315. ["en", "English", [1,2], 2],
  19316. ["eo", "Esperanto",[1,2], 2],
  19317. ["es", "Spanish", [1,2], 2],
  19318. ["es_ar","Argentinean Spanish", [1,2], 2],
  19319. ["et", "Estonian", [1,2], 2],
  19320. ["eu", "Basque", [1,2], 2],
  19321. ["fa", "Persian", [1], 3],
  19322. ["fi", "Finnish", [1,2], 2],
  19323. ["fil", "Filipino", [1,2], 1],
  19324. ["fo", "Faroese", [1,2], 2],
  19325. ["fr", "French", [1,2], 9],
  19326. ["fur", "Friulian", [1,2], 2],
  19327. ["fy", "Frisian", [1,2], 2],
  19328. ["ga", "Irish", [1,2,3,7,11],10],
  19329. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19330. ["gl", "Galician", [1,2], 2],
  19331. ["gu", "Gujarati", [1,2], 2],
  19332. ["gun", "Gun", [1,2], 1],
  19333. ["ha", "Hausa", [1,2], 2],
  19334. ["he", "Hebrew", [1,2], 2],
  19335. ["hi", "Hindi", [1,2], 2],
  19336. ["hr", "Croatian", [1,2,5],4],
  19337. ["hu", "Hungarian",[1,2], 2],
  19338. ["hy", "Armenian", [1,2], 2],
  19339. ["ia", "Interlingua",[1,2],2],
  19340. ["id", "Indonesian",[1], 3],
  19341. ["is", "Icelandic",[1,2], 12],
  19342. ["it", "Italian", [1,2], 2],
  19343. ["ja", "Japanese", [1], 3],
  19344. ["jbo", "Lojban", [1], 3],
  19345. ["jv", "Javanese", [0,1], 13],
  19346. ["ka", "Georgian", [1], 3],
  19347. ["kk", "Kazakh", [1], 3],
  19348. ["km", "Khmer", [1], 3],
  19349. ["kn", "Kannada", [1,2], 2],
  19350. ["ko", "Korean", [1], 3],
  19351. ["ku", "Kurdish", [1,2], 2],
  19352. ["kw", "Cornish", [1,2,3,4],14],
  19353. ["ky", "Kyrgyz", [1], 3],
  19354. ["lb", "Letzeburgesch",[1,2],2],
  19355. ["ln", "Lingala", [1,2], 1],
  19356. ["lo", "Lao", [1], 3],
  19357. ["lt", "Lithuanian",[1,2,10],15],
  19358. ["lv", "Latvian", [1,2,0],16],
  19359. ["mai", "Maithili", [1,2], 2],
  19360. ["mfe", "Mauritian Creole",[1,2],1],
  19361. ["mg", "Malagasy", [1,2], 1],
  19362. ["mi", "Maori", [1,2], 1],
  19363. ["mk", "Macedonian",[1,2],17],
  19364. ["ml", "Malayalam",[1,2], 2],
  19365. ["mn", "Mongolian",[1,2], 2],
  19366. ["mnk", "Mandinka", [0,1,2],18],
  19367. ["mr", "Marathi", [1,2], 2],
  19368. ["ms", "Malay", [1], 3],
  19369. ["mt", "Maltese", [1,2,11,20],19],
  19370. ["nah", "Nahuatl", [1,2], 2],
  19371. ["nap", "Neapolitan",[1,2], 2],
  19372. ["nb", "Norwegian Bokmal",[1,2],2],
  19373. ["ne", "Nepali", [1,2], 2],
  19374. ["nl", "Dutch", [1,2], 2],
  19375. ["nn", "Norwegian Nynorsk",[1,2],2],
  19376. ["no", "Norwegian",[1,2], 2],
  19377. ["nso", "Northern Sotho",[1,2],2],
  19378. ["oc", "Occitan", [1,2], 1],
  19379. ["or", "Oriya", [2,1], 2],
  19380. ["pa", "Punjabi", [1,2], 2],
  19381. ["pap", "Papiamento",[1,2], 2],
  19382. ["pl", "Polish", [1,2,5],7],
  19383. ["pms", "Piemontese",[1,2], 2],
  19384. ["ps", "Pashto", [1,2], 2],
  19385. ["pt", "Portuguese",[1,2], 2],
  19386. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19387. ["rm", "Romansh", [1,2], 2],
  19388. ["ro", "Romanian", [1,2,20],20],
  19389. ["ru", "Russian", [1,2,5],4],
  19390. ["sah", "Yakut", [1], 3],
  19391. ["sco", "Scots", [1,2], 2],
  19392. ["se", "Northern Sami",[1,2], 2],
  19393. ["si", "Sinhala", [1,2], 2],
  19394. ["sk", "Slovak", [1,2,5],6],
  19395. ["sl", "Slovenian",[5,1,2,3],21],
  19396. ["so", "Somali", [1,2], 2],
  19397. ["son", "Songhay", [1,2], 2],
  19398. ["sq", "Albanian", [1,2], 2],
  19399. ["sr", "Serbian", [1,2,5],4],
  19400. ["su", "Sundanese",[1], 3],
  19401. ["sv", "Swedish", [1,2], 2],
  19402. ["sw", "Swahili", [1,2], 2],
  19403. ["ta", "Tamil", [1,2], 2],
  19404. ["te", "Telugu", [1,2], 2],
  19405. ["tg", "Tajik", [1,2], 1],
  19406. ["th", "Thai", [1], 3],
  19407. ["ti", "Tigrinya", [1,2], 1],
  19408. ["tk", "Turkmen", [1,2], 2],
  19409. ["tr", "Turkish", [1,2], 1],
  19410. ["tt", "Tatar", [1], 3],
  19411. ["ug", "Uyghur", [1], 3],
  19412. ["uk", "Ukrainian",[1,2,5],4],
  19413. ["ur", "Urdu", [1,2], 2],
  19414. ["uz", "Uzbek", [1,2], 1],
  19415. ["vi", "Vietnamese",[1], 3],
  19416. ["wa", "Walloon", [1,2], 1],
  19417. ["wo", "Wolof", [1], 3],
  19418. ["yo", "Yoruba", [1,2], 2],
  19419. ["zh", "Chinese", [1], 3]
  19420. ];
  19421. var _rulesPluralsTypes = {
  19422. 1: function(n) {return Number(n > 1);},
  19423. 2: function(n) {return Number(n != 1);},
  19424. 3: function(n) {return 0;},
  19425. 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);},
  19426. 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);},
  19427. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19428. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19429. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19430. 9: function(n) {return Number(n >= 2);},
  19431. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19432. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19433. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19434. 13: function(n) {return Number(n !== 0);},
  19435. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19436. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19437. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19438. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19439. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19440. 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);},
  19441. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19442. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19443. };
  19444. var pluralExtensions = {
  19445. rules: (function () {
  19446. var l, rules = {};
  19447. for (l=_rules.length; l-- ;) {
  19448. rules[_rules[l][0]] = {
  19449. name: _rules[l][1],
  19450. numbers: _rules[l][2],
  19451. plurals: _rulesPluralsTypes[_rules[l][3]]
  19452. }
  19453. }
  19454. return rules;
  19455. }()),
  19456. // you can add your own pluralExtensions
  19457. addRule: function(lng, obj) {
  19458. pluralExtensions.rules[lng] = obj;
  19459. },
  19460. setCurrentLng: function(lng) {
  19461. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19462. var parts = lng.split('-');
  19463. pluralExtensions.currentRule = {
  19464. lng: lng,
  19465. rule: pluralExtensions.rules[parts[0]]
  19466. };
  19467. }
  19468. },
  19469. needsPlural: function(lng, count) {
  19470. var parts = lng.split('-');
  19471. var ext;
  19472. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19473. ext = pluralExtensions.currentRule.rule;
  19474. } else {
  19475. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19476. }
  19477. if (ext && ext.numbers.length <= 1) {
  19478. return false;
  19479. } else {
  19480. return this.get(lng, count) !== 1;
  19481. }
  19482. },
  19483. get: function(lng, count) {
  19484. var parts = lng.split('-');
  19485. function getResult(l, c) {
  19486. var ext;
  19487. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19488. ext = pluralExtensions.currentRule.rule;
  19489. } else {
  19490. ext = pluralExtensions.rules[l];
  19491. }
  19492. if (ext) {
  19493. var i;
  19494. if (ext.noAbs) {
  19495. i = ext.plurals(c);
  19496. } else {
  19497. i = ext.plurals(Math.abs(c));
  19498. }
  19499. var number = ext.numbers[i];
  19500. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19501. if (number === 2) {
  19502. number = -1; // regular plural
  19503. } else if (number === 1) {
  19504. number = 1; // singular
  19505. }
  19506. }//console.log(count + '-' + number);
  19507. return number;
  19508. } else {
  19509. return c === 1 ? '1' : '-1';
  19510. }
  19511. }
  19512. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19513. }
  19514. };
  19515. var postProcessors = {};
  19516. var addPostProcessor = function(name, fc) {
  19517. postProcessors[name] = fc;
  19518. };
  19519. // sprintf support
  19520. var sprintf = (function() {
  19521. function get_type(variable) {
  19522. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19523. }
  19524. function str_repeat(input, multiplier) {
  19525. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19526. return output.join('');
  19527. }
  19528. var str_format = function() {
  19529. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19530. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19531. }
  19532. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19533. };
  19534. str_format.format = function(parse_tree, argv) {
  19535. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19536. for (i = 0; i < tree_length; i++) {
  19537. node_type = get_type(parse_tree[i]);
  19538. if (node_type === 'string') {
  19539. output.push(parse_tree[i]);
  19540. }
  19541. else if (node_type === 'array') {
  19542. match = parse_tree[i]; // convenience purposes only
  19543. if (match[2]) { // keyword argument
  19544. arg = argv[cursor];
  19545. for (k = 0; k < match[2].length; k++) {
  19546. if (!arg.hasOwnProperty(match[2][k])) {
  19547. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19548. }
  19549. arg = arg[match[2][k]];
  19550. }
  19551. }
  19552. else if (match[1]) { // positional argument (explicit)
  19553. arg = argv[match[1]];
  19554. }
  19555. else { // positional argument (implicit)
  19556. arg = argv[cursor++];
  19557. }
  19558. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19559. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19560. }
  19561. switch (match[8]) {
  19562. case 'b': arg = arg.toString(2); break;
  19563. case 'c': arg = String.fromCharCode(arg); break;
  19564. case 'd': arg = parseInt(arg, 10); break;
  19565. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19566. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19567. case 'o': arg = arg.toString(8); break;
  19568. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19569. case 'u': arg = Math.abs(arg); break;
  19570. case 'x': arg = arg.toString(16); break;
  19571. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19572. }
  19573. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19574. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19575. pad_length = match[6] - String(arg).length;
  19576. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19577. output.push(match[5] ? arg + pad : pad + arg);
  19578. }
  19579. }
  19580. return output.join('');
  19581. };
  19582. str_format.cache = {};
  19583. str_format.parse = function(fmt) {
  19584. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19585. while (_fmt) {
  19586. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19587. parse_tree.push(match[0]);
  19588. }
  19589. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19590. parse_tree.push('%');
  19591. }
  19592. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19593. if (match[2]) {
  19594. arg_names |= 1;
  19595. var field_list = [], replacement_field = match[2], field_match = [];
  19596. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19597. field_list.push(field_match[1]);
  19598. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19599. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19600. field_list.push(field_match[1]);
  19601. }
  19602. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19603. field_list.push(field_match[1]);
  19604. }
  19605. else {
  19606. throw('[sprintf] huh?');
  19607. }
  19608. }
  19609. }
  19610. else {
  19611. throw('[sprintf] huh?');
  19612. }
  19613. match[2] = field_list;
  19614. }
  19615. else {
  19616. arg_names |= 2;
  19617. }
  19618. if (arg_names === 3) {
  19619. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19620. }
  19621. parse_tree.push(match);
  19622. }
  19623. else {
  19624. throw('[sprintf] huh?');
  19625. }
  19626. _fmt = _fmt.substring(match[0].length);
  19627. }
  19628. return parse_tree;
  19629. };
  19630. return str_format;
  19631. })();
  19632. var vsprintf = function(fmt, argv) {
  19633. argv.unshift(fmt);
  19634. return sprintf.apply(null, argv);
  19635. };
  19636. addPostProcessor("sprintf", function(val, key, opts) {
  19637. if (!opts.sprintf) return val;
  19638. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19639. return vsprintf(val, opts.sprintf);
  19640. } else if (typeof opts.sprintf === 'object') {
  19641. return sprintf(val, opts.sprintf);
  19642. }
  19643. return val;
  19644. });
  19645. // public api interface
  19646. i18n.init = init;
  19647. i18n.setLng = setLng;
  19648. i18n.preload = preload;
  19649. i18n.addResourceBundle = addResourceBundle;
  19650. i18n.hasResourceBundle = hasResourceBundle;
  19651. i18n.addResource = addResource;
  19652. i18n.addResources = addResources;
  19653. i18n.removeResourceBundle = removeResourceBundle;
  19654. i18n.loadNamespace = loadNamespace;
  19655. i18n.loadNamespaces = loadNamespaces;
  19656. i18n.setDefaultNamespace = setDefaultNamespace;
  19657. i18n.t = translate;
  19658. i18n.translate = translate;
  19659. i18n.exists = exists;
  19660. i18n.detectLanguage = f.detectLanguage;
  19661. i18n.pluralExtensions = pluralExtensions;
  19662. i18n.sync = sync;
  19663. i18n.functions = f;
  19664. i18n.lng = lng;
  19665. i18n.addPostProcessor = addPostProcessor;
  19666. i18n.options = o;
  19667. })();
  19668. },{"jquery":"jquery"}],71:[function(require,module,exports){
  19669. /*
  19670. A JavaScript implementation of the SHA family of hashes, as
  19671. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  19672. as defined in FIPS PUB 198a
  19673. Copyright Brian Turek 2008-2013
  19674. Distributed under the BSD License
  19675. See http://caligatio.github.com/jsSHA/ for more information
  19676. Several functions taken from Paul Johnston
  19677. */
  19678. (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"!==
  19679. 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";
  19680. 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"===
  19681. 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|
  19682. (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,
  19683. 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,
  19684. 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=
  19685. {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):
  19686. 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,
  19687. 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>>>
  19688. 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>>>
  19689. 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>>>
  19690. 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-
  19691. 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,
  19692. 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,
  19693. 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],
  19694. 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),
  19695. 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),
  19696. 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,
  19697. 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,
  19698. 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?
  19699. 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,
  19700. 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);
  19701. },{}],72:[function(require,module,exports){
  19702. // Top level file is just a mixin of submodules & constants
  19703. 'use strict';
  19704. var assign = require('./lib/utils/common').assign;
  19705. var deflate = require('./lib/deflate');
  19706. var inflate = require('./lib/inflate');
  19707. var constants = require('./lib/zlib/constants');
  19708. var pako = {};
  19709. assign(pako, deflate, inflate, constants);
  19710. module.exports = pako;
  19711. },{"./lib/deflate":73,"./lib/inflate":74,"./lib/utils/common":75,"./lib/zlib/constants":78}],73:[function(require,module,exports){
  19712. 'use strict';
  19713. var zlib_deflate = require('./zlib/deflate.js');
  19714. var utils = require('./utils/common');
  19715. var strings = require('./utils/strings');
  19716. var msg = require('./zlib/messages');
  19717. var zstream = require('./zlib/zstream');
  19718. var toString = Object.prototype.toString;
  19719. /* Public constants ==========================================================*/
  19720. /* ===========================================================================*/
  19721. var Z_NO_FLUSH = 0;
  19722. var Z_FINISH = 4;
  19723. var Z_OK = 0;
  19724. var Z_STREAM_END = 1;
  19725. var Z_SYNC_FLUSH = 2;
  19726. var Z_DEFAULT_COMPRESSION = -1;
  19727. var Z_DEFAULT_STRATEGY = 0;
  19728. var Z_DEFLATED = 8;
  19729. /* ===========================================================================*/
  19730. /**
  19731. * class Deflate
  19732. *
  19733. * Generic JS-style wrapper for zlib calls. If you don't need
  19734. * streaming behaviour - use more simple functions: [[deflate]],
  19735. * [[deflateRaw]] and [[gzip]].
  19736. **/
  19737. /* internal
  19738. * Deflate.chunks -> Array
  19739. *
  19740. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19741. **/
  19742. /**
  19743. * Deflate.result -> Uint8Array|Array
  19744. *
  19745. * Compressed result, generated by default [[Deflate#onData]]
  19746. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19747. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19748. * push a chunk with explicit flush (call [[Deflate#push]] with
  19749. * `Z_SYNC_FLUSH` param).
  19750. **/
  19751. /**
  19752. * Deflate.err -> Number
  19753. *
  19754. * Error code after deflate finished. 0 (Z_OK) on success.
  19755. * You will not need it in real life, because deflate errors
  19756. * are possible only on wrong options or bad `onData` / `onEnd`
  19757. * custom handlers.
  19758. **/
  19759. /**
  19760. * Deflate.msg -> String
  19761. *
  19762. * Error message, if [[Deflate.err]] != 0
  19763. **/
  19764. /**
  19765. * new Deflate(options)
  19766. * - options (Object): zlib deflate options.
  19767. *
  19768. * Creates new deflator instance with specified params. Throws exception
  19769. * on bad params. Supported options:
  19770. *
  19771. * - `level`
  19772. * - `windowBits`
  19773. * - `memLevel`
  19774. * - `strategy`
  19775. *
  19776. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19777. * for more information on these.
  19778. *
  19779. * Additional options, for internal needs:
  19780. *
  19781. * - `chunkSize` - size of generated data chunks (16K by default)
  19782. * - `raw` (Boolean) - do raw deflate
  19783. * - `gzip` (Boolean) - create gzip wrapper
  19784. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19785. * (each char code [0..255])
  19786. * - `header` (Object) - custom header for gzip
  19787. * - `text` (Boolean) - true if compressed data believed to be text
  19788. * - `time` (Number) - modification time, unix timestamp
  19789. * - `os` (Number) - operation system code
  19790. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19791. * - `name` (String) - file name (binary string)
  19792. * - `comment` (String) - comment (binary string)
  19793. * - `hcrc` (Boolean) - true if header crc should be added
  19794. *
  19795. * ##### Example:
  19796. *
  19797. * ```javascript
  19798. * var pako = require('pako')
  19799. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19800. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19801. *
  19802. * var deflate = new pako.Deflate({ level: 3});
  19803. *
  19804. * deflate.push(chunk1, false);
  19805. * deflate.push(chunk2, true); // true -> last chunk
  19806. *
  19807. * if (deflate.err) { throw new Error(deflate.err); }
  19808. *
  19809. * console.log(deflate.result);
  19810. * ```
  19811. **/
  19812. var Deflate = function(options) {
  19813. this.options = utils.assign({
  19814. level: Z_DEFAULT_COMPRESSION,
  19815. method: Z_DEFLATED,
  19816. chunkSize: 16384,
  19817. windowBits: 15,
  19818. memLevel: 8,
  19819. strategy: Z_DEFAULT_STRATEGY,
  19820. to: ''
  19821. }, options || {});
  19822. var opt = this.options;
  19823. if (opt.raw && (opt.windowBits > 0)) {
  19824. opt.windowBits = -opt.windowBits;
  19825. }
  19826. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19827. opt.windowBits += 16;
  19828. }
  19829. this.err = 0; // error code, if happens (0 = Z_OK)
  19830. this.msg = ''; // error message
  19831. this.ended = false; // used to avoid multiple onEnd() calls
  19832. this.chunks = []; // chunks of compressed data
  19833. this.strm = new zstream();
  19834. this.strm.avail_out = 0;
  19835. var status = zlib_deflate.deflateInit2(
  19836. this.strm,
  19837. opt.level,
  19838. opt.method,
  19839. opt.windowBits,
  19840. opt.memLevel,
  19841. opt.strategy
  19842. );
  19843. if (status !== Z_OK) {
  19844. throw new Error(msg[status]);
  19845. }
  19846. if (opt.header) {
  19847. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19848. }
  19849. };
  19850. /**
  19851. * Deflate#push(data[, mode]) -> Boolean
  19852. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19853. * converted to utf8 byte sequence.
  19854. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19855. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19856. *
  19857. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19858. * new compressed chunks. Returns `true` on success. The last data block must have
  19859. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19860. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19861. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19862. *
  19863. * On fail call [[Deflate#onEnd]] with error code and return false.
  19864. *
  19865. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19866. * array format is detected automatically). Also, don't skip last param and always
  19867. * use the same type in your code (boolean or number). That will improve JS speed.
  19868. *
  19869. * For regular `Array`-s make sure all elements are [0..255].
  19870. *
  19871. * ##### Example
  19872. *
  19873. * ```javascript
  19874. * push(chunk, false); // push one of data chunks
  19875. * ...
  19876. * push(chunk, true); // push last chunk
  19877. * ```
  19878. **/
  19879. Deflate.prototype.push = function(data, mode) {
  19880. var strm = this.strm;
  19881. var chunkSize = this.options.chunkSize;
  19882. var status, _mode;
  19883. if (this.ended) { return false; }
  19884. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19885. // Convert data if needed
  19886. if (typeof data === 'string') {
  19887. // If we need to compress text, change encoding to utf8.
  19888. strm.input = strings.string2buf(data);
  19889. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19890. strm.input = new Uint8Array(data);
  19891. } else {
  19892. strm.input = data;
  19893. }
  19894. strm.next_in = 0;
  19895. strm.avail_in = strm.input.length;
  19896. do {
  19897. if (strm.avail_out === 0) {
  19898. strm.output = new utils.Buf8(chunkSize);
  19899. strm.next_out = 0;
  19900. strm.avail_out = chunkSize;
  19901. }
  19902. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19903. if (status !== Z_STREAM_END && status !== Z_OK) {
  19904. this.onEnd(status);
  19905. this.ended = true;
  19906. return false;
  19907. }
  19908. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19909. if (this.options.to === 'string') {
  19910. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19911. } else {
  19912. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19913. }
  19914. }
  19915. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19916. // Finalize on the last chunk.
  19917. if (_mode === Z_FINISH) {
  19918. status = zlib_deflate.deflateEnd(this.strm);
  19919. this.onEnd(status);
  19920. this.ended = true;
  19921. return status === Z_OK;
  19922. }
  19923. // callback interim results if Z_SYNC_FLUSH.
  19924. if (_mode === Z_SYNC_FLUSH) {
  19925. this.onEnd(Z_OK);
  19926. strm.avail_out = 0;
  19927. return true;
  19928. }
  19929. return true;
  19930. };
  19931. /**
  19932. * Deflate#onData(chunk) -> Void
  19933. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19934. * on js engine support. When string output requested, each chunk
  19935. * will be string.
  19936. *
  19937. * By default, stores data blocks in `chunks[]` property and glue
  19938. * those in `onEnd`. Override this handler, if you need another behaviour.
  19939. **/
  19940. Deflate.prototype.onData = function(chunk) {
  19941. this.chunks.push(chunk);
  19942. };
  19943. /**
  19944. * Deflate#onEnd(status) -> Void
  19945. * - status (Number): deflate status. 0 (Z_OK) on success,
  19946. * other if not.
  19947. *
  19948. * Called once after you tell deflate that the input stream is
  19949. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19950. * or if an error happened. By default - join collected chunks,
  19951. * free memory and fill `results` / `err` properties.
  19952. **/
  19953. Deflate.prototype.onEnd = function(status) {
  19954. // On success - join
  19955. if (status === Z_OK) {
  19956. if (this.options.to === 'string') {
  19957. this.result = this.chunks.join('');
  19958. } else {
  19959. this.result = utils.flattenChunks(this.chunks);
  19960. }
  19961. }
  19962. this.chunks = [];
  19963. this.err = status;
  19964. this.msg = this.strm.msg;
  19965. };
  19966. /**
  19967. * deflate(data[, options]) -> Uint8Array|Array|String
  19968. * - data (Uint8Array|Array|String): input data to compress.
  19969. * - options (Object): zlib deflate options.
  19970. *
  19971. * Compress `data` with deflate alrorythm and `options`.
  19972. *
  19973. * Supported options are:
  19974. *
  19975. * - level
  19976. * - windowBits
  19977. * - memLevel
  19978. * - strategy
  19979. *
  19980. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19981. * for more information on these.
  19982. *
  19983. * Sugar (options):
  19984. *
  19985. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19986. * negative windowBits implicitly.
  19987. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19988. * (each char code [0..255])
  19989. *
  19990. * ##### Example:
  19991. *
  19992. * ```javascript
  19993. * var pako = require('pako')
  19994. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19995. *
  19996. * console.log(pako.deflate(data));
  19997. * ```
  19998. **/
  19999. function deflate(input, options) {
  20000. var deflator = new Deflate(options);
  20001. deflator.push(input, true);
  20002. // That will never happens, if you don't cheat with options :)
  20003. if (deflator.err) { throw deflator.msg; }
  20004. return deflator.result;
  20005. }
  20006. /**
  20007. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  20008. * - data (Uint8Array|Array|String): input data to compress.
  20009. * - options (Object): zlib deflate options.
  20010. *
  20011. * The same as [[deflate]], but creates raw data, without wrapper
  20012. * (header and adler32 crc).
  20013. **/
  20014. function deflateRaw(input, options) {
  20015. options = options || {};
  20016. options.raw = true;
  20017. return deflate(input, options);
  20018. }
  20019. /**
  20020. * gzip(data[, options]) -> Uint8Array|Array|String
  20021. * - data (Uint8Array|Array|String): input data to compress.
  20022. * - options (Object): zlib deflate options.
  20023. *
  20024. * The same as [[deflate]], but create gzip wrapper instead of
  20025. * deflate one.
  20026. **/
  20027. function gzip(input, options) {
  20028. options = options || {};
  20029. options.gzip = true;
  20030. return deflate(input, options);
  20031. }
  20032. exports.Deflate = Deflate;
  20033. exports.deflate = deflate;
  20034. exports.deflateRaw = deflateRaw;
  20035. exports.gzip = gzip;
  20036. },{"./utils/common":75,"./utils/strings":76,"./zlib/deflate.js":80,"./zlib/messages":85,"./zlib/zstream":87}],74:[function(require,module,exports){
  20037. 'use strict';
  20038. var zlib_inflate = require('./zlib/inflate.js');
  20039. var utils = require('./utils/common');
  20040. var strings = require('./utils/strings');
  20041. var c = require('./zlib/constants');
  20042. var msg = require('./zlib/messages');
  20043. var zstream = require('./zlib/zstream');
  20044. var gzheader = require('./zlib/gzheader');
  20045. var toString = Object.prototype.toString;
  20046. /**
  20047. * class Inflate
  20048. *
  20049. * Generic JS-style wrapper for zlib calls. If you don't need
  20050. * streaming behaviour - use more simple functions: [[inflate]]
  20051. * and [[inflateRaw]].
  20052. **/
  20053. /* internal
  20054. * inflate.chunks -> Array
  20055. *
  20056. * Chunks of output data, if [[Inflate#onData]] not overriden.
  20057. **/
  20058. /**
  20059. * Inflate.result -> Uint8Array|Array|String
  20060. *
  20061. * Uncompressed result, generated by default [[Inflate#onData]]
  20062. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  20063. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  20064. * push a chunk with explicit flush (call [[Inflate#push]] with
  20065. * `Z_SYNC_FLUSH` param).
  20066. **/
  20067. /**
  20068. * Inflate.err -> Number
  20069. *
  20070. * Error code after inflate finished. 0 (Z_OK) on success.
  20071. * Should be checked if broken data possible.
  20072. **/
  20073. /**
  20074. * Inflate.msg -> String
  20075. *
  20076. * Error message, if [[Inflate.err]] != 0
  20077. **/
  20078. /**
  20079. * new Inflate(options)
  20080. * - options (Object): zlib inflate options.
  20081. *
  20082. * Creates new inflator instance with specified params. Throws exception
  20083. * on bad params. Supported options:
  20084. *
  20085. * - `windowBits`
  20086. *
  20087. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20088. * for more information on these.
  20089. *
  20090. * Additional options, for internal needs:
  20091. *
  20092. * - `chunkSize` - size of generated data chunks (16K by default)
  20093. * - `raw` (Boolean) - do raw inflate
  20094. * - `to` (String) - if equal to 'string', then result will be converted
  20095. * from utf8 to utf16 (javascript) string. When string output requested,
  20096. * chunk length can differ from `chunkSize`, depending on content.
  20097. *
  20098. * By default, when no options set, autodetect deflate/gzip data format via
  20099. * wrapper header.
  20100. *
  20101. * ##### Example:
  20102. *
  20103. * ```javascript
  20104. * var pako = require('pako')
  20105. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20106. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20107. *
  20108. * var inflate = new pako.Inflate({ level: 3});
  20109. *
  20110. * inflate.push(chunk1, false);
  20111. * inflate.push(chunk2, true); // true -> last chunk
  20112. *
  20113. * if (inflate.err) { throw new Error(inflate.err); }
  20114. *
  20115. * console.log(inflate.result);
  20116. * ```
  20117. **/
  20118. var Inflate = function(options) {
  20119. this.options = utils.assign({
  20120. chunkSize: 16384,
  20121. windowBits: 0,
  20122. to: ''
  20123. }, options || {});
  20124. var opt = this.options;
  20125. // Force window size for `raw` data, if not set directly,
  20126. // because we have no header for autodetect.
  20127. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  20128. opt.windowBits = -opt.windowBits;
  20129. if (opt.windowBits === 0) { opt.windowBits = -15; }
  20130. }
  20131. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  20132. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  20133. !(options && options.windowBits)) {
  20134. opt.windowBits += 32;
  20135. }
  20136. // Gzip header has no info about windows size, we can do autodetect only
  20137. // for deflate. So, if window size not set, force it to max when gzip possible
  20138. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  20139. // bit 3 (16) -> gzipped data
  20140. // bit 4 (32) -> autodetect gzip/deflate
  20141. if ((opt.windowBits & 15) === 0) {
  20142. opt.windowBits |= 15;
  20143. }
  20144. }
  20145. this.err = 0; // error code, if happens (0 = Z_OK)
  20146. this.msg = ''; // error message
  20147. this.ended = false; // used to avoid multiple onEnd() calls
  20148. this.chunks = []; // chunks of compressed data
  20149. this.strm = new zstream();
  20150. this.strm.avail_out = 0;
  20151. var status = zlib_inflate.inflateInit2(
  20152. this.strm,
  20153. opt.windowBits
  20154. );
  20155. if (status !== c.Z_OK) {
  20156. throw new Error(msg[status]);
  20157. }
  20158. this.header = new gzheader();
  20159. zlib_inflate.inflateGetHeader(this.strm, this.header);
  20160. };
  20161. /**
  20162. * Inflate#push(data[, mode]) -> Boolean
  20163. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  20164. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20165. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20166. *
  20167. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  20168. * new output chunks. Returns `true` on success. The last data block must have
  20169. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20170. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20171. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  20172. *
  20173. * On fail call [[Inflate#onEnd]] with error code and return false.
  20174. *
  20175. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20176. * format is detected automatically). Also, don't skip last param and always
  20177. * use the same type in your code (boolean or number). That will improve JS speed.
  20178. *
  20179. * For regular `Array`-s make sure all elements are [0..255].
  20180. *
  20181. * ##### Example
  20182. *
  20183. * ```javascript
  20184. * push(chunk, false); // push one of data chunks
  20185. * ...
  20186. * push(chunk, true); // push last chunk
  20187. * ```
  20188. **/
  20189. Inflate.prototype.push = function(data, mode) {
  20190. var strm = this.strm;
  20191. var chunkSize = this.options.chunkSize;
  20192. var status, _mode;
  20193. var next_out_utf8, tail, utf8str;
  20194. if (this.ended) { return false; }
  20195. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  20196. // Convert data if needed
  20197. if (typeof data === 'string') {
  20198. // Only binary strings can be decompressed on practice
  20199. strm.input = strings.binstring2buf(data);
  20200. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20201. strm.input = new Uint8Array(data);
  20202. } else {
  20203. strm.input = data;
  20204. }
  20205. strm.next_in = 0;
  20206. strm.avail_in = strm.input.length;
  20207. do {
  20208. if (strm.avail_out === 0) {
  20209. strm.output = new utils.Buf8(chunkSize);
  20210. strm.next_out = 0;
  20211. strm.avail_out = chunkSize;
  20212. }
  20213. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20214. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20215. this.onEnd(status);
  20216. this.ended = true;
  20217. return false;
  20218. }
  20219. if (strm.next_out) {
  20220. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20221. if (this.options.to === 'string') {
  20222. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20223. tail = strm.next_out - next_out_utf8;
  20224. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20225. // move tail
  20226. strm.next_out = tail;
  20227. strm.avail_out = chunkSize - tail;
  20228. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20229. this.onData(utf8str);
  20230. } else {
  20231. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20232. }
  20233. }
  20234. }
  20235. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20236. if (status === c.Z_STREAM_END) {
  20237. _mode = c.Z_FINISH;
  20238. }
  20239. // Finalize on the last chunk.
  20240. if (_mode === c.Z_FINISH) {
  20241. status = zlib_inflate.inflateEnd(this.strm);
  20242. this.onEnd(status);
  20243. this.ended = true;
  20244. return status === c.Z_OK;
  20245. }
  20246. // callback interim results if Z_SYNC_FLUSH.
  20247. if (_mode === c.Z_SYNC_FLUSH) {
  20248. this.onEnd(c.Z_OK);
  20249. strm.avail_out = 0;
  20250. return true;
  20251. }
  20252. return true;
  20253. };
  20254. /**
  20255. * Inflate#onData(chunk) -> Void
  20256. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20257. * on js engine support. When string output requested, each chunk
  20258. * will be string.
  20259. *
  20260. * By default, stores data blocks in `chunks[]` property and glue
  20261. * those in `onEnd`. Override this handler, if you need another behaviour.
  20262. **/
  20263. Inflate.prototype.onData = function(chunk) {
  20264. this.chunks.push(chunk);
  20265. };
  20266. /**
  20267. * Inflate#onEnd(status) -> Void
  20268. * - status (Number): inflate status. 0 (Z_OK) on success,
  20269. * other if not.
  20270. *
  20271. * Called either after you tell inflate that the input stream is
  20272. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20273. * or if an error happened. By default - join collected chunks,
  20274. * free memory and fill `results` / `err` properties.
  20275. **/
  20276. Inflate.prototype.onEnd = function(status) {
  20277. // On success - join
  20278. if (status === c.Z_OK) {
  20279. if (this.options.to === 'string') {
  20280. // Glue & convert here, until we teach pako to send
  20281. // utf8 alligned strings to onData
  20282. this.result = this.chunks.join('');
  20283. } else {
  20284. this.result = utils.flattenChunks(this.chunks);
  20285. }
  20286. }
  20287. this.chunks = [];
  20288. this.err = status;
  20289. this.msg = this.strm.msg;
  20290. };
  20291. /**
  20292. * inflate(data[, options]) -> Uint8Array|Array|String
  20293. * - data (Uint8Array|Array|String): input data to decompress.
  20294. * - options (Object): zlib inflate options.
  20295. *
  20296. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20297. * format via wrapper header by default. That's why we don't provide
  20298. * separate `ungzip` method.
  20299. *
  20300. * Supported options are:
  20301. *
  20302. * - windowBits
  20303. *
  20304. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20305. * for more information.
  20306. *
  20307. * Sugar (options):
  20308. *
  20309. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20310. * negative windowBits implicitly.
  20311. * - `to` (String) - if equal to 'string', then result will be converted
  20312. * from utf8 to utf16 (javascript) string. When string output requested,
  20313. * chunk length can differ from `chunkSize`, depending on content.
  20314. *
  20315. *
  20316. * ##### Example:
  20317. *
  20318. * ```javascript
  20319. * var pako = require('pako')
  20320. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20321. * , output;
  20322. *
  20323. * try {
  20324. * output = pako.inflate(input);
  20325. * } catch (err)
  20326. * console.log(err);
  20327. * }
  20328. * ```
  20329. **/
  20330. function inflate(input, options) {
  20331. var inflator = new Inflate(options);
  20332. inflator.push(input, true);
  20333. // That will never happens, if you don't cheat with options :)
  20334. if (inflator.err) { throw inflator.msg; }
  20335. return inflator.result;
  20336. }
  20337. /**
  20338. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20339. * - data (Uint8Array|Array|String): input data to decompress.
  20340. * - options (Object): zlib inflate options.
  20341. *
  20342. * The same as [[inflate]], but creates raw data, without wrapper
  20343. * (header and adler32 crc).
  20344. **/
  20345. function inflateRaw(input, options) {
  20346. options = options || {};
  20347. options.raw = true;
  20348. return inflate(input, options);
  20349. }
  20350. /**
  20351. * ungzip(data[, options]) -> Uint8Array|Array|String
  20352. * - data (Uint8Array|Array|String): input data to decompress.
  20353. * - options (Object): zlib inflate options.
  20354. *
  20355. * Just shortcut to [[inflate]], because it autodetects format
  20356. * by header.content. Done for convenience.
  20357. **/
  20358. exports.Inflate = Inflate;
  20359. exports.inflate = inflate;
  20360. exports.inflateRaw = inflateRaw;
  20361. exports.ungzip = inflate;
  20362. },{"./utils/common":75,"./utils/strings":76,"./zlib/constants":78,"./zlib/gzheader":81,"./zlib/inflate.js":83,"./zlib/messages":85,"./zlib/zstream":87}],75:[function(require,module,exports){
  20363. 'use strict';
  20364. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20365. (typeof Uint16Array !== 'undefined') &&
  20366. (typeof Int32Array !== 'undefined');
  20367. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20368. var sources = Array.prototype.slice.call(arguments, 1);
  20369. while (sources.length) {
  20370. var source = sources.shift();
  20371. if (!source) { continue; }
  20372. if (typeof source !== 'object') {
  20373. throw new TypeError(source + 'must be non-object');
  20374. }
  20375. for (var p in source) {
  20376. if (source.hasOwnProperty(p)) {
  20377. obj[p] = source[p];
  20378. }
  20379. }
  20380. }
  20381. return obj;
  20382. };
  20383. // reduce buffer size, avoiding mem copy
  20384. exports.shrinkBuf = function (buf, size) {
  20385. if (buf.length === size) { return buf; }
  20386. if (buf.subarray) { return buf.subarray(0, size); }
  20387. buf.length = size;
  20388. return buf;
  20389. };
  20390. var fnTyped = {
  20391. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20392. if (src.subarray && dest.subarray) {
  20393. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20394. return;
  20395. }
  20396. // Fallback to ordinary array
  20397. for (var i=0; i<len; i++) {
  20398. dest[dest_offs + i] = src[src_offs + i];
  20399. }
  20400. },
  20401. // Join array of chunks to single array.
  20402. flattenChunks: function(chunks) {
  20403. var i, l, len, pos, chunk, result;
  20404. // calculate data length
  20405. len = 0;
  20406. for (i=0, l=chunks.length; i<l; i++) {
  20407. len += chunks[i].length;
  20408. }
  20409. // join chunks
  20410. result = new Uint8Array(len);
  20411. pos = 0;
  20412. for (i=0, l=chunks.length; i<l; i++) {
  20413. chunk = chunks[i];
  20414. result.set(chunk, pos);
  20415. pos += chunk.length;
  20416. }
  20417. return result;
  20418. }
  20419. };
  20420. var fnUntyped = {
  20421. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20422. for (var i=0; i<len; i++) {
  20423. dest[dest_offs + i] = src[src_offs + i];
  20424. }
  20425. },
  20426. // Join array of chunks to single array.
  20427. flattenChunks: function(chunks) {
  20428. return [].concat.apply([], chunks);
  20429. }
  20430. };
  20431. // Enable/Disable typed arrays use, for testing
  20432. //
  20433. exports.setTyped = function (on) {
  20434. if (on) {
  20435. exports.Buf8 = Uint8Array;
  20436. exports.Buf16 = Uint16Array;
  20437. exports.Buf32 = Int32Array;
  20438. exports.assign(exports, fnTyped);
  20439. } else {
  20440. exports.Buf8 = Array;
  20441. exports.Buf16 = Array;
  20442. exports.Buf32 = Array;
  20443. exports.assign(exports, fnUntyped);
  20444. }
  20445. };
  20446. exports.setTyped(TYPED_OK);
  20447. },{}],76:[function(require,module,exports){
  20448. // String encode/decode helpers
  20449. 'use strict';
  20450. var utils = require('./common');
  20451. // Quick check if we can use fast array to bin string conversion
  20452. //
  20453. // - apply(Array) can fail on Android 2.2
  20454. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20455. //
  20456. var STR_APPLY_OK = true;
  20457. var STR_APPLY_UIA_OK = true;
  20458. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20459. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20460. // Table with utf8 lengths (calculated by first byte of sequence)
  20461. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20462. // because max possible codepoint is 0x10ffff
  20463. var _utf8len = new utils.Buf8(256);
  20464. for (var q=0; q<256; q++) {
  20465. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20466. }
  20467. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20468. // convert string to array (typed, when possible)
  20469. exports.string2buf = function (str) {
  20470. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20471. // count binary size
  20472. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20473. c = str.charCodeAt(m_pos);
  20474. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20475. c2 = str.charCodeAt(m_pos+1);
  20476. if ((c2 & 0xfc00) === 0xdc00) {
  20477. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20478. m_pos++;
  20479. }
  20480. }
  20481. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20482. }
  20483. // allocate buffer
  20484. buf = new utils.Buf8(buf_len);
  20485. // convert
  20486. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20487. c = str.charCodeAt(m_pos);
  20488. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20489. c2 = str.charCodeAt(m_pos+1);
  20490. if ((c2 & 0xfc00) === 0xdc00) {
  20491. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20492. m_pos++;
  20493. }
  20494. }
  20495. if (c < 0x80) {
  20496. /* one byte */
  20497. buf[i++] = c;
  20498. } else if (c < 0x800) {
  20499. /* two bytes */
  20500. buf[i++] = 0xC0 | (c >>> 6);
  20501. buf[i++] = 0x80 | (c & 0x3f);
  20502. } else if (c < 0x10000) {
  20503. /* three bytes */
  20504. buf[i++] = 0xE0 | (c >>> 12);
  20505. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20506. buf[i++] = 0x80 | (c & 0x3f);
  20507. } else {
  20508. /* four bytes */
  20509. buf[i++] = 0xf0 | (c >>> 18);
  20510. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20511. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20512. buf[i++] = 0x80 | (c & 0x3f);
  20513. }
  20514. }
  20515. return buf;
  20516. };
  20517. // Helper (used in 2 places)
  20518. function buf2binstring(buf, len) {
  20519. // use fallback for big arrays to avoid stack overflow
  20520. if (len < 65537) {
  20521. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20522. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20523. }
  20524. }
  20525. var result = '';
  20526. for (var i=0; i < len; i++) {
  20527. result += String.fromCharCode(buf[i]);
  20528. }
  20529. return result;
  20530. }
  20531. // Convert byte array to binary string
  20532. exports.buf2binstring = function(buf) {
  20533. return buf2binstring(buf, buf.length);
  20534. };
  20535. // Convert binary string (typed, when possible)
  20536. exports.binstring2buf = function(str) {
  20537. var buf = new utils.Buf8(str.length);
  20538. for (var i=0, len=buf.length; i < len; i++) {
  20539. buf[i] = str.charCodeAt(i);
  20540. }
  20541. return buf;
  20542. };
  20543. // convert array to string
  20544. exports.buf2string = function (buf, max) {
  20545. var i, out, c, c_len;
  20546. var len = max || buf.length;
  20547. // Reserve max possible length (2 words per char)
  20548. // NB: by unknown reasons, Array is significantly faster for
  20549. // String.fromCharCode.apply than Uint16Array.
  20550. var utf16buf = new Array(len*2);
  20551. for (out=0, i=0; i<len;) {
  20552. c = buf[i++];
  20553. // quick process ascii
  20554. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20555. c_len = _utf8len[c];
  20556. // skip 5 & 6 byte codes
  20557. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20558. // apply mask on first byte
  20559. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20560. // join the rest
  20561. while (c_len > 1 && i < len) {
  20562. c = (c << 6) | (buf[i++] & 0x3f);
  20563. c_len--;
  20564. }
  20565. // terminated by end of string?
  20566. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20567. if (c < 0x10000) {
  20568. utf16buf[out++] = c;
  20569. } else {
  20570. c -= 0x10000;
  20571. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20572. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20573. }
  20574. }
  20575. return buf2binstring(utf16buf, out);
  20576. };
  20577. // Calculate max possible position in utf8 buffer,
  20578. // that will not break sequence. If that's not possible
  20579. // - (very small limits) return max size as is.
  20580. //
  20581. // buf[] - utf8 bytes array
  20582. // max - length limit (mandatory);
  20583. exports.utf8border = function(buf, max) {
  20584. var pos;
  20585. max = max || buf.length;
  20586. if (max > buf.length) { max = buf.length; }
  20587. // go back from last position, until start of sequence found
  20588. pos = max-1;
  20589. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20590. // Fuckup - very small and broken sequence,
  20591. // return max, because we should return something anyway.
  20592. if (pos < 0) { return max; }
  20593. // If we came to start of buffer - that means vuffer is too small,
  20594. // return max too.
  20595. if (pos === 0) { return max; }
  20596. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20597. };
  20598. },{"./common":75}],77:[function(require,module,exports){
  20599. 'use strict';
  20600. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20601. // It doesn't worth to make additional optimizationa as in original.
  20602. // Small size is preferable.
  20603. function adler32(adler, buf, len, pos) {
  20604. var s1 = (adler & 0xffff) |0,
  20605. s2 = ((adler >>> 16) & 0xffff) |0,
  20606. n = 0;
  20607. while (len !== 0) {
  20608. // Set limit ~ twice less than 5552, to keep
  20609. // s2 in 31-bits, because we force signed ints.
  20610. // in other case %= will fail.
  20611. n = len > 2000 ? 2000 : len;
  20612. len -= n;
  20613. do {
  20614. s1 = (s1 + buf[pos++]) |0;
  20615. s2 = (s2 + s1) |0;
  20616. } while (--n);
  20617. s1 %= 65521;
  20618. s2 %= 65521;
  20619. }
  20620. return (s1 | (s2 << 16)) |0;
  20621. }
  20622. module.exports = adler32;
  20623. },{}],78:[function(require,module,exports){
  20624. module.exports = {
  20625. /* Allowed flush values; see deflate() and inflate() below for details */
  20626. Z_NO_FLUSH: 0,
  20627. Z_PARTIAL_FLUSH: 1,
  20628. Z_SYNC_FLUSH: 2,
  20629. Z_FULL_FLUSH: 3,
  20630. Z_FINISH: 4,
  20631. Z_BLOCK: 5,
  20632. Z_TREES: 6,
  20633. /* Return codes for the compression/decompression functions. Negative values
  20634. * are errors, positive values are used for special but normal events.
  20635. */
  20636. Z_OK: 0,
  20637. Z_STREAM_END: 1,
  20638. Z_NEED_DICT: 2,
  20639. Z_ERRNO: -1,
  20640. Z_STREAM_ERROR: -2,
  20641. Z_DATA_ERROR: -3,
  20642. //Z_MEM_ERROR: -4,
  20643. Z_BUF_ERROR: -5,
  20644. //Z_VERSION_ERROR: -6,
  20645. /* compression levels */
  20646. Z_NO_COMPRESSION: 0,
  20647. Z_BEST_SPEED: 1,
  20648. Z_BEST_COMPRESSION: 9,
  20649. Z_DEFAULT_COMPRESSION: -1,
  20650. Z_FILTERED: 1,
  20651. Z_HUFFMAN_ONLY: 2,
  20652. Z_RLE: 3,
  20653. Z_FIXED: 4,
  20654. Z_DEFAULT_STRATEGY: 0,
  20655. /* Possible values of the data_type field (though see inflate()) */
  20656. Z_BINARY: 0,
  20657. Z_TEXT: 1,
  20658. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20659. Z_UNKNOWN: 2,
  20660. /* The deflate compression method */
  20661. Z_DEFLATED: 8
  20662. //Z_NULL: null // Use -1 or null inline, depending on var type
  20663. };
  20664. },{}],79:[function(require,module,exports){
  20665. 'use strict';
  20666. // Note: we can't get significant speed boost here.
  20667. // So write code to minimize size - no pregenerated tables
  20668. // and array tools dependencies.
  20669. // Use ordinary array, since untyped makes no boost here
  20670. function makeTable() {
  20671. var c, table = [];
  20672. for (var n =0; n < 256; n++) {
  20673. c = n;
  20674. for (var k =0; k < 8; k++) {
  20675. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20676. }
  20677. table[n] = c;
  20678. }
  20679. return table;
  20680. }
  20681. // Create table on load. Just 255 signed longs. Not a problem.
  20682. var crcTable = makeTable();
  20683. function crc32(crc, buf, len, pos) {
  20684. var t = crcTable,
  20685. end = pos + len;
  20686. crc = crc ^ (-1);
  20687. for (var i = pos; i < end; i++) {
  20688. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20689. }
  20690. return (crc ^ (-1)); // >>> 0;
  20691. }
  20692. module.exports = crc32;
  20693. },{}],80:[function(require,module,exports){
  20694. 'use strict';
  20695. var utils = require('../utils/common');
  20696. var trees = require('./trees');
  20697. var adler32 = require('./adler32');
  20698. var crc32 = require('./crc32');
  20699. var msg = require('./messages');
  20700. /* Public constants ==========================================================*/
  20701. /* ===========================================================================*/
  20702. /* Allowed flush values; see deflate() and inflate() below for details */
  20703. var Z_NO_FLUSH = 0;
  20704. var Z_PARTIAL_FLUSH = 1;
  20705. //var Z_SYNC_FLUSH = 2;
  20706. var Z_FULL_FLUSH = 3;
  20707. var Z_FINISH = 4;
  20708. var Z_BLOCK = 5;
  20709. //var Z_TREES = 6;
  20710. /* Return codes for the compression/decompression functions. Negative values
  20711. * are errors, positive values are used for special but normal events.
  20712. */
  20713. var Z_OK = 0;
  20714. var Z_STREAM_END = 1;
  20715. //var Z_NEED_DICT = 2;
  20716. //var Z_ERRNO = -1;
  20717. var Z_STREAM_ERROR = -2;
  20718. var Z_DATA_ERROR = -3;
  20719. //var Z_MEM_ERROR = -4;
  20720. var Z_BUF_ERROR = -5;
  20721. //var Z_VERSION_ERROR = -6;
  20722. /* compression levels */
  20723. //var Z_NO_COMPRESSION = 0;
  20724. //var Z_BEST_SPEED = 1;
  20725. //var Z_BEST_COMPRESSION = 9;
  20726. var Z_DEFAULT_COMPRESSION = -1;
  20727. var Z_FILTERED = 1;
  20728. var Z_HUFFMAN_ONLY = 2;
  20729. var Z_RLE = 3;
  20730. var Z_FIXED = 4;
  20731. var Z_DEFAULT_STRATEGY = 0;
  20732. /* Possible values of the data_type field (though see inflate()) */
  20733. //var Z_BINARY = 0;
  20734. //var Z_TEXT = 1;
  20735. //var Z_ASCII = 1; // = Z_TEXT
  20736. var Z_UNKNOWN = 2;
  20737. /* The deflate compression method */
  20738. var Z_DEFLATED = 8;
  20739. /*============================================================================*/
  20740. var MAX_MEM_LEVEL = 9;
  20741. /* Maximum value for memLevel in deflateInit2 */
  20742. var MAX_WBITS = 15;
  20743. /* 32K LZ77 window */
  20744. var DEF_MEM_LEVEL = 8;
  20745. var LENGTH_CODES = 29;
  20746. /* number of length codes, not counting the special END_BLOCK code */
  20747. var LITERALS = 256;
  20748. /* number of literal bytes 0..255 */
  20749. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20750. /* number of Literal or Length codes, including the END_BLOCK code */
  20751. var D_CODES = 30;
  20752. /* number of distance codes */
  20753. var BL_CODES = 19;
  20754. /* number of codes used to transfer the bit lengths */
  20755. var HEAP_SIZE = 2*L_CODES + 1;
  20756. /* maximum heap size */
  20757. var MAX_BITS = 15;
  20758. /* All codes must not exceed MAX_BITS bits */
  20759. var MIN_MATCH = 3;
  20760. var MAX_MATCH = 258;
  20761. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20762. var PRESET_DICT = 0x20;
  20763. var INIT_STATE = 42;
  20764. var EXTRA_STATE = 69;
  20765. var NAME_STATE = 73;
  20766. var COMMENT_STATE = 91;
  20767. var HCRC_STATE = 103;
  20768. var BUSY_STATE = 113;
  20769. var FINISH_STATE = 666;
  20770. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20771. var BS_BLOCK_DONE = 2; /* block flush performed */
  20772. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20773. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20774. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20775. function err(strm, errorCode) {
  20776. strm.msg = msg[errorCode];
  20777. return errorCode;
  20778. }
  20779. function rank(f) {
  20780. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20781. }
  20782. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20783. /* =========================================================================
  20784. * Flush as much pending output as possible. All deflate() output goes
  20785. * through this function so some applications may wish to modify it
  20786. * to avoid allocating a large strm->output buffer and copying into it.
  20787. * (See also read_buf()).
  20788. */
  20789. function flush_pending(strm) {
  20790. var s = strm.state;
  20791. //_tr_flush_bits(s);
  20792. var len = s.pending;
  20793. if (len > strm.avail_out) {
  20794. len = strm.avail_out;
  20795. }
  20796. if (len === 0) { return; }
  20797. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20798. strm.next_out += len;
  20799. s.pending_out += len;
  20800. strm.total_out += len;
  20801. strm.avail_out -= len;
  20802. s.pending -= len;
  20803. if (s.pending === 0) {
  20804. s.pending_out = 0;
  20805. }
  20806. }
  20807. function flush_block_only (s, last) {
  20808. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20809. s.block_start = s.strstart;
  20810. flush_pending(s.strm);
  20811. }
  20812. function put_byte(s, b) {
  20813. s.pending_buf[s.pending++] = b;
  20814. }
  20815. /* =========================================================================
  20816. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20817. * IN assertion: the stream state is correct and there is enough room in
  20818. * pending_buf.
  20819. */
  20820. function putShortMSB(s, b) {
  20821. // put_byte(s, (Byte)(b >> 8));
  20822. // put_byte(s, (Byte)(b & 0xff));
  20823. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20824. s.pending_buf[s.pending++] = b & 0xff;
  20825. }
  20826. /* ===========================================================================
  20827. * Read a new buffer from the current input stream, update the adler32
  20828. * and total number of bytes read. All deflate() input goes through
  20829. * this function so some applications may wish to modify it to avoid
  20830. * allocating a large strm->input buffer and copying from it.
  20831. * (See also flush_pending()).
  20832. */
  20833. function read_buf(strm, buf, start, size) {
  20834. var len = strm.avail_in;
  20835. if (len > size) { len = size; }
  20836. if (len === 0) { return 0; }
  20837. strm.avail_in -= len;
  20838. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20839. if (strm.state.wrap === 1) {
  20840. strm.adler = adler32(strm.adler, buf, len, start);
  20841. }
  20842. else if (strm.state.wrap === 2) {
  20843. strm.adler = crc32(strm.adler, buf, len, start);
  20844. }
  20845. strm.next_in += len;
  20846. strm.total_in += len;
  20847. return len;
  20848. }
  20849. /* ===========================================================================
  20850. * Set match_start to the longest match starting at the given string and
  20851. * return its length. Matches shorter or equal to prev_length are discarded,
  20852. * in which case the result is equal to prev_length and match_start is
  20853. * garbage.
  20854. * IN assertions: cur_match is the head of the hash chain for the current
  20855. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20856. * OUT assertion: the match length is not greater than s->lookahead.
  20857. */
  20858. function longest_match(s, cur_match) {
  20859. var chain_length = s.max_chain_length; /* max hash chain length */
  20860. var scan = s.strstart; /* current string */
  20861. var match; /* matched string */
  20862. var len; /* length of current match */
  20863. var best_len = s.prev_length; /* best match length so far */
  20864. var nice_match = s.nice_match; /* stop if match long enough */
  20865. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20866. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20867. var _win = s.window; // shortcut
  20868. var wmask = s.w_mask;
  20869. var prev = s.prev;
  20870. /* Stop when cur_match becomes <= limit. To simplify the code,
  20871. * we prevent matches with the string of window index 0.
  20872. */
  20873. var strend = s.strstart + MAX_MATCH;
  20874. var scan_end1 = _win[scan + best_len - 1];
  20875. var scan_end = _win[scan + best_len];
  20876. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20877. * It is easy to get rid of this optimization if necessary.
  20878. */
  20879. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20880. /* Do not waste too much time if we already have a good match: */
  20881. if (s.prev_length >= s.good_match) {
  20882. chain_length >>= 2;
  20883. }
  20884. /* Do not look for matches beyond the end of the input. This is necessary
  20885. * to make deflate deterministic.
  20886. */
  20887. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20888. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20889. do {
  20890. // Assert(cur_match < s->strstart, "no future");
  20891. match = cur_match;
  20892. /* Skip to next match if the match length cannot increase
  20893. * or if the match length is less than 2. Note that the checks below
  20894. * for insufficient lookahead only occur occasionally for performance
  20895. * reasons. Therefore uninitialized memory will be accessed, and
  20896. * conditional jumps will be made that depend on those values.
  20897. * However the length of the match is limited to the lookahead, so
  20898. * the output of deflate is not affected by the uninitialized values.
  20899. */
  20900. if (_win[match + best_len] !== scan_end ||
  20901. _win[match + best_len - 1] !== scan_end1 ||
  20902. _win[match] !== _win[scan] ||
  20903. _win[++match] !== _win[scan + 1]) {
  20904. continue;
  20905. }
  20906. /* The check at best_len-1 can be removed because it will be made
  20907. * again later. (This heuristic is not always a win.)
  20908. * It is not necessary to compare scan[2] and match[2] since they
  20909. * are always equal when the other bytes match, given that
  20910. * the hash keys are equal and that HASH_BITS >= 8.
  20911. */
  20912. scan += 2;
  20913. match++;
  20914. // Assert(*scan == *match, "match[2]?");
  20915. /* We check for insufficient lookahead only every 8th comparison;
  20916. * the 256th check will be made at strstart+258.
  20917. */
  20918. do {
  20919. /*jshint noempty:false*/
  20920. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20921. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20922. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20923. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20924. scan < strend);
  20925. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20926. len = MAX_MATCH - (strend - scan);
  20927. scan = strend - MAX_MATCH;
  20928. if (len > best_len) {
  20929. s.match_start = cur_match;
  20930. best_len = len;
  20931. if (len >= nice_match) {
  20932. break;
  20933. }
  20934. scan_end1 = _win[scan + best_len - 1];
  20935. scan_end = _win[scan + best_len];
  20936. }
  20937. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20938. if (best_len <= s.lookahead) {
  20939. return best_len;
  20940. }
  20941. return s.lookahead;
  20942. }
  20943. /* ===========================================================================
  20944. * Fill the window when the lookahead becomes insufficient.
  20945. * Updates strstart and lookahead.
  20946. *
  20947. * IN assertion: lookahead < MIN_LOOKAHEAD
  20948. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20949. * At least one byte has been read, or avail_in == 0; reads are
  20950. * performed for at least two bytes (required for the zip translate_eol
  20951. * option -- not supported here).
  20952. */
  20953. function fill_window(s) {
  20954. var _w_size = s.w_size;
  20955. var p, n, m, more, str;
  20956. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20957. do {
  20958. more = s.window_size - s.lookahead - s.strstart;
  20959. // JS ints have 32 bit, block below not needed
  20960. /* Deal with !@#$% 64K limit: */
  20961. //if (sizeof(int) <= 2) {
  20962. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20963. // more = wsize;
  20964. //
  20965. // } else if (more == (unsigned)(-1)) {
  20966. // /* Very unlikely, but possible on 16 bit machine if
  20967. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20968. // */
  20969. // more--;
  20970. // }
  20971. //}
  20972. /* If the window is almost full and there is insufficient lookahead,
  20973. * move the upper half to the lower one to make room in the upper half.
  20974. */
  20975. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20976. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20977. s.match_start -= _w_size;
  20978. s.strstart -= _w_size;
  20979. /* we now have strstart >= MAX_DIST */
  20980. s.block_start -= _w_size;
  20981. /* Slide the hash table (could be avoided with 32 bit values
  20982. at the expense of memory usage). We slide even when level == 0
  20983. to keep the hash table consistent if we switch back to level > 0
  20984. later. (Using level 0 permanently is not an optimal usage of
  20985. zlib, so we don't care about this pathological case.)
  20986. */
  20987. n = s.hash_size;
  20988. p = n;
  20989. do {
  20990. m = s.head[--p];
  20991. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20992. } while (--n);
  20993. n = _w_size;
  20994. p = n;
  20995. do {
  20996. m = s.prev[--p];
  20997. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20998. /* If n is not on any hash chain, prev[n] is garbage but
  20999. * its value will never be used.
  21000. */
  21001. } while (--n);
  21002. more += _w_size;
  21003. }
  21004. if (s.strm.avail_in === 0) {
  21005. break;
  21006. }
  21007. /* If there was no sliding:
  21008. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  21009. * more == window_size - lookahead - strstart
  21010. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  21011. * => more >= window_size - 2*WSIZE + 2
  21012. * In the BIG_MEM or MMAP case (not yet supported),
  21013. * window_size == input_size + MIN_LOOKAHEAD &&
  21014. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  21015. * Otherwise, window_size == 2*WSIZE so more >= 2.
  21016. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  21017. */
  21018. //Assert(more >= 2, "more < 2");
  21019. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  21020. s.lookahead += n;
  21021. /* Initialize the hash value now that we have some input: */
  21022. if (s.lookahead + s.insert >= MIN_MATCH) {
  21023. str = s.strstart - s.insert;
  21024. s.ins_h = s.window[str];
  21025. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  21026. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  21027. //#if MIN_MATCH != 3
  21028. // Call update_hash() MIN_MATCH-3 more times
  21029. //#endif
  21030. while (s.insert) {
  21031. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  21032. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  21033. s.prev[str & s.w_mask] = s.head[s.ins_h];
  21034. s.head[s.ins_h] = str;
  21035. str++;
  21036. s.insert--;
  21037. if (s.lookahead + s.insert < MIN_MATCH) {
  21038. break;
  21039. }
  21040. }
  21041. }
  21042. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  21043. * but this is not important since only literal bytes will be emitted.
  21044. */
  21045. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  21046. /* If the WIN_INIT bytes after the end of the current data have never been
  21047. * written, then zero those bytes in order to avoid memory check reports of
  21048. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  21049. * the longest match routines. Update the high water mark for the next
  21050. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  21051. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  21052. */
  21053. // if (s.high_water < s.window_size) {
  21054. // var curr = s.strstart + s.lookahead;
  21055. // var init = 0;
  21056. //
  21057. // if (s.high_water < curr) {
  21058. // /* Previous high water mark below current data -- zero WIN_INIT
  21059. // * bytes or up to end of window, whichever is less.
  21060. // */
  21061. // init = s.window_size - curr;
  21062. // if (init > WIN_INIT)
  21063. // init = WIN_INIT;
  21064. // zmemzero(s->window + curr, (unsigned)init);
  21065. // s->high_water = curr + init;
  21066. // }
  21067. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  21068. // /* High water mark at or above current data, but below current data
  21069. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  21070. // * to end of window, whichever is less.
  21071. // */
  21072. // init = (ulg)curr + WIN_INIT - s->high_water;
  21073. // if (init > s->window_size - s->high_water)
  21074. // init = s->window_size - s->high_water;
  21075. // zmemzero(s->window + s->high_water, (unsigned)init);
  21076. // s->high_water += init;
  21077. // }
  21078. // }
  21079. //
  21080. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  21081. // "not enough room for search");
  21082. }
  21083. /* ===========================================================================
  21084. * Copy without compression as much as possible from the input stream, return
  21085. * the current block state.
  21086. * This function does not insert new strings in the dictionary since
  21087. * uncompressible data is probably not useful. This function is used
  21088. * only for the level=0 compression option.
  21089. * NOTE: this function should be optimized to avoid extra copying from
  21090. * window to pending_buf.
  21091. */
  21092. function deflate_stored(s, flush) {
  21093. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  21094. * to pending_buf_size, and each stored block has a 5 byte header:
  21095. */
  21096. var max_block_size = 0xffff;
  21097. if (max_block_size > s.pending_buf_size - 5) {
  21098. max_block_size = s.pending_buf_size - 5;
  21099. }
  21100. /* Copy as much as possible from input to output: */
  21101. for (;;) {
  21102. /* Fill the window as much as possible: */
  21103. if (s.lookahead <= 1) {
  21104. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  21105. // s->block_start >= (long)s->w_size, "slide too late");
  21106. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  21107. // s.block_start >= s.w_size)) {
  21108. // throw new Error("slide too late");
  21109. // }
  21110. fill_window(s);
  21111. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  21112. return BS_NEED_MORE;
  21113. }
  21114. if (s.lookahead === 0) {
  21115. break;
  21116. }
  21117. /* flush the current block */
  21118. }
  21119. //Assert(s->block_start >= 0L, "block gone");
  21120. // if (s.block_start < 0) throw new Error("block gone");
  21121. s.strstart += s.lookahead;
  21122. s.lookahead = 0;
  21123. /* Emit a stored block if pending_buf will be full: */
  21124. var max_start = s.block_start + max_block_size;
  21125. if (s.strstart === 0 || s.strstart >= max_start) {
  21126. /* strstart == 0 is possible when wraparound on 16-bit machine */
  21127. s.lookahead = s.strstart - max_start;
  21128. s.strstart = max_start;
  21129. /*** FLUSH_BLOCK(s, 0); ***/
  21130. flush_block_only(s, false);
  21131. if (s.strm.avail_out === 0) {
  21132. return BS_NEED_MORE;
  21133. }
  21134. /***/
  21135. }
  21136. /* Flush if we may have to slide, otherwise block_start may become
  21137. * negative and the data will be gone:
  21138. */
  21139. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  21140. /*** FLUSH_BLOCK(s, 0); ***/
  21141. flush_block_only(s, false);
  21142. if (s.strm.avail_out === 0) {
  21143. return BS_NEED_MORE;
  21144. }
  21145. /***/
  21146. }
  21147. }
  21148. s.insert = 0;
  21149. if (flush === Z_FINISH) {
  21150. /*** FLUSH_BLOCK(s, 1); ***/
  21151. flush_block_only(s, true);
  21152. if (s.strm.avail_out === 0) {
  21153. return BS_FINISH_STARTED;
  21154. }
  21155. /***/
  21156. return BS_FINISH_DONE;
  21157. }
  21158. if (s.strstart > s.block_start) {
  21159. /*** FLUSH_BLOCK(s, 0); ***/
  21160. flush_block_only(s, false);
  21161. if (s.strm.avail_out === 0) {
  21162. return BS_NEED_MORE;
  21163. }
  21164. /***/
  21165. }
  21166. return BS_NEED_MORE;
  21167. }
  21168. /* ===========================================================================
  21169. * Compress as much as possible from the input stream, return the current
  21170. * block state.
  21171. * This function does not perform lazy evaluation of matches and inserts
  21172. * new strings in the dictionary only for unmatched strings or for short
  21173. * matches. It is used only for the fast compression options.
  21174. */
  21175. function deflate_fast(s, flush) {
  21176. var hash_head; /* head of the hash chain */
  21177. var bflush; /* set if current block must be flushed */
  21178. for (;;) {
  21179. /* Make sure that we always have enough lookahead, except
  21180. * at the end of the input file. We need MAX_MATCH bytes
  21181. * for the next match, plus MIN_MATCH bytes to insert the
  21182. * string following the next match.
  21183. */
  21184. if (s.lookahead < MIN_LOOKAHEAD) {
  21185. fill_window(s);
  21186. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21187. return BS_NEED_MORE;
  21188. }
  21189. if (s.lookahead === 0) {
  21190. break; /* flush the current block */
  21191. }
  21192. }
  21193. /* Insert the string window[strstart .. strstart+2] in the
  21194. * dictionary, and set hash_head to the head of the hash chain:
  21195. */
  21196. hash_head = 0/*NIL*/;
  21197. if (s.lookahead >= MIN_MATCH) {
  21198. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21199. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21200. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21201. s.head[s.ins_h] = s.strstart;
  21202. /***/
  21203. }
  21204. /* Find the longest match, discarding those <= prev_length.
  21205. * At this point we have always match_length < MIN_MATCH
  21206. */
  21207. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  21208. /* To simplify the code, we prevent matches with the string
  21209. * of window index 0 (in particular we have to avoid a match
  21210. * of the string with itself at the start of the input file).
  21211. */
  21212. s.match_length = longest_match(s, hash_head);
  21213. /* longest_match() sets match_start */
  21214. }
  21215. if (s.match_length >= MIN_MATCH) {
  21216. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  21217. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  21218. s.match_length - MIN_MATCH, bflush); ***/
  21219. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  21220. s.lookahead -= s.match_length;
  21221. /* Insert new strings in the hash table only if the match length
  21222. * is not too large. This saves time but degrades compression.
  21223. */
  21224. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  21225. s.match_length--; /* string at strstart already in table */
  21226. do {
  21227. s.strstart++;
  21228. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21229. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21230. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21231. s.head[s.ins_h] = s.strstart;
  21232. /***/
  21233. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21234. * always MIN_MATCH bytes ahead.
  21235. */
  21236. } while (--s.match_length !== 0);
  21237. s.strstart++;
  21238. } else
  21239. {
  21240. s.strstart += s.match_length;
  21241. s.match_length = 0;
  21242. s.ins_h = s.window[s.strstart];
  21243. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21244. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21245. //#if MIN_MATCH != 3
  21246. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21247. //#endif
  21248. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21249. * matter since it will be recomputed at next deflate call.
  21250. */
  21251. }
  21252. } else {
  21253. /* No match, output a literal byte */
  21254. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21255. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21256. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21257. s.lookahead--;
  21258. s.strstart++;
  21259. }
  21260. if (bflush) {
  21261. /*** FLUSH_BLOCK(s, 0); ***/
  21262. flush_block_only(s, false);
  21263. if (s.strm.avail_out === 0) {
  21264. return BS_NEED_MORE;
  21265. }
  21266. /***/
  21267. }
  21268. }
  21269. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21270. if (flush === Z_FINISH) {
  21271. /*** FLUSH_BLOCK(s, 1); ***/
  21272. flush_block_only(s, true);
  21273. if (s.strm.avail_out === 0) {
  21274. return BS_FINISH_STARTED;
  21275. }
  21276. /***/
  21277. return BS_FINISH_DONE;
  21278. }
  21279. if (s.last_lit) {
  21280. /*** FLUSH_BLOCK(s, 0); ***/
  21281. flush_block_only(s, false);
  21282. if (s.strm.avail_out === 0) {
  21283. return BS_NEED_MORE;
  21284. }
  21285. /***/
  21286. }
  21287. return BS_BLOCK_DONE;
  21288. }
  21289. /* ===========================================================================
  21290. * Same as above, but achieves better compression. We use a lazy
  21291. * evaluation for matches: a match is finally adopted only if there is
  21292. * no better match at the next window position.
  21293. */
  21294. function deflate_slow(s, flush) {
  21295. var hash_head; /* head of hash chain */
  21296. var bflush; /* set if current block must be flushed */
  21297. var max_insert;
  21298. /* Process the input block. */
  21299. for (;;) {
  21300. /* Make sure that we always have enough lookahead, except
  21301. * at the end of the input file. We need MAX_MATCH bytes
  21302. * for the next match, plus MIN_MATCH bytes to insert the
  21303. * string following the next match.
  21304. */
  21305. if (s.lookahead < MIN_LOOKAHEAD) {
  21306. fill_window(s);
  21307. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21308. return BS_NEED_MORE;
  21309. }
  21310. if (s.lookahead === 0) { break; } /* flush the current block */
  21311. }
  21312. /* Insert the string window[strstart .. strstart+2] in the
  21313. * dictionary, and set hash_head to the head of the hash chain:
  21314. */
  21315. hash_head = 0/*NIL*/;
  21316. if (s.lookahead >= MIN_MATCH) {
  21317. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21318. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21319. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21320. s.head[s.ins_h] = s.strstart;
  21321. /***/
  21322. }
  21323. /* Find the longest match, discarding those <= prev_length.
  21324. */
  21325. s.prev_length = s.match_length;
  21326. s.prev_match = s.match_start;
  21327. s.match_length = MIN_MATCH-1;
  21328. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21329. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21330. /* To simplify the code, we prevent matches with the string
  21331. * of window index 0 (in particular we have to avoid a match
  21332. * of the string with itself at the start of the input file).
  21333. */
  21334. s.match_length = longest_match(s, hash_head);
  21335. /* longest_match() sets match_start */
  21336. if (s.match_length <= 5 &&
  21337. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21338. /* If prev_match is also MIN_MATCH, match_start is garbage
  21339. * but we will ignore the current match anyway.
  21340. */
  21341. s.match_length = MIN_MATCH-1;
  21342. }
  21343. }
  21344. /* If there was a match at the previous step and the current
  21345. * match is not better, output the previous match:
  21346. */
  21347. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21348. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21349. /* Do not insert strings in hash table beyond this. */
  21350. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21351. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21352. s.prev_length - MIN_MATCH, bflush);***/
  21353. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21354. /* Insert in hash table all strings up to the end of the match.
  21355. * strstart-1 and strstart are already inserted. If there is not
  21356. * enough lookahead, the last two strings are not inserted in
  21357. * the hash table.
  21358. */
  21359. s.lookahead -= s.prev_length-1;
  21360. s.prev_length -= 2;
  21361. do {
  21362. if (++s.strstart <= max_insert) {
  21363. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21364. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21365. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21366. s.head[s.ins_h] = s.strstart;
  21367. /***/
  21368. }
  21369. } while (--s.prev_length !== 0);
  21370. s.match_available = 0;
  21371. s.match_length = MIN_MATCH-1;
  21372. s.strstart++;
  21373. if (bflush) {
  21374. /*** FLUSH_BLOCK(s, 0); ***/
  21375. flush_block_only(s, false);
  21376. if (s.strm.avail_out === 0) {
  21377. return BS_NEED_MORE;
  21378. }
  21379. /***/
  21380. }
  21381. } else if (s.match_available) {
  21382. /* If there was no match at the previous position, output a
  21383. * single literal. If there was a match but the current match
  21384. * is longer, truncate the previous match to a single literal.
  21385. */
  21386. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21387. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21388. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21389. if (bflush) {
  21390. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21391. flush_block_only(s, false);
  21392. /***/
  21393. }
  21394. s.strstart++;
  21395. s.lookahead--;
  21396. if (s.strm.avail_out === 0) {
  21397. return BS_NEED_MORE;
  21398. }
  21399. } else {
  21400. /* There is no previous match to compare with, wait for
  21401. * the next step to decide.
  21402. */
  21403. s.match_available = 1;
  21404. s.strstart++;
  21405. s.lookahead--;
  21406. }
  21407. }
  21408. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21409. if (s.match_available) {
  21410. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21411. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21412. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21413. s.match_available = 0;
  21414. }
  21415. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21416. if (flush === Z_FINISH) {
  21417. /*** FLUSH_BLOCK(s, 1); ***/
  21418. flush_block_only(s, true);
  21419. if (s.strm.avail_out === 0) {
  21420. return BS_FINISH_STARTED;
  21421. }
  21422. /***/
  21423. return BS_FINISH_DONE;
  21424. }
  21425. if (s.last_lit) {
  21426. /*** FLUSH_BLOCK(s, 0); ***/
  21427. flush_block_only(s, false);
  21428. if (s.strm.avail_out === 0) {
  21429. return BS_NEED_MORE;
  21430. }
  21431. /***/
  21432. }
  21433. return BS_BLOCK_DONE;
  21434. }
  21435. /* ===========================================================================
  21436. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21437. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21438. * deflate switches away from Z_RLE.)
  21439. */
  21440. function deflate_rle(s, flush) {
  21441. var bflush; /* set if current block must be flushed */
  21442. var prev; /* byte at distance one to match */
  21443. var scan, strend; /* scan goes up to strend for length of run */
  21444. var _win = s.window;
  21445. for (;;) {
  21446. /* Make sure that we always have enough lookahead, except
  21447. * at the end of the input file. We need MAX_MATCH bytes
  21448. * for the longest run, plus one for the unrolled loop.
  21449. */
  21450. if (s.lookahead <= MAX_MATCH) {
  21451. fill_window(s);
  21452. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21453. return BS_NEED_MORE;
  21454. }
  21455. if (s.lookahead === 0) { break; } /* flush the current block */
  21456. }
  21457. /* See how many times the previous byte repeats */
  21458. s.match_length = 0;
  21459. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21460. scan = s.strstart - 1;
  21461. prev = _win[scan];
  21462. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21463. strend = s.strstart + MAX_MATCH;
  21464. do {
  21465. /*jshint noempty:false*/
  21466. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21467. prev === _win[++scan] && prev === _win[++scan] &&
  21468. prev === _win[++scan] && prev === _win[++scan] &&
  21469. prev === _win[++scan] && prev === _win[++scan] &&
  21470. scan < strend);
  21471. s.match_length = MAX_MATCH - (strend - scan);
  21472. if (s.match_length > s.lookahead) {
  21473. s.match_length = s.lookahead;
  21474. }
  21475. }
  21476. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21477. }
  21478. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21479. if (s.match_length >= MIN_MATCH) {
  21480. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21481. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21482. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21483. s.lookahead -= s.match_length;
  21484. s.strstart += s.match_length;
  21485. s.match_length = 0;
  21486. } else {
  21487. /* No match, output a literal byte */
  21488. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21489. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21490. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21491. s.lookahead--;
  21492. s.strstart++;
  21493. }
  21494. if (bflush) {
  21495. /*** FLUSH_BLOCK(s, 0); ***/
  21496. flush_block_only(s, false);
  21497. if (s.strm.avail_out === 0) {
  21498. return BS_NEED_MORE;
  21499. }
  21500. /***/
  21501. }
  21502. }
  21503. s.insert = 0;
  21504. if (flush === Z_FINISH) {
  21505. /*** FLUSH_BLOCK(s, 1); ***/
  21506. flush_block_only(s, true);
  21507. if (s.strm.avail_out === 0) {
  21508. return BS_FINISH_STARTED;
  21509. }
  21510. /***/
  21511. return BS_FINISH_DONE;
  21512. }
  21513. if (s.last_lit) {
  21514. /*** FLUSH_BLOCK(s, 0); ***/
  21515. flush_block_only(s, false);
  21516. if (s.strm.avail_out === 0) {
  21517. return BS_NEED_MORE;
  21518. }
  21519. /***/
  21520. }
  21521. return BS_BLOCK_DONE;
  21522. }
  21523. /* ===========================================================================
  21524. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21525. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21526. */
  21527. function deflate_huff(s, flush) {
  21528. var bflush; /* set if current block must be flushed */
  21529. for (;;) {
  21530. /* Make sure that we have a literal to write. */
  21531. if (s.lookahead === 0) {
  21532. fill_window(s);
  21533. if (s.lookahead === 0) {
  21534. if (flush === Z_NO_FLUSH) {
  21535. return BS_NEED_MORE;
  21536. }
  21537. break; /* flush the current block */
  21538. }
  21539. }
  21540. /* Output a literal byte */
  21541. s.match_length = 0;
  21542. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21543. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21544. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21545. s.lookahead--;
  21546. s.strstart++;
  21547. if (bflush) {
  21548. /*** FLUSH_BLOCK(s, 0); ***/
  21549. flush_block_only(s, false);
  21550. if (s.strm.avail_out === 0) {
  21551. return BS_NEED_MORE;
  21552. }
  21553. /***/
  21554. }
  21555. }
  21556. s.insert = 0;
  21557. if (flush === Z_FINISH) {
  21558. /*** FLUSH_BLOCK(s, 1); ***/
  21559. flush_block_only(s, true);
  21560. if (s.strm.avail_out === 0) {
  21561. return BS_FINISH_STARTED;
  21562. }
  21563. /***/
  21564. return BS_FINISH_DONE;
  21565. }
  21566. if (s.last_lit) {
  21567. /*** FLUSH_BLOCK(s, 0); ***/
  21568. flush_block_only(s, false);
  21569. if (s.strm.avail_out === 0) {
  21570. return BS_NEED_MORE;
  21571. }
  21572. /***/
  21573. }
  21574. return BS_BLOCK_DONE;
  21575. }
  21576. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21577. * the desired pack level (0..9). The values given below have been tuned to
  21578. * exclude worst case performance for pathological files. Better values may be
  21579. * found for specific files.
  21580. */
  21581. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21582. this.good_length = good_length;
  21583. this.max_lazy = max_lazy;
  21584. this.nice_length = nice_length;
  21585. this.max_chain = max_chain;
  21586. this.func = func;
  21587. };
  21588. var configuration_table;
  21589. configuration_table = [
  21590. /* good lazy nice chain */
  21591. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21592. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21593. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21594. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21595. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21596. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21597. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21598. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21599. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21600. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21601. ];
  21602. /* ===========================================================================
  21603. * Initialize the "longest match" routines for a new zlib stream
  21604. */
  21605. function lm_init(s) {
  21606. s.window_size = 2 * s.w_size;
  21607. /*** CLEAR_HASH(s); ***/
  21608. zero(s.head); // Fill with NIL (= 0);
  21609. /* Set the default configuration parameters:
  21610. */
  21611. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21612. s.good_match = configuration_table[s.level].good_length;
  21613. s.nice_match = configuration_table[s.level].nice_length;
  21614. s.max_chain_length = configuration_table[s.level].max_chain;
  21615. s.strstart = 0;
  21616. s.block_start = 0;
  21617. s.lookahead = 0;
  21618. s.insert = 0;
  21619. s.match_length = s.prev_length = MIN_MATCH - 1;
  21620. s.match_available = 0;
  21621. s.ins_h = 0;
  21622. }
  21623. function DeflateState() {
  21624. this.strm = null; /* pointer back to this zlib stream */
  21625. this.status = 0; /* as the name implies */
  21626. this.pending_buf = null; /* output still pending */
  21627. this.pending_buf_size = 0; /* size of pending_buf */
  21628. this.pending_out = 0; /* next pending byte to output to the stream */
  21629. this.pending = 0; /* nb of bytes in the pending buffer */
  21630. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21631. this.gzhead = null; /* gzip header information to write */
  21632. this.gzindex = 0; /* where in extra, name, or comment */
  21633. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21634. this.last_flush = -1; /* value of flush param for previous deflate call */
  21635. this.w_size = 0; /* LZ77 window size (32K by default) */
  21636. this.w_bits = 0; /* log2(w_size) (8..16) */
  21637. this.w_mask = 0; /* w_size - 1 */
  21638. this.window = null;
  21639. /* Sliding window. Input bytes are read into the second half of the window,
  21640. * and move to the first half later to keep a dictionary of at least wSize
  21641. * bytes. With this organization, matches are limited to a distance of
  21642. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21643. * performed with a length multiple of the block size.
  21644. */
  21645. this.window_size = 0;
  21646. /* Actual size of window: 2*wSize, except when the user input buffer
  21647. * is directly used as sliding window.
  21648. */
  21649. this.prev = null;
  21650. /* Link to older string with same hash index. To limit the size of this
  21651. * array to 64K, this link is maintained only for the last 32K strings.
  21652. * An index in this array is thus a window index modulo 32K.
  21653. */
  21654. this.head = null; /* Heads of the hash chains or NIL. */
  21655. this.ins_h = 0; /* hash index of string to be inserted */
  21656. this.hash_size = 0; /* number of elements in hash table */
  21657. this.hash_bits = 0; /* log2(hash_size) */
  21658. this.hash_mask = 0; /* hash_size-1 */
  21659. this.hash_shift = 0;
  21660. /* Number of bits by which ins_h must be shifted at each input
  21661. * step. It must be such that after MIN_MATCH steps, the oldest
  21662. * byte no longer takes part in the hash key, that is:
  21663. * hash_shift * MIN_MATCH >= hash_bits
  21664. */
  21665. this.block_start = 0;
  21666. /* Window position at the beginning of the current output block. Gets
  21667. * negative when the window is moved backwards.
  21668. */
  21669. this.match_length = 0; /* length of best match */
  21670. this.prev_match = 0; /* previous match */
  21671. this.match_available = 0; /* set if previous match exists */
  21672. this.strstart = 0; /* start of string to insert */
  21673. this.match_start = 0; /* start of matching string */
  21674. this.lookahead = 0; /* number of valid bytes ahead in window */
  21675. this.prev_length = 0;
  21676. /* Length of the best match at previous step. Matches not greater than this
  21677. * are discarded. This is used in the lazy match evaluation.
  21678. */
  21679. this.max_chain_length = 0;
  21680. /* To speed up deflation, hash chains are never searched beyond this
  21681. * length. A higher limit improves compression ratio but degrades the
  21682. * speed.
  21683. */
  21684. this.max_lazy_match = 0;
  21685. /* Attempt to find a better match only when the current match is strictly
  21686. * smaller than this value. This mechanism is used only for compression
  21687. * levels >= 4.
  21688. */
  21689. // That's alias to max_lazy_match, don't use directly
  21690. //this.max_insert_length = 0;
  21691. /* Insert new strings in the hash table only if the match length is not
  21692. * greater than this length. This saves time but degrades compression.
  21693. * max_insert_length is used only for compression levels <= 3.
  21694. */
  21695. this.level = 0; /* compression level (1..9) */
  21696. this.strategy = 0; /* favor or force Huffman coding*/
  21697. this.good_match = 0;
  21698. /* Use a faster search when the previous match is longer than this */
  21699. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21700. /* used by trees.c: */
  21701. /* Didn't use ct_data typedef below to suppress compiler warning */
  21702. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21703. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21704. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21705. // Use flat array of DOUBLE size, with interleaved fata,
  21706. // because JS does not support effective
  21707. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21708. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21709. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21710. zero(this.dyn_ltree);
  21711. zero(this.dyn_dtree);
  21712. zero(this.bl_tree);
  21713. this.l_desc = null; /* desc. for literal tree */
  21714. this.d_desc = null; /* desc. for distance tree */
  21715. this.bl_desc = null; /* desc. for bit length tree */
  21716. //ush bl_count[MAX_BITS+1];
  21717. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21718. /* number of codes at each bit length for an optimal tree */
  21719. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21720. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21721. zero(this.heap);
  21722. this.heap_len = 0; /* number of elements in the heap */
  21723. this.heap_max = 0; /* element of largest frequency */
  21724. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21725. * The same heap array is used to build all trees.
  21726. */
  21727. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21728. zero(this.depth);
  21729. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21730. */
  21731. this.l_buf = 0; /* buffer index for literals or lengths */
  21732. this.lit_bufsize = 0;
  21733. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21734. * limiting lit_bufsize to 64K:
  21735. * - frequencies can be kept in 16 bit counters
  21736. * - if compression is not successful for the first block, all input
  21737. * data is still in the window so we can still emit a stored block even
  21738. * when input comes from standard input. (This can also be done for
  21739. * all blocks if lit_bufsize is not greater than 32K.)
  21740. * - if compression is not successful for a file smaller than 64K, we can
  21741. * even emit a stored file instead of a stored block (saving 5 bytes).
  21742. * This is applicable only for zip (not gzip or zlib).
  21743. * - creating new Huffman trees less frequently may not provide fast
  21744. * adaptation to changes in the input data statistics. (Take for
  21745. * example a binary file with poorly compressible code followed by
  21746. * a highly compressible string table.) Smaller buffer sizes give
  21747. * fast adaptation but have of course the overhead of transmitting
  21748. * trees more frequently.
  21749. * - I can't count above 4
  21750. */
  21751. this.last_lit = 0; /* running index in l_buf */
  21752. this.d_buf = 0;
  21753. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21754. * the same number of elements. To use different lengths, an extra flag
  21755. * array would be necessary.
  21756. */
  21757. this.opt_len = 0; /* bit length of current block with optimal trees */
  21758. this.static_len = 0; /* bit length of current block with static trees */
  21759. this.matches = 0; /* number of string matches in current block */
  21760. this.insert = 0; /* bytes at end of window left to insert */
  21761. this.bi_buf = 0;
  21762. /* Output buffer. bits are inserted starting at the bottom (least
  21763. * significant bits).
  21764. */
  21765. this.bi_valid = 0;
  21766. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21767. * are always zero.
  21768. */
  21769. // Used for window memory init. We safely ignore it for JS. That makes
  21770. // sense only for pointers and memory check tools.
  21771. //this.high_water = 0;
  21772. /* High water mark offset in window for initialized bytes -- bytes above
  21773. * this are set to zero in order to avoid memory check warnings when
  21774. * longest match routines access bytes past the input. This is then
  21775. * updated to the new high water mark.
  21776. */
  21777. }
  21778. function deflateResetKeep(strm) {
  21779. var s;
  21780. if (!strm || !strm.state) {
  21781. return err(strm, Z_STREAM_ERROR);
  21782. }
  21783. strm.total_in = strm.total_out = 0;
  21784. strm.data_type = Z_UNKNOWN;
  21785. s = strm.state;
  21786. s.pending = 0;
  21787. s.pending_out = 0;
  21788. if (s.wrap < 0) {
  21789. s.wrap = -s.wrap;
  21790. /* was made negative by deflate(..., Z_FINISH); */
  21791. }
  21792. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21793. strm.adler = (s.wrap === 2) ?
  21794. 0 // crc32(0, Z_NULL, 0)
  21795. :
  21796. 1; // adler32(0, Z_NULL, 0)
  21797. s.last_flush = Z_NO_FLUSH;
  21798. trees._tr_init(s);
  21799. return Z_OK;
  21800. }
  21801. function deflateReset(strm) {
  21802. var ret = deflateResetKeep(strm);
  21803. if (ret === Z_OK) {
  21804. lm_init(strm.state);
  21805. }
  21806. return ret;
  21807. }
  21808. function deflateSetHeader(strm, head) {
  21809. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21810. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21811. strm.state.gzhead = head;
  21812. return Z_OK;
  21813. }
  21814. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21815. if (!strm) { // === Z_NULL
  21816. return Z_STREAM_ERROR;
  21817. }
  21818. var wrap = 1;
  21819. if (level === Z_DEFAULT_COMPRESSION) {
  21820. level = 6;
  21821. }
  21822. if (windowBits < 0) { /* suppress zlib wrapper */
  21823. wrap = 0;
  21824. windowBits = -windowBits;
  21825. }
  21826. else if (windowBits > 15) {
  21827. wrap = 2; /* write gzip wrapper instead */
  21828. windowBits -= 16;
  21829. }
  21830. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21831. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21832. strategy < 0 || strategy > Z_FIXED) {
  21833. return err(strm, Z_STREAM_ERROR);
  21834. }
  21835. if (windowBits === 8) {
  21836. windowBits = 9;
  21837. }
  21838. /* until 256-byte window bug fixed */
  21839. var s = new DeflateState();
  21840. strm.state = s;
  21841. s.strm = strm;
  21842. s.wrap = wrap;
  21843. s.gzhead = null;
  21844. s.w_bits = windowBits;
  21845. s.w_size = 1 << s.w_bits;
  21846. s.w_mask = s.w_size - 1;
  21847. s.hash_bits = memLevel + 7;
  21848. s.hash_size = 1 << s.hash_bits;
  21849. s.hash_mask = s.hash_size - 1;
  21850. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21851. s.window = new utils.Buf8(s.w_size * 2);
  21852. s.head = new utils.Buf16(s.hash_size);
  21853. s.prev = new utils.Buf16(s.w_size);
  21854. // Don't need mem init magic for JS.
  21855. //s.high_water = 0; /* nothing written to s->window yet */
  21856. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21857. s.pending_buf_size = s.lit_bufsize * 4;
  21858. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21859. s.d_buf = s.lit_bufsize >> 1;
  21860. s.l_buf = (1 + 2) * s.lit_bufsize;
  21861. s.level = level;
  21862. s.strategy = strategy;
  21863. s.method = method;
  21864. return deflateReset(strm);
  21865. }
  21866. function deflateInit(strm, level) {
  21867. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21868. }
  21869. function deflate(strm, flush) {
  21870. var old_flush, s;
  21871. var beg, val; // for gzip header write only
  21872. if (!strm || !strm.state ||
  21873. flush > Z_BLOCK || flush < 0) {
  21874. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21875. }
  21876. s = strm.state;
  21877. if (!strm.output ||
  21878. (!strm.input && strm.avail_in !== 0) ||
  21879. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21880. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21881. }
  21882. s.strm = strm; /* just in case */
  21883. old_flush = s.last_flush;
  21884. s.last_flush = flush;
  21885. /* Write the header */
  21886. if (s.status === INIT_STATE) {
  21887. if (s.wrap === 2) { // GZIP header
  21888. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21889. put_byte(s, 31);
  21890. put_byte(s, 139);
  21891. put_byte(s, 8);
  21892. if (!s.gzhead) { // s->gzhead == Z_NULL
  21893. put_byte(s, 0);
  21894. put_byte(s, 0);
  21895. put_byte(s, 0);
  21896. put_byte(s, 0);
  21897. put_byte(s, 0);
  21898. put_byte(s, s.level === 9 ? 2 :
  21899. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21900. 4 : 0));
  21901. put_byte(s, OS_CODE);
  21902. s.status = BUSY_STATE;
  21903. }
  21904. else {
  21905. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21906. (s.gzhead.hcrc ? 2 : 0) +
  21907. (!s.gzhead.extra ? 0 : 4) +
  21908. (!s.gzhead.name ? 0 : 8) +
  21909. (!s.gzhead.comment ? 0 : 16)
  21910. );
  21911. put_byte(s, s.gzhead.time & 0xff);
  21912. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21913. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21914. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21915. put_byte(s, s.level === 9 ? 2 :
  21916. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21917. 4 : 0));
  21918. put_byte(s, s.gzhead.os & 0xff);
  21919. if (s.gzhead.extra && s.gzhead.extra.length) {
  21920. put_byte(s, s.gzhead.extra.length & 0xff);
  21921. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21922. }
  21923. if (s.gzhead.hcrc) {
  21924. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21925. }
  21926. s.gzindex = 0;
  21927. s.status = EXTRA_STATE;
  21928. }
  21929. }
  21930. else // DEFLATE header
  21931. {
  21932. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21933. var level_flags = -1;
  21934. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21935. level_flags = 0;
  21936. } else if (s.level < 6) {
  21937. level_flags = 1;
  21938. } else if (s.level === 6) {
  21939. level_flags = 2;
  21940. } else {
  21941. level_flags = 3;
  21942. }
  21943. header |= (level_flags << 6);
  21944. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21945. header += 31 - (header % 31);
  21946. s.status = BUSY_STATE;
  21947. putShortMSB(s, header);
  21948. /* Save the adler32 of the preset dictionary: */
  21949. if (s.strstart !== 0) {
  21950. putShortMSB(s, strm.adler >>> 16);
  21951. putShortMSB(s, strm.adler & 0xffff);
  21952. }
  21953. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21954. }
  21955. }
  21956. //#ifdef GZIP
  21957. if (s.status === EXTRA_STATE) {
  21958. if (s.gzhead.extra/* != Z_NULL*/) {
  21959. beg = s.pending; /* start of bytes to update crc */
  21960. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21961. if (s.pending === s.pending_buf_size) {
  21962. if (s.gzhead.hcrc && s.pending > beg) {
  21963. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21964. }
  21965. flush_pending(strm);
  21966. beg = s.pending;
  21967. if (s.pending === s.pending_buf_size) {
  21968. break;
  21969. }
  21970. }
  21971. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21972. s.gzindex++;
  21973. }
  21974. if (s.gzhead.hcrc && s.pending > beg) {
  21975. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21976. }
  21977. if (s.gzindex === s.gzhead.extra.length) {
  21978. s.gzindex = 0;
  21979. s.status = NAME_STATE;
  21980. }
  21981. }
  21982. else {
  21983. s.status = NAME_STATE;
  21984. }
  21985. }
  21986. if (s.status === NAME_STATE) {
  21987. if (s.gzhead.name/* != Z_NULL*/) {
  21988. beg = s.pending; /* start of bytes to update crc */
  21989. //int val;
  21990. do {
  21991. if (s.pending === s.pending_buf_size) {
  21992. if (s.gzhead.hcrc && s.pending > beg) {
  21993. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21994. }
  21995. flush_pending(strm);
  21996. beg = s.pending;
  21997. if (s.pending === s.pending_buf_size) {
  21998. val = 1;
  21999. break;
  22000. }
  22001. }
  22002. // JS specific: little magic to add zero terminator to end of string
  22003. if (s.gzindex < s.gzhead.name.length) {
  22004. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  22005. } else {
  22006. val = 0;
  22007. }
  22008. put_byte(s, val);
  22009. } while (val !== 0);
  22010. if (s.gzhead.hcrc && s.pending > beg) {
  22011. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22012. }
  22013. if (val === 0) {
  22014. s.gzindex = 0;
  22015. s.status = COMMENT_STATE;
  22016. }
  22017. }
  22018. else {
  22019. s.status = COMMENT_STATE;
  22020. }
  22021. }
  22022. if (s.status === COMMENT_STATE) {
  22023. if (s.gzhead.comment/* != Z_NULL*/) {
  22024. beg = s.pending; /* start of bytes to update crc */
  22025. //int val;
  22026. do {
  22027. if (s.pending === s.pending_buf_size) {
  22028. if (s.gzhead.hcrc && s.pending > beg) {
  22029. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22030. }
  22031. flush_pending(strm);
  22032. beg = s.pending;
  22033. if (s.pending === s.pending_buf_size) {
  22034. val = 1;
  22035. break;
  22036. }
  22037. }
  22038. // JS specific: little magic to add zero terminator to end of string
  22039. if (s.gzindex < s.gzhead.comment.length) {
  22040. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  22041. } else {
  22042. val = 0;
  22043. }
  22044. put_byte(s, val);
  22045. } while (val !== 0);
  22046. if (s.gzhead.hcrc && s.pending > beg) {
  22047. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22048. }
  22049. if (val === 0) {
  22050. s.status = HCRC_STATE;
  22051. }
  22052. }
  22053. else {
  22054. s.status = HCRC_STATE;
  22055. }
  22056. }
  22057. if (s.status === HCRC_STATE) {
  22058. if (s.gzhead.hcrc) {
  22059. if (s.pending + 2 > s.pending_buf_size) {
  22060. flush_pending(strm);
  22061. }
  22062. if (s.pending + 2 <= s.pending_buf_size) {
  22063. put_byte(s, strm.adler & 0xff);
  22064. put_byte(s, (strm.adler >> 8) & 0xff);
  22065. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22066. s.status = BUSY_STATE;
  22067. }
  22068. }
  22069. else {
  22070. s.status = BUSY_STATE;
  22071. }
  22072. }
  22073. //#endif
  22074. /* Flush as much pending output as possible */
  22075. if (s.pending !== 0) {
  22076. flush_pending(strm);
  22077. if (strm.avail_out === 0) {
  22078. /* Since avail_out is 0, deflate will be called again with
  22079. * more output space, but possibly with both pending and
  22080. * avail_in equal to zero. There won't be anything to do,
  22081. * but this is not an error situation so make sure we
  22082. * return OK instead of BUF_ERROR at next call of deflate:
  22083. */
  22084. s.last_flush = -1;
  22085. return Z_OK;
  22086. }
  22087. /* Make sure there is something to do and avoid duplicate consecutive
  22088. * flushes. For repeated and useless calls with Z_FINISH, we keep
  22089. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  22090. */
  22091. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  22092. flush !== Z_FINISH) {
  22093. return err(strm, Z_BUF_ERROR);
  22094. }
  22095. /* User must not provide more input after the first FINISH: */
  22096. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  22097. return err(strm, Z_BUF_ERROR);
  22098. }
  22099. /* Start a new block or continue the current one.
  22100. */
  22101. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  22102. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  22103. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  22104. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  22105. configuration_table[s.level].func(s, flush));
  22106. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  22107. s.status = FINISH_STATE;
  22108. }
  22109. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  22110. if (strm.avail_out === 0) {
  22111. s.last_flush = -1;
  22112. /* avoid BUF_ERROR next call, see above */
  22113. }
  22114. return Z_OK;
  22115. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  22116. * of deflate should use the same flush parameter to make sure
  22117. * that the flush is complete. So we don't have to output an
  22118. * empty block here, this will be done at next call. This also
  22119. * ensures that for a very small output buffer, we emit at most
  22120. * one empty block.
  22121. */
  22122. }
  22123. if (bstate === BS_BLOCK_DONE) {
  22124. if (flush === Z_PARTIAL_FLUSH) {
  22125. trees._tr_align(s);
  22126. }
  22127. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  22128. trees._tr_stored_block(s, 0, 0, false);
  22129. /* For a full flush, this empty block will be recognized
  22130. * as a special marker by inflate_sync().
  22131. */
  22132. if (flush === Z_FULL_FLUSH) {
  22133. /*** CLEAR_HASH(s); ***/ /* forget history */
  22134. zero(s.head); // Fill with NIL (= 0);
  22135. if (s.lookahead === 0) {
  22136. s.strstart = 0;
  22137. s.block_start = 0;
  22138. s.insert = 0;
  22139. }
  22140. }
  22141. }
  22142. flush_pending(strm);
  22143. if (strm.avail_out === 0) {
  22144. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  22145. return Z_OK;
  22146. }
  22147. }
  22148. }
  22149. //Assert(strm->avail_out > 0, "bug2");
  22150. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  22151. if (flush !== Z_FINISH) { return Z_OK; }
  22152. if (s.wrap <= 0) { return Z_STREAM_END; }
  22153. /* Write the trailer */
  22154. if (s.wrap === 2) {
  22155. put_byte(s, strm.adler & 0xff);
  22156. put_byte(s, (strm.adler >> 8) & 0xff);
  22157. put_byte(s, (strm.adler >> 16) & 0xff);
  22158. put_byte(s, (strm.adler >> 24) & 0xff);
  22159. put_byte(s, strm.total_in & 0xff);
  22160. put_byte(s, (strm.total_in >> 8) & 0xff);
  22161. put_byte(s, (strm.total_in >> 16) & 0xff);
  22162. put_byte(s, (strm.total_in >> 24) & 0xff);
  22163. }
  22164. else
  22165. {
  22166. putShortMSB(s, strm.adler >>> 16);
  22167. putShortMSB(s, strm.adler & 0xffff);
  22168. }
  22169. flush_pending(strm);
  22170. /* If avail_out is zero, the application will call deflate again
  22171. * to flush the rest.
  22172. */
  22173. if (s.wrap > 0) { s.wrap = -s.wrap; }
  22174. /* write the trailer only once! */
  22175. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  22176. }
  22177. function deflateEnd(strm) {
  22178. var status;
  22179. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  22180. return Z_STREAM_ERROR;
  22181. }
  22182. status = strm.state.status;
  22183. if (status !== INIT_STATE &&
  22184. status !== EXTRA_STATE &&
  22185. status !== NAME_STATE &&
  22186. status !== COMMENT_STATE &&
  22187. status !== HCRC_STATE &&
  22188. status !== BUSY_STATE &&
  22189. status !== FINISH_STATE
  22190. ) {
  22191. return err(strm, Z_STREAM_ERROR);
  22192. }
  22193. strm.state = null;
  22194. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  22195. }
  22196. /* =========================================================================
  22197. * Copy the source state to the destination state
  22198. */
  22199. //function deflateCopy(dest, source) {
  22200. //
  22201. //}
  22202. exports.deflateInit = deflateInit;
  22203. exports.deflateInit2 = deflateInit2;
  22204. exports.deflateReset = deflateReset;
  22205. exports.deflateResetKeep = deflateResetKeep;
  22206. exports.deflateSetHeader = deflateSetHeader;
  22207. exports.deflate = deflate;
  22208. exports.deflateEnd = deflateEnd;
  22209. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  22210. /* Not implemented
  22211. exports.deflateBound = deflateBound;
  22212. exports.deflateCopy = deflateCopy;
  22213. exports.deflateSetDictionary = deflateSetDictionary;
  22214. exports.deflateParams = deflateParams;
  22215. exports.deflatePending = deflatePending;
  22216. exports.deflatePrime = deflatePrime;
  22217. exports.deflateTune = deflateTune;
  22218. */
  22219. },{"../utils/common":75,"./adler32":77,"./crc32":79,"./messages":85,"./trees":86}],81:[function(require,module,exports){
  22220. 'use strict';
  22221. function GZheader() {
  22222. /* true if compressed data believed to be text */
  22223. this.text = 0;
  22224. /* modification time */
  22225. this.time = 0;
  22226. /* extra flags (not used when writing a gzip file) */
  22227. this.xflags = 0;
  22228. /* operating system */
  22229. this.os = 0;
  22230. /* pointer to extra field or Z_NULL if none */
  22231. this.extra = null;
  22232. /* extra field length (valid if extra != Z_NULL) */
  22233. this.extra_len = 0; // Actually, we don't need it in JS,
  22234. // but leave for few code modifications
  22235. //
  22236. // Setup limits is not necessary because in js we should not preallocate memory
  22237. // for inflate use constant limit in 65536 bytes
  22238. //
  22239. /* space at extra (only when reading header) */
  22240. // this.extra_max = 0;
  22241. /* pointer to zero-terminated file name or Z_NULL */
  22242. this.name = '';
  22243. /* space at name (only when reading header) */
  22244. // this.name_max = 0;
  22245. /* pointer to zero-terminated comment or Z_NULL */
  22246. this.comment = '';
  22247. /* space at comment (only when reading header) */
  22248. // this.comm_max = 0;
  22249. /* true if there was or will be a header crc */
  22250. this.hcrc = 0;
  22251. /* true when done reading gzip header (not used when writing a gzip file) */
  22252. this.done = false;
  22253. }
  22254. module.exports = GZheader;
  22255. },{}],82:[function(require,module,exports){
  22256. 'use strict';
  22257. // See state defs from inflate.js
  22258. var BAD = 30; /* got a data error -- remain here until reset */
  22259. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22260. /*
  22261. Decode literal, length, and distance codes and write out the resulting
  22262. literal and match bytes until either not enough input or output is
  22263. available, an end-of-block is encountered, or a data error is encountered.
  22264. When large enough input and output buffers are supplied to inflate(), for
  22265. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22266. inflate execution time is spent in this routine.
  22267. Entry assumptions:
  22268. state.mode === LEN
  22269. strm.avail_in >= 6
  22270. strm.avail_out >= 258
  22271. start >= strm.avail_out
  22272. state.bits < 8
  22273. On return, state.mode is one of:
  22274. LEN -- ran out of enough output space or enough available input
  22275. TYPE -- reached end of block code, inflate() to interpret next block
  22276. BAD -- error in block data
  22277. Notes:
  22278. - The maximum input bits used by a length/distance pair is 15 bits for the
  22279. length code, 5 bits for the length extra, 15 bits for the distance code,
  22280. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22281. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22282. checking for available input while decoding.
  22283. - The maximum bytes that a single length/distance pair can output is 258
  22284. bytes, which is the maximum length that can be coded. inflate_fast()
  22285. requires strm.avail_out >= 258 for each loop to avoid checking for
  22286. output space.
  22287. */
  22288. module.exports = function inflate_fast(strm, start) {
  22289. var state;
  22290. var _in; /* local strm.input */
  22291. var last; /* have enough input while in < last */
  22292. var _out; /* local strm.output */
  22293. var beg; /* inflate()'s initial strm.output */
  22294. var end; /* while out < end, enough space available */
  22295. //#ifdef INFLATE_STRICT
  22296. var dmax; /* maximum distance from zlib header */
  22297. //#endif
  22298. var wsize; /* window size or zero if not using window */
  22299. var whave; /* valid bytes in the window */
  22300. var wnext; /* window write index */
  22301. var window; /* allocated sliding window, if wsize != 0 */
  22302. var hold; /* local strm.hold */
  22303. var bits; /* local strm.bits */
  22304. var lcode; /* local strm.lencode */
  22305. var dcode; /* local strm.distcode */
  22306. var lmask; /* mask for first level of length codes */
  22307. var dmask; /* mask for first level of distance codes */
  22308. var here; /* retrieved table entry */
  22309. var op; /* code bits, operation, extra bits, or */
  22310. /* window position, window bytes to copy */
  22311. var len; /* match length, unused bytes */
  22312. var dist; /* match distance */
  22313. var from; /* where to copy match from */
  22314. var from_source;
  22315. var input, output; // JS specific, because we have no pointers
  22316. /* copy state to local variables */
  22317. state = strm.state;
  22318. //here = state.here;
  22319. _in = strm.next_in;
  22320. input = strm.input;
  22321. last = _in + (strm.avail_in - 5);
  22322. _out = strm.next_out;
  22323. output = strm.output;
  22324. beg = _out - (start - strm.avail_out);
  22325. end = _out + (strm.avail_out - 257);
  22326. //#ifdef INFLATE_STRICT
  22327. dmax = state.dmax;
  22328. //#endif
  22329. wsize = state.wsize;
  22330. whave = state.whave;
  22331. wnext = state.wnext;
  22332. window = state.window;
  22333. hold = state.hold;
  22334. bits = state.bits;
  22335. lcode = state.lencode;
  22336. dcode = state.distcode;
  22337. lmask = (1 << state.lenbits) - 1;
  22338. dmask = (1 << state.distbits) - 1;
  22339. /* decode literals and length/distances until end-of-block or not enough
  22340. input data or output space */
  22341. top:
  22342. do {
  22343. if (bits < 15) {
  22344. hold += input[_in++] << bits;
  22345. bits += 8;
  22346. hold += input[_in++] << bits;
  22347. bits += 8;
  22348. }
  22349. here = lcode[hold & lmask];
  22350. dolen:
  22351. for (;;) { // Goto emulation
  22352. op = here >>> 24/*here.bits*/;
  22353. hold >>>= op;
  22354. bits -= op;
  22355. op = (here >>> 16) & 0xff/*here.op*/;
  22356. if (op === 0) { /* literal */
  22357. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22358. // "inflate: literal '%c'\n" :
  22359. // "inflate: literal 0x%02x\n", here.val));
  22360. output[_out++] = here & 0xffff/*here.val*/;
  22361. }
  22362. else if (op & 16) { /* length base */
  22363. len = here & 0xffff/*here.val*/;
  22364. op &= 15; /* number of extra bits */
  22365. if (op) {
  22366. if (bits < op) {
  22367. hold += input[_in++] << bits;
  22368. bits += 8;
  22369. }
  22370. len += hold & ((1 << op) - 1);
  22371. hold >>>= op;
  22372. bits -= op;
  22373. }
  22374. //Tracevv((stderr, "inflate: length %u\n", len));
  22375. if (bits < 15) {
  22376. hold += input[_in++] << bits;
  22377. bits += 8;
  22378. hold += input[_in++] << bits;
  22379. bits += 8;
  22380. }
  22381. here = dcode[hold & dmask];
  22382. dodist:
  22383. for (;;) { // goto emulation
  22384. op = here >>> 24/*here.bits*/;
  22385. hold >>>= op;
  22386. bits -= op;
  22387. op = (here >>> 16) & 0xff/*here.op*/;
  22388. if (op & 16) { /* distance base */
  22389. dist = here & 0xffff/*here.val*/;
  22390. op &= 15; /* number of extra bits */
  22391. if (bits < op) {
  22392. hold += input[_in++] << bits;
  22393. bits += 8;
  22394. if (bits < op) {
  22395. hold += input[_in++] << bits;
  22396. bits += 8;
  22397. }
  22398. }
  22399. dist += hold & ((1 << op) - 1);
  22400. //#ifdef INFLATE_STRICT
  22401. if (dist > dmax) {
  22402. strm.msg = 'invalid distance too far back';
  22403. state.mode = BAD;
  22404. break top;
  22405. }
  22406. //#endif
  22407. hold >>>= op;
  22408. bits -= op;
  22409. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22410. op = _out - beg; /* max distance in output */
  22411. if (dist > op) { /* see if copy from window */
  22412. op = dist - op; /* distance back in window */
  22413. if (op > whave) {
  22414. if (state.sane) {
  22415. strm.msg = 'invalid distance too far back';
  22416. state.mode = BAD;
  22417. break top;
  22418. }
  22419. // (!) This block is disabled in zlib defailts,
  22420. // don't enable it for binary compatibility
  22421. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22422. // if (len <= op - whave) {
  22423. // do {
  22424. // output[_out++] = 0;
  22425. // } while (--len);
  22426. // continue top;
  22427. // }
  22428. // len -= op - whave;
  22429. // do {
  22430. // output[_out++] = 0;
  22431. // } while (--op > whave);
  22432. // if (op === 0) {
  22433. // from = _out - dist;
  22434. // do {
  22435. // output[_out++] = output[from++];
  22436. // } while (--len);
  22437. // continue top;
  22438. // }
  22439. //#endif
  22440. }
  22441. from = 0; // window index
  22442. from_source = window;
  22443. if (wnext === 0) { /* very common case */
  22444. from += wsize - op;
  22445. if (op < len) { /* some from window */
  22446. len -= op;
  22447. do {
  22448. output[_out++] = window[from++];
  22449. } while (--op);
  22450. from = _out - dist; /* rest from output */
  22451. from_source = output;
  22452. }
  22453. }
  22454. else if (wnext < op) { /* wrap around window */
  22455. from += wsize + wnext - op;
  22456. op -= wnext;
  22457. if (op < len) { /* some from end of window */
  22458. len -= op;
  22459. do {
  22460. output[_out++] = window[from++];
  22461. } while (--op);
  22462. from = 0;
  22463. if (wnext < len) { /* some from start of window */
  22464. op = wnext;
  22465. len -= op;
  22466. do {
  22467. output[_out++] = window[from++];
  22468. } while (--op);
  22469. from = _out - dist; /* rest from output */
  22470. from_source = output;
  22471. }
  22472. }
  22473. }
  22474. else { /* contiguous in window */
  22475. from += wnext - op;
  22476. if (op < len) { /* some from window */
  22477. len -= op;
  22478. do {
  22479. output[_out++] = window[from++];
  22480. } while (--op);
  22481. from = _out - dist; /* rest from output */
  22482. from_source = output;
  22483. }
  22484. }
  22485. while (len > 2) {
  22486. output[_out++] = from_source[from++];
  22487. output[_out++] = from_source[from++];
  22488. output[_out++] = from_source[from++];
  22489. len -= 3;
  22490. }
  22491. if (len) {
  22492. output[_out++] = from_source[from++];
  22493. if (len > 1) {
  22494. output[_out++] = from_source[from++];
  22495. }
  22496. }
  22497. }
  22498. else {
  22499. from = _out - dist; /* copy direct from output */
  22500. do { /* minimum length is three */
  22501. output[_out++] = output[from++];
  22502. output[_out++] = output[from++];
  22503. output[_out++] = output[from++];
  22504. len -= 3;
  22505. } while (len > 2);
  22506. if (len) {
  22507. output[_out++] = output[from++];
  22508. if (len > 1) {
  22509. output[_out++] = output[from++];
  22510. }
  22511. }
  22512. }
  22513. }
  22514. else if ((op & 64) === 0) { /* 2nd level distance code */
  22515. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22516. continue dodist;
  22517. }
  22518. else {
  22519. strm.msg = 'invalid distance code';
  22520. state.mode = BAD;
  22521. break top;
  22522. }
  22523. break; // need to emulate goto via "continue"
  22524. }
  22525. }
  22526. else if ((op & 64) === 0) { /* 2nd level length code */
  22527. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22528. continue dolen;
  22529. }
  22530. else if (op & 32) { /* end-of-block */
  22531. //Tracevv((stderr, "inflate: end of block\n"));
  22532. state.mode = TYPE;
  22533. break top;
  22534. }
  22535. else {
  22536. strm.msg = 'invalid literal/length code';
  22537. state.mode = BAD;
  22538. break top;
  22539. }
  22540. break; // need to emulate goto via "continue"
  22541. }
  22542. } while (_in < last && _out < end);
  22543. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22544. len = bits >> 3;
  22545. _in -= len;
  22546. bits -= len << 3;
  22547. hold &= (1 << bits) - 1;
  22548. /* update state and return */
  22549. strm.next_in = _in;
  22550. strm.next_out = _out;
  22551. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22552. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22553. state.hold = hold;
  22554. state.bits = bits;
  22555. return;
  22556. };
  22557. },{}],83:[function(require,module,exports){
  22558. 'use strict';
  22559. var utils = require('../utils/common');
  22560. var adler32 = require('./adler32');
  22561. var crc32 = require('./crc32');
  22562. var inflate_fast = require('./inffast');
  22563. var inflate_table = require('./inftrees');
  22564. var CODES = 0;
  22565. var LENS = 1;
  22566. var DISTS = 2;
  22567. /* Public constants ==========================================================*/
  22568. /* ===========================================================================*/
  22569. /* Allowed flush values; see deflate() and inflate() below for details */
  22570. //var Z_NO_FLUSH = 0;
  22571. //var Z_PARTIAL_FLUSH = 1;
  22572. //var Z_SYNC_FLUSH = 2;
  22573. //var Z_FULL_FLUSH = 3;
  22574. var Z_FINISH = 4;
  22575. var Z_BLOCK = 5;
  22576. var Z_TREES = 6;
  22577. /* Return codes for the compression/decompression functions. Negative values
  22578. * are errors, positive values are used for special but normal events.
  22579. */
  22580. var Z_OK = 0;
  22581. var Z_STREAM_END = 1;
  22582. var Z_NEED_DICT = 2;
  22583. //var Z_ERRNO = -1;
  22584. var Z_STREAM_ERROR = -2;
  22585. var Z_DATA_ERROR = -3;
  22586. var Z_MEM_ERROR = -4;
  22587. var Z_BUF_ERROR = -5;
  22588. //var Z_VERSION_ERROR = -6;
  22589. /* The deflate compression method */
  22590. var Z_DEFLATED = 8;
  22591. /* STATES ====================================================================*/
  22592. /* ===========================================================================*/
  22593. var HEAD = 1; /* i: waiting for magic header */
  22594. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22595. var TIME = 3; /* i: waiting for modification time (gzip) */
  22596. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22597. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22598. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22599. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22600. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22601. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22602. var DICTID = 10; /* i: waiting for dictionary check value */
  22603. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22604. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22605. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22606. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22607. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22608. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22609. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22610. var LENLENS = 18; /* i: waiting for code length code lengths */
  22611. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22612. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22613. var LEN = 21; /* i: waiting for length/lit/eob code */
  22614. var LENEXT = 22; /* i: waiting for length extra bits */
  22615. var DIST = 23; /* i: waiting for distance code */
  22616. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22617. var MATCH = 25; /* o: waiting for output space to copy string */
  22618. var LIT = 26; /* o: waiting for output space to write literal */
  22619. var CHECK = 27; /* i: waiting for 32-bit check value */
  22620. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22621. var DONE = 29; /* finished check, done -- remain here until reset */
  22622. var BAD = 30; /* got a data error -- remain here until reset */
  22623. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22624. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22625. /* ===========================================================================*/
  22626. var ENOUGH_LENS = 852;
  22627. var ENOUGH_DISTS = 592;
  22628. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22629. var MAX_WBITS = 15;
  22630. /* 32K LZ77 window */
  22631. var DEF_WBITS = MAX_WBITS;
  22632. function ZSWAP32(q) {
  22633. return (((q >>> 24) & 0xff) +
  22634. ((q >>> 8) & 0xff00) +
  22635. ((q & 0xff00) << 8) +
  22636. ((q & 0xff) << 24));
  22637. }
  22638. function InflateState() {
  22639. this.mode = 0; /* current inflate mode */
  22640. this.last = false; /* true if processing last block */
  22641. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22642. this.havedict = false; /* true if dictionary provided */
  22643. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22644. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22645. this.check = 0; /* protected copy of check value */
  22646. this.total = 0; /* protected copy of output count */
  22647. // TODO: may be {}
  22648. this.head = null; /* where to save gzip header information */
  22649. /* sliding window */
  22650. this.wbits = 0; /* log base 2 of requested window size */
  22651. this.wsize = 0; /* window size or zero if not using window */
  22652. this.whave = 0; /* valid bytes in the window */
  22653. this.wnext = 0; /* window write index */
  22654. this.window = null; /* allocated sliding window, if needed */
  22655. /* bit accumulator */
  22656. this.hold = 0; /* input bit accumulator */
  22657. this.bits = 0; /* number of bits in "in" */
  22658. /* for string and stored block copying */
  22659. this.length = 0; /* literal or length of data to copy */
  22660. this.offset = 0; /* distance back to copy string from */
  22661. /* for table and code decoding */
  22662. this.extra = 0; /* extra bits needed */
  22663. /* fixed and dynamic code tables */
  22664. this.lencode = null; /* starting table for length/literal codes */
  22665. this.distcode = null; /* starting table for distance codes */
  22666. this.lenbits = 0; /* index bits for lencode */
  22667. this.distbits = 0; /* index bits for distcode */
  22668. /* dynamic table building */
  22669. this.ncode = 0; /* number of code length code lengths */
  22670. this.nlen = 0; /* number of length code lengths */
  22671. this.ndist = 0; /* number of distance code lengths */
  22672. this.have = 0; /* number of code lengths in lens[] */
  22673. this.next = null; /* next available space in codes[] */
  22674. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22675. this.work = new utils.Buf16(288); /* work area for code table building */
  22676. /*
  22677. because we don't have pointers in js, we use lencode and distcode directly
  22678. as buffers so we don't need codes
  22679. */
  22680. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22681. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22682. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22683. this.sane = 0; /* if false, allow invalid distance too far */
  22684. this.back = 0; /* bits back of last unprocessed length/lit */
  22685. this.was = 0; /* initial length of match */
  22686. }
  22687. function inflateResetKeep(strm) {
  22688. var state;
  22689. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22690. state = strm.state;
  22691. strm.total_in = strm.total_out = state.total = 0;
  22692. strm.msg = ''; /*Z_NULL*/
  22693. if (state.wrap) { /* to support ill-conceived Java test suite */
  22694. strm.adler = state.wrap & 1;
  22695. }
  22696. state.mode = HEAD;
  22697. state.last = 0;
  22698. state.havedict = 0;
  22699. state.dmax = 32768;
  22700. state.head = null/*Z_NULL*/;
  22701. state.hold = 0;
  22702. state.bits = 0;
  22703. //state.lencode = state.distcode = state.next = state.codes;
  22704. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22705. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22706. state.sane = 1;
  22707. state.back = -1;
  22708. //Tracev((stderr, "inflate: reset\n"));
  22709. return Z_OK;
  22710. }
  22711. function inflateReset(strm) {
  22712. var state;
  22713. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22714. state = strm.state;
  22715. state.wsize = 0;
  22716. state.whave = 0;
  22717. state.wnext = 0;
  22718. return inflateResetKeep(strm);
  22719. }
  22720. function inflateReset2(strm, windowBits) {
  22721. var wrap;
  22722. var state;
  22723. /* get the state */
  22724. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22725. state = strm.state;
  22726. /* extract wrap request from windowBits parameter */
  22727. if (windowBits < 0) {
  22728. wrap = 0;
  22729. windowBits = -windowBits;
  22730. }
  22731. else {
  22732. wrap = (windowBits >> 4) + 1;
  22733. if (windowBits < 48) {
  22734. windowBits &= 15;
  22735. }
  22736. }
  22737. /* set number of window bits, free window if different */
  22738. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22739. return Z_STREAM_ERROR;
  22740. }
  22741. if (state.window !== null && state.wbits !== windowBits) {
  22742. state.window = null;
  22743. }
  22744. /* update state and reset the rest of it */
  22745. state.wrap = wrap;
  22746. state.wbits = windowBits;
  22747. return inflateReset(strm);
  22748. }
  22749. function inflateInit2(strm, windowBits) {
  22750. var ret;
  22751. var state;
  22752. if (!strm) { return Z_STREAM_ERROR; }
  22753. //strm.msg = Z_NULL; /* in case we return an error */
  22754. state = new InflateState();
  22755. //if (state === Z_NULL) return Z_MEM_ERROR;
  22756. //Tracev((stderr, "inflate: allocated\n"));
  22757. strm.state = state;
  22758. state.window = null/*Z_NULL*/;
  22759. ret = inflateReset2(strm, windowBits);
  22760. if (ret !== Z_OK) {
  22761. strm.state = null/*Z_NULL*/;
  22762. }
  22763. return ret;
  22764. }
  22765. function inflateInit(strm) {
  22766. return inflateInit2(strm, DEF_WBITS);
  22767. }
  22768. /*
  22769. Return state with length and distance decoding tables and index sizes set to
  22770. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22771. If BUILDFIXED is defined, then instead this routine builds the tables the
  22772. first time it's called, and returns those tables the first time and
  22773. thereafter. This reduces the size of the code by about 2K bytes, in
  22774. exchange for a little execution time. However, BUILDFIXED should not be
  22775. used for threaded applications, since the rewriting of the tables and virgin
  22776. may not be thread-safe.
  22777. */
  22778. var virgin = true;
  22779. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22780. function fixedtables(state) {
  22781. /* build fixed huffman tables if first call (may not be thread safe) */
  22782. if (virgin) {
  22783. var sym;
  22784. lenfix = new utils.Buf32(512);
  22785. distfix = new utils.Buf32(32);
  22786. /* literal/length table */
  22787. sym = 0;
  22788. while (sym < 144) { state.lens[sym++] = 8; }
  22789. while (sym < 256) { state.lens[sym++] = 9; }
  22790. while (sym < 280) { state.lens[sym++] = 7; }
  22791. while (sym < 288) { state.lens[sym++] = 8; }
  22792. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22793. /* distance table */
  22794. sym = 0;
  22795. while (sym < 32) { state.lens[sym++] = 5; }
  22796. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22797. /* do this just once */
  22798. virgin = false;
  22799. }
  22800. state.lencode = lenfix;
  22801. state.lenbits = 9;
  22802. state.distcode = distfix;
  22803. state.distbits = 5;
  22804. }
  22805. /*
  22806. Update the window with the last wsize (normally 32K) bytes written before
  22807. returning. If window does not exist yet, create it. This is only called
  22808. when a window is already in use, or when output has been written during this
  22809. inflate call, but the end of the deflate stream has not been reached yet.
  22810. It is also called to create a window for dictionary data when a dictionary
  22811. is loaded.
  22812. Providing output buffers larger than 32K to inflate() should provide a speed
  22813. advantage, since only the last 32K of output is copied to the sliding window
  22814. upon return from inflate(), and since all distances after the first 32K of
  22815. output will fall in the output data, making match copies simpler and faster.
  22816. The advantage may be dependent on the size of the processor's data caches.
  22817. */
  22818. function updatewindow(strm, src, end, copy) {
  22819. var dist;
  22820. var state = strm.state;
  22821. /* if it hasn't been done already, allocate space for the window */
  22822. if (state.window === null) {
  22823. state.wsize = 1 << state.wbits;
  22824. state.wnext = 0;
  22825. state.whave = 0;
  22826. state.window = new utils.Buf8(state.wsize);
  22827. }
  22828. /* copy state->wsize or less output bytes into the circular window */
  22829. if (copy >= state.wsize) {
  22830. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22831. state.wnext = 0;
  22832. state.whave = state.wsize;
  22833. }
  22834. else {
  22835. dist = state.wsize - state.wnext;
  22836. if (dist > copy) {
  22837. dist = copy;
  22838. }
  22839. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22840. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22841. copy -= dist;
  22842. if (copy) {
  22843. //zmemcpy(state->window, end - copy, copy);
  22844. utils.arraySet(state.window,src, end - copy, copy, 0);
  22845. state.wnext = copy;
  22846. state.whave = state.wsize;
  22847. }
  22848. else {
  22849. state.wnext += dist;
  22850. if (state.wnext === state.wsize) { state.wnext = 0; }
  22851. if (state.whave < state.wsize) { state.whave += dist; }
  22852. }
  22853. }
  22854. return 0;
  22855. }
  22856. function inflate(strm, flush) {
  22857. var state;
  22858. var input, output; // input/output buffers
  22859. var next; /* next input INDEX */
  22860. var put; /* next output INDEX */
  22861. var have, left; /* available input and output */
  22862. var hold; /* bit buffer */
  22863. var bits; /* bits in bit buffer */
  22864. var _in, _out; /* save starting available input and output */
  22865. var copy; /* number of stored or match bytes to copy */
  22866. var from; /* where to copy match bytes from */
  22867. var from_source;
  22868. var here = 0; /* current decoding table entry */
  22869. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22870. //var last; /* parent table entry */
  22871. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22872. var len; /* length to copy for repeats, bits to drop */
  22873. var ret; /* return code */
  22874. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22875. var opts;
  22876. var n; // temporary var for NEED_BITS
  22877. var order = /* permutation of code lengths */
  22878. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22879. if (!strm || !strm.state || !strm.output ||
  22880. (!strm.input && strm.avail_in !== 0)) {
  22881. return Z_STREAM_ERROR;
  22882. }
  22883. state = strm.state;
  22884. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22885. //--- LOAD() ---
  22886. put = strm.next_out;
  22887. output = strm.output;
  22888. left = strm.avail_out;
  22889. next = strm.next_in;
  22890. input = strm.input;
  22891. have = strm.avail_in;
  22892. hold = state.hold;
  22893. bits = state.bits;
  22894. //---
  22895. _in = have;
  22896. _out = left;
  22897. ret = Z_OK;
  22898. inf_leave: // goto emulation
  22899. for (;;) {
  22900. switch (state.mode) {
  22901. case HEAD:
  22902. if (state.wrap === 0) {
  22903. state.mode = TYPEDO;
  22904. break;
  22905. }
  22906. //=== NEEDBITS(16);
  22907. while (bits < 16) {
  22908. if (have === 0) { break inf_leave; }
  22909. have--;
  22910. hold += input[next++] << bits;
  22911. bits += 8;
  22912. }
  22913. //===//
  22914. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22915. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22916. //=== CRC2(state.check, hold);
  22917. hbuf[0] = hold & 0xff;
  22918. hbuf[1] = (hold >>> 8) & 0xff;
  22919. state.check = crc32(state.check, hbuf, 2, 0);
  22920. //===//
  22921. //=== INITBITS();
  22922. hold = 0;
  22923. bits = 0;
  22924. //===//
  22925. state.mode = FLAGS;
  22926. break;
  22927. }
  22928. state.flags = 0; /* expect zlib header */
  22929. if (state.head) {
  22930. state.head.done = false;
  22931. }
  22932. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22933. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22934. strm.msg = 'incorrect header check';
  22935. state.mode = BAD;
  22936. break;
  22937. }
  22938. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22939. strm.msg = 'unknown compression method';
  22940. state.mode = BAD;
  22941. break;
  22942. }
  22943. //--- DROPBITS(4) ---//
  22944. hold >>>= 4;
  22945. bits -= 4;
  22946. //---//
  22947. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22948. if (state.wbits === 0) {
  22949. state.wbits = len;
  22950. }
  22951. else if (len > state.wbits) {
  22952. strm.msg = 'invalid window size';
  22953. state.mode = BAD;
  22954. break;
  22955. }
  22956. state.dmax = 1 << len;
  22957. //Tracev((stderr, "inflate: zlib header ok\n"));
  22958. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22959. state.mode = hold & 0x200 ? DICTID : TYPE;
  22960. //=== INITBITS();
  22961. hold = 0;
  22962. bits = 0;
  22963. //===//
  22964. break;
  22965. case FLAGS:
  22966. //=== NEEDBITS(16); */
  22967. while (bits < 16) {
  22968. if (have === 0) { break inf_leave; }
  22969. have--;
  22970. hold += input[next++] << bits;
  22971. bits += 8;
  22972. }
  22973. //===//
  22974. state.flags = hold;
  22975. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22976. strm.msg = 'unknown compression method';
  22977. state.mode = BAD;
  22978. break;
  22979. }
  22980. if (state.flags & 0xe000) {
  22981. strm.msg = 'unknown header flags set';
  22982. state.mode = BAD;
  22983. break;
  22984. }
  22985. if (state.head) {
  22986. state.head.text = ((hold >> 8) & 1);
  22987. }
  22988. if (state.flags & 0x0200) {
  22989. //=== CRC2(state.check, hold);
  22990. hbuf[0] = hold & 0xff;
  22991. hbuf[1] = (hold >>> 8) & 0xff;
  22992. state.check = crc32(state.check, hbuf, 2, 0);
  22993. //===//
  22994. }
  22995. //=== INITBITS();
  22996. hold = 0;
  22997. bits = 0;
  22998. //===//
  22999. state.mode = TIME;
  23000. /* falls through */
  23001. case TIME:
  23002. //=== NEEDBITS(32); */
  23003. while (bits < 32) {
  23004. if (have === 0) { break inf_leave; }
  23005. have--;
  23006. hold += input[next++] << bits;
  23007. bits += 8;
  23008. }
  23009. //===//
  23010. if (state.head) {
  23011. state.head.time = hold;
  23012. }
  23013. if (state.flags & 0x0200) {
  23014. //=== CRC4(state.check, hold)
  23015. hbuf[0] = hold & 0xff;
  23016. hbuf[1] = (hold >>> 8) & 0xff;
  23017. hbuf[2] = (hold >>> 16) & 0xff;
  23018. hbuf[3] = (hold >>> 24) & 0xff;
  23019. state.check = crc32(state.check, hbuf, 4, 0);
  23020. //===
  23021. }
  23022. //=== INITBITS();
  23023. hold = 0;
  23024. bits = 0;
  23025. //===//
  23026. state.mode = OS;
  23027. /* falls through */
  23028. case OS:
  23029. //=== NEEDBITS(16); */
  23030. while (bits < 16) {
  23031. if (have === 0) { break inf_leave; }
  23032. have--;
  23033. hold += input[next++] << bits;
  23034. bits += 8;
  23035. }
  23036. //===//
  23037. if (state.head) {
  23038. state.head.xflags = (hold & 0xff);
  23039. state.head.os = (hold >> 8);
  23040. }
  23041. if (state.flags & 0x0200) {
  23042. //=== CRC2(state.check, hold);
  23043. hbuf[0] = hold & 0xff;
  23044. hbuf[1] = (hold >>> 8) & 0xff;
  23045. state.check = crc32(state.check, hbuf, 2, 0);
  23046. //===//
  23047. }
  23048. //=== INITBITS();
  23049. hold = 0;
  23050. bits = 0;
  23051. //===//
  23052. state.mode = EXLEN;
  23053. /* falls through */
  23054. case EXLEN:
  23055. if (state.flags & 0x0400) {
  23056. //=== NEEDBITS(16); */
  23057. while (bits < 16) {
  23058. if (have === 0) { break inf_leave; }
  23059. have--;
  23060. hold += input[next++] << bits;
  23061. bits += 8;
  23062. }
  23063. //===//
  23064. state.length = hold;
  23065. if (state.head) {
  23066. state.head.extra_len = hold;
  23067. }
  23068. if (state.flags & 0x0200) {
  23069. //=== CRC2(state.check, hold);
  23070. hbuf[0] = hold & 0xff;
  23071. hbuf[1] = (hold >>> 8) & 0xff;
  23072. state.check = crc32(state.check, hbuf, 2, 0);
  23073. //===//
  23074. }
  23075. //=== INITBITS();
  23076. hold = 0;
  23077. bits = 0;
  23078. //===//
  23079. }
  23080. else if (state.head) {
  23081. state.head.extra = null/*Z_NULL*/;
  23082. }
  23083. state.mode = EXTRA;
  23084. /* falls through */
  23085. case EXTRA:
  23086. if (state.flags & 0x0400) {
  23087. copy = state.length;
  23088. if (copy > have) { copy = have; }
  23089. if (copy) {
  23090. if (state.head) {
  23091. len = state.head.extra_len - state.length;
  23092. if (!state.head.extra) {
  23093. // Use untyped array for more conveniend processing later
  23094. state.head.extra = new Array(state.head.extra_len);
  23095. }
  23096. utils.arraySet(
  23097. state.head.extra,
  23098. input,
  23099. next,
  23100. // extra field is limited to 65536 bytes
  23101. // - no need for additional size check
  23102. copy,
  23103. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  23104. len
  23105. );
  23106. //zmemcpy(state.head.extra + len, next,
  23107. // len + copy > state.head.extra_max ?
  23108. // state.head.extra_max - len : copy);
  23109. }
  23110. if (state.flags & 0x0200) {
  23111. state.check = crc32(state.check, input, copy, next);
  23112. }
  23113. have -= copy;
  23114. next += copy;
  23115. state.length -= copy;
  23116. }
  23117. if (state.length) { break inf_leave; }
  23118. }
  23119. state.length = 0;
  23120. state.mode = NAME;
  23121. /* falls through */
  23122. case NAME:
  23123. if (state.flags & 0x0800) {
  23124. if (have === 0) { break inf_leave; }
  23125. copy = 0;
  23126. do {
  23127. // TODO: 2 or 1 bytes?
  23128. len = input[next + copy++];
  23129. /* use constant limit because in js we should not preallocate memory */
  23130. if (state.head && len &&
  23131. (state.length < 65536 /*state.head.name_max*/)) {
  23132. state.head.name += String.fromCharCode(len);
  23133. }
  23134. } while (len && copy < have);
  23135. if (state.flags & 0x0200) {
  23136. state.check = crc32(state.check, input, copy, next);
  23137. }
  23138. have -= copy;
  23139. next += copy;
  23140. if (len) { break inf_leave; }
  23141. }
  23142. else if (state.head) {
  23143. state.head.name = null;
  23144. }
  23145. state.length = 0;
  23146. state.mode = COMMENT;
  23147. /* falls through */
  23148. case COMMENT:
  23149. if (state.flags & 0x1000) {
  23150. if (have === 0) { break inf_leave; }
  23151. copy = 0;
  23152. do {
  23153. len = input[next + copy++];
  23154. /* use constant limit because in js we should not preallocate memory */
  23155. if (state.head && len &&
  23156. (state.length < 65536 /*state.head.comm_max*/)) {
  23157. state.head.comment += String.fromCharCode(len);
  23158. }
  23159. } while (len && copy < have);
  23160. if (state.flags & 0x0200) {
  23161. state.check = crc32(state.check, input, copy, next);
  23162. }
  23163. have -= copy;
  23164. next += copy;
  23165. if (len) { break inf_leave; }
  23166. }
  23167. else if (state.head) {
  23168. state.head.comment = null;
  23169. }
  23170. state.mode = HCRC;
  23171. /* falls through */
  23172. case HCRC:
  23173. if (state.flags & 0x0200) {
  23174. //=== NEEDBITS(16); */
  23175. while (bits < 16) {
  23176. if (have === 0) { break inf_leave; }
  23177. have--;
  23178. hold += input[next++] << bits;
  23179. bits += 8;
  23180. }
  23181. //===//
  23182. if (hold !== (state.check & 0xffff)) {
  23183. strm.msg = 'header crc mismatch';
  23184. state.mode = BAD;
  23185. break;
  23186. }
  23187. //=== INITBITS();
  23188. hold = 0;
  23189. bits = 0;
  23190. //===//
  23191. }
  23192. if (state.head) {
  23193. state.head.hcrc = ((state.flags >> 9) & 1);
  23194. state.head.done = true;
  23195. }
  23196. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  23197. state.mode = TYPE;
  23198. break;
  23199. case DICTID:
  23200. //=== NEEDBITS(32); */
  23201. while (bits < 32) {
  23202. if (have === 0) { break inf_leave; }
  23203. have--;
  23204. hold += input[next++] << bits;
  23205. bits += 8;
  23206. }
  23207. //===//
  23208. strm.adler = state.check = ZSWAP32(hold);
  23209. //=== INITBITS();
  23210. hold = 0;
  23211. bits = 0;
  23212. //===//
  23213. state.mode = DICT;
  23214. /* falls through */
  23215. case DICT:
  23216. if (state.havedict === 0) {
  23217. //--- RESTORE() ---
  23218. strm.next_out = put;
  23219. strm.avail_out = left;
  23220. strm.next_in = next;
  23221. strm.avail_in = have;
  23222. state.hold = hold;
  23223. state.bits = bits;
  23224. //---
  23225. return Z_NEED_DICT;
  23226. }
  23227. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23228. state.mode = TYPE;
  23229. /* falls through */
  23230. case TYPE:
  23231. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  23232. /* falls through */
  23233. case TYPEDO:
  23234. if (state.last) {
  23235. //--- BYTEBITS() ---//
  23236. hold >>>= bits & 7;
  23237. bits -= bits & 7;
  23238. //---//
  23239. state.mode = CHECK;
  23240. break;
  23241. }
  23242. //=== NEEDBITS(3); */
  23243. while (bits < 3) {
  23244. if (have === 0) { break inf_leave; }
  23245. have--;
  23246. hold += input[next++] << bits;
  23247. bits += 8;
  23248. }
  23249. //===//
  23250. state.last = (hold & 0x01)/*BITS(1)*/;
  23251. //--- DROPBITS(1) ---//
  23252. hold >>>= 1;
  23253. bits -= 1;
  23254. //---//
  23255. switch ((hold & 0x03)/*BITS(2)*/) {
  23256. case 0: /* stored block */
  23257. //Tracev((stderr, "inflate: stored block%s\n",
  23258. // state.last ? " (last)" : ""));
  23259. state.mode = STORED;
  23260. break;
  23261. case 1: /* fixed block */
  23262. fixedtables(state);
  23263. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23264. // state.last ? " (last)" : ""));
  23265. state.mode = LEN_; /* decode codes */
  23266. if (flush === Z_TREES) {
  23267. //--- DROPBITS(2) ---//
  23268. hold >>>= 2;
  23269. bits -= 2;
  23270. //---//
  23271. break inf_leave;
  23272. }
  23273. break;
  23274. case 2: /* dynamic block */
  23275. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23276. // state.last ? " (last)" : ""));
  23277. state.mode = TABLE;
  23278. break;
  23279. case 3:
  23280. strm.msg = 'invalid block type';
  23281. state.mode = BAD;
  23282. }
  23283. //--- DROPBITS(2) ---//
  23284. hold >>>= 2;
  23285. bits -= 2;
  23286. //---//
  23287. break;
  23288. case STORED:
  23289. //--- BYTEBITS() ---// /* go to byte boundary */
  23290. hold >>>= bits & 7;
  23291. bits -= bits & 7;
  23292. //---//
  23293. //=== NEEDBITS(32); */
  23294. while (bits < 32) {
  23295. if (have === 0) { break inf_leave; }
  23296. have--;
  23297. hold += input[next++] << bits;
  23298. bits += 8;
  23299. }
  23300. //===//
  23301. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23302. strm.msg = 'invalid stored block lengths';
  23303. state.mode = BAD;
  23304. break;
  23305. }
  23306. state.length = hold & 0xffff;
  23307. //Tracev((stderr, "inflate: stored length %u\n",
  23308. // state.length));
  23309. //=== INITBITS();
  23310. hold = 0;
  23311. bits = 0;
  23312. //===//
  23313. state.mode = COPY_;
  23314. if (flush === Z_TREES) { break inf_leave; }
  23315. /* falls through */
  23316. case COPY_:
  23317. state.mode = COPY;
  23318. /* falls through */
  23319. case COPY:
  23320. copy = state.length;
  23321. if (copy) {
  23322. if (copy > have) { copy = have; }
  23323. if (copy > left) { copy = left; }
  23324. if (copy === 0) { break inf_leave; }
  23325. //--- zmemcpy(put, next, copy); ---
  23326. utils.arraySet(output, input, next, copy, put);
  23327. //---//
  23328. have -= copy;
  23329. next += copy;
  23330. left -= copy;
  23331. put += copy;
  23332. state.length -= copy;
  23333. break;
  23334. }
  23335. //Tracev((stderr, "inflate: stored end\n"));
  23336. state.mode = TYPE;
  23337. break;
  23338. case TABLE:
  23339. //=== NEEDBITS(14); */
  23340. while (bits < 14) {
  23341. if (have === 0) { break inf_leave; }
  23342. have--;
  23343. hold += input[next++] << bits;
  23344. bits += 8;
  23345. }
  23346. //===//
  23347. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23348. //--- DROPBITS(5) ---//
  23349. hold >>>= 5;
  23350. bits -= 5;
  23351. //---//
  23352. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23353. //--- DROPBITS(5) ---//
  23354. hold >>>= 5;
  23355. bits -= 5;
  23356. //---//
  23357. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23358. //--- DROPBITS(4) ---//
  23359. hold >>>= 4;
  23360. bits -= 4;
  23361. //---//
  23362. //#ifndef PKZIP_BUG_WORKAROUND
  23363. if (state.nlen > 286 || state.ndist > 30) {
  23364. strm.msg = 'too many length or distance symbols';
  23365. state.mode = BAD;
  23366. break;
  23367. }
  23368. //#endif
  23369. //Tracev((stderr, "inflate: table sizes ok\n"));
  23370. state.have = 0;
  23371. state.mode = LENLENS;
  23372. /* falls through */
  23373. case LENLENS:
  23374. while (state.have < state.ncode) {
  23375. //=== NEEDBITS(3);
  23376. while (bits < 3) {
  23377. if (have === 0) { break inf_leave; }
  23378. have--;
  23379. hold += input[next++] << bits;
  23380. bits += 8;
  23381. }
  23382. //===//
  23383. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23384. //--- DROPBITS(3) ---//
  23385. hold >>>= 3;
  23386. bits -= 3;
  23387. //---//
  23388. }
  23389. while (state.have < 19) {
  23390. state.lens[order[state.have++]] = 0;
  23391. }
  23392. // We have separate tables & no pointers. 2 commented lines below not needed.
  23393. //state.next = state.codes;
  23394. //state.lencode = state.next;
  23395. // Switch to use dynamic table
  23396. state.lencode = state.lendyn;
  23397. state.lenbits = 7;
  23398. opts = {bits: state.lenbits};
  23399. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23400. state.lenbits = opts.bits;
  23401. if (ret) {
  23402. strm.msg = 'invalid code lengths set';
  23403. state.mode = BAD;
  23404. break;
  23405. }
  23406. //Tracev((stderr, "inflate: code lengths ok\n"));
  23407. state.have = 0;
  23408. state.mode = CODELENS;
  23409. /* falls through */
  23410. case CODELENS:
  23411. while (state.have < state.nlen + state.ndist) {
  23412. for (;;) {
  23413. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23414. here_bits = here >>> 24;
  23415. here_op = (here >>> 16) & 0xff;
  23416. here_val = here & 0xffff;
  23417. if ((here_bits) <= bits) { break; }
  23418. //--- PULLBYTE() ---//
  23419. if (have === 0) { break inf_leave; }
  23420. have--;
  23421. hold += input[next++] << bits;
  23422. bits += 8;
  23423. //---//
  23424. }
  23425. if (here_val < 16) {
  23426. //--- DROPBITS(here.bits) ---//
  23427. hold >>>= here_bits;
  23428. bits -= here_bits;
  23429. //---//
  23430. state.lens[state.have++] = here_val;
  23431. }
  23432. else {
  23433. if (here_val === 16) {
  23434. //=== NEEDBITS(here.bits + 2);
  23435. n = here_bits + 2;
  23436. while (bits < n) {
  23437. if (have === 0) { break inf_leave; }
  23438. have--;
  23439. hold += input[next++] << bits;
  23440. bits += 8;
  23441. }
  23442. //===//
  23443. //--- DROPBITS(here.bits) ---//
  23444. hold >>>= here_bits;
  23445. bits -= here_bits;
  23446. //---//
  23447. if (state.have === 0) {
  23448. strm.msg = 'invalid bit length repeat';
  23449. state.mode = BAD;
  23450. break;
  23451. }
  23452. len = state.lens[state.have - 1];
  23453. copy = 3 + (hold & 0x03);//BITS(2);
  23454. //--- DROPBITS(2) ---//
  23455. hold >>>= 2;
  23456. bits -= 2;
  23457. //---//
  23458. }
  23459. else if (here_val === 17) {
  23460. //=== NEEDBITS(here.bits + 3);
  23461. n = here_bits + 3;
  23462. while (bits < n) {
  23463. if (have === 0) { break inf_leave; }
  23464. have--;
  23465. hold += input[next++] << bits;
  23466. bits += 8;
  23467. }
  23468. //===//
  23469. //--- DROPBITS(here.bits) ---//
  23470. hold >>>= here_bits;
  23471. bits -= here_bits;
  23472. //---//
  23473. len = 0;
  23474. copy = 3 + (hold & 0x07);//BITS(3);
  23475. //--- DROPBITS(3) ---//
  23476. hold >>>= 3;
  23477. bits -= 3;
  23478. //---//
  23479. }
  23480. else {
  23481. //=== NEEDBITS(here.bits + 7);
  23482. n = here_bits + 7;
  23483. while (bits < n) {
  23484. if (have === 0) { break inf_leave; }
  23485. have--;
  23486. hold += input[next++] << bits;
  23487. bits += 8;
  23488. }
  23489. //===//
  23490. //--- DROPBITS(here.bits) ---//
  23491. hold >>>= here_bits;
  23492. bits -= here_bits;
  23493. //---//
  23494. len = 0;
  23495. copy = 11 + (hold & 0x7f);//BITS(7);
  23496. //--- DROPBITS(7) ---//
  23497. hold >>>= 7;
  23498. bits -= 7;
  23499. //---//
  23500. }
  23501. if (state.have + copy > state.nlen + state.ndist) {
  23502. strm.msg = 'invalid bit length repeat';
  23503. state.mode = BAD;
  23504. break;
  23505. }
  23506. while (copy--) {
  23507. state.lens[state.have++] = len;
  23508. }
  23509. }
  23510. }
  23511. /* handle error breaks in while */
  23512. if (state.mode === BAD) { break; }
  23513. /* check for end-of-block code (better have one) */
  23514. if (state.lens[256] === 0) {
  23515. strm.msg = 'invalid code -- missing end-of-block';
  23516. state.mode = BAD;
  23517. break;
  23518. }
  23519. /* build code tables -- note: do not change the lenbits or distbits
  23520. values here (9 and 6) without reading the comments in inftrees.h
  23521. concerning the ENOUGH constants, which depend on those values */
  23522. state.lenbits = 9;
  23523. opts = {bits: state.lenbits};
  23524. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23525. // We have separate tables & no pointers. 2 commented lines below not needed.
  23526. // state.next_index = opts.table_index;
  23527. state.lenbits = opts.bits;
  23528. // state.lencode = state.next;
  23529. if (ret) {
  23530. strm.msg = 'invalid literal/lengths set';
  23531. state.mode = BAD;
  23532. break;
  23533. }
  23534. state.distbits = 6;
  23535. //state.distcode.copy(state.codes);
  23536. // Switch to use dynamic table
  23537. state.distcode = state.distdyn;
  23538. opts = {bits: state.distbits};
  23539. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23540. // We have separate tables & no pointers. 2 commented lines below not needed.
  23541. // state.next_index = opts.table_index;
  23542. state.distbits = opts.bits;
  23543. // state.distcode = state.next;
  23544. if (ret) {
  23545. strm.msg = 'invalid distances set';
  23546. state.mode = BAD;
  23547. break;
  23548. }
  23549. //Tracev((stderr, 'inflate: codes ok\n'));
  23550. state.mode = LEN_;
  23551. if (flush === Z_TREES) { break inf_leave; }
  23552. /* falls through */
  23553. case LEN_:
  23554. state.mode = LEN;
  23555. /* falls through */
  23556. case LEN:
  23557. if (have >= 6 && left >= 258) {
  23558. //--- RESTORE() ---
  23559. strm.next_out = put;
  23560. strm.avail_out = left;
  23561. strm.next_in = next;
  23562. strm.avail_in = have;
  23563. state.hold = hold;
  23564. state.bits = bits;
  23565. //---
  23566. inflate_fast(strm, _out);
  23567. //--- LOAD() ---
  23568. put = strm.next_out;
  23569. output = strm.output;
  23570. left = strm.avail_out;
  23571. next = strm.next_in;
  23572. input = strm.input;
  23573. have = strm.avail_in;
  23574. hold = state.hold;
  23575. bits = state.bits;
  23576. //---
  23577. if (state.mode === TYPE) {
  23578. state.back = -1;
  23579. }
  23580. break;
  23581. }
  23582. state.back = 0;
  23583. for (;;) {
  23584. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23585. here_bits = here >>> 24;
  23586. here_op = (here >>> 16) & 0xff;
  23587. here_val = here & 0xffff;
  23588. if (here_bits <= bits) { break; }
  23589. //--- PULLBYTE() ---//
  23590. if (have === 0) { break inf_leave; }
  23591. have--;
  23592. hold += input[next++] << bits;
  23593. bits += 8;
  23594. //---//
  23595. }
  23596. if (here_op && (here_op & 0xf0) === 0) {
  23597. last_bits = here_bits;
  23598. last_op = here_op;
  23599. last_val = here_val;
  23600. for (;;) {
  23601. here = state.lencode[last_val +
  23602. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23603. here_bits = here >>> 24;
  23604. here_op = (here >>> 16) & 0xff;
  23605. here_val = here & 0xffff;
  23606. if ((last_bits + here_bits) <= bits) { break; }
  23607. //--- PULLBYTE() ---//
  23608. if (have === 0) { break inf_leave; }
  23609. have--;
  23610. hold += input[next++] << bits;
  23611. bits += 8;
  23612. //---//
  23613. }
  23614. //--- DROPBITS(last.bits) ---//
  23615. hold >>>= last_bits;
  23616. bits -= last_bits;
  23617. //---//
  23618. state.back += last_bits;
  23619. }
  23620. //--- DROPBITS(here.bits) ---//
  23621. hold >>>= here_bits;
  23622. bits -= here_bits;
  23623. //---//
  23624. state.back += here_bits;
  23625. state.length = here_val;
  23626. if (here_op === 0) {
  23627. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23628. // "inflate: literal '%c'\n" :
  23629. // "inflate: literal 0x%02x\n", here.val));
  23630. state.mode = LIT;
  23631. break;
  23632. }
  23633. if (here_op & 32) {
  23634. //Tracevv((stderr, "inflate: end of block\n"));
  23635. state.back = -1;
  23636. state.mode = TYPE;
  23637. break;
  23638. }
  23639. if (here_op & 64) {
  23640. strm.msg = 'invalid literal/length code';
  23641. state.mode = BAD;
  23642. break;
  23643. }
  23644. state.extra = here_op & 15;
  23645. state.mode = LENEXT;
  23646. /* falls through */
  23647. case LENEXT:
  23648. if (state.extra) {
  23649. //=== NEEDBITS(state.extra);
  23650. n = state.extra;
  23651. while (bits < n) {
  23652. if (have === 0) { break inf_leave; }
  23653. have--;
  23654. hold += input[next++] << bits;
  23655. bits += 8;
  23656. }
  23657. //===//
  23658. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23659. //--- DROPBITS(state.extra) ---//
  23660. hold >>>= state.extra;
  23661. bits -= state.extra;
  23662. //---//
  23663. state.back += state.extra;
  23664. }
  23665. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23666. state.was = state.length;
  23667. state.mode = DIST;
  23668. /* falls through */
  23669. case DIST:
  23670. for (;;) {
  23671. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23672. here_bits = here >>> 24;
  23673. here_op = (here >>> 16) & 0xff;
  23674. here_val = here & 0xffff;
  23675. if ((here_bits) <= bits) { break; }
  23676. //--- PULLBYTE() ---//
  23677. if (have === 0) { break inf_leave; }
  23678. have--;
  23679. hold += input[next++] << bits;
  23680. bits += 8;
  23681. //---//
  23682. }
  23683. if ((here_op & 0xf0) === 0) {
  23684. last_bits = here_bits;
  23685. last_op = here_op;
  23686. last_val = here_val;
  23687. for (;;) {
  23688. here = state.distcode[last_val +
  23689. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23690. here_bits = here >>> 24;
  23691. here_op = (here >>> 16) & 0xff;
  23692. here_val = here & 0xffff;
  23693. if ((last_bits + here_bits) <= bits) { break; }
  23694. //--- PULLBYTE() ---//
  23695. if (have === 0) { break inf_leave; }
  23696. have--;
  23697. hold += input[next++] << bits;
  23698. bits += 8;
  23699. //---//
  23700. }
  23701. //--- DROPBITS(last.bits) ---//
  23702. hold >>>= last_bits;
  23703. bits -= last_bits;
  23704. //---//
  23705. state.back += last_bits;
  23706. }
  23707. //--- DROPBITS(here.bits) ---//
  23708. hold >>>= here_bits;
  23709. bits -= here_bits;
  23710. //---//
  23711. state.back += here_bits;
  23712. if (here_op & 64) {
  23713. strm.msg = 'invalid distance code';
  23714. state.mode = BAD;
  23715. break;
  23716. }
  23717. state.offset = here_val;
  23718. state.extra = (here_op) & 15;
  23719. state.mode = DISTEXT;
  23720. /* falls through */
  23721. case DISTEXT:
  23722. if (state.extra) {
  23723. //=== NEEDBITS(state.extra);
  23724. n = state.extra;
  23725. while (bits < n) {
  23726. if (have === 0) { break inf_leave; }
  23727. have--;
  23728. hold += input[next++] << bits;
  23729. bits += 8;
  23730. }
  23731. //===//
  23732. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23733. //--- DROPBITS(state.extra) ---//
  23734. hold >>>= state.extra;
  23735. bits -= state.extra;
  23736. //---//
  23737. state.back += state.extra;
  23738. }
  23739. //#ifdef INFLATE_STRICT
  23740. if (state.offset > state.dmax) {
  23741. strm.msg = 'invalid distance too far back';
  23742. state.mode = BAD;
  23743. break;
  23744. }
  23745. //#endif
  23746. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23747. state.mode = MATCH;
  23748. /* falls through */
  23749. case MATCH:
  23750. if (left === 0) { break inf_leave; }
  23751. copy = _out - left;
  23752. if (state.offset > copy) { /* copy from window */
  23753. copy = state.offset - copy;
  23754. if (copy > state.whave) {
  23755. if (state.sane) {
  23756. strm.msg = 'invalid distance too far back';
  23757. state.mode = BAD;
  23758. break;
  23759. }
  23760. // (!) This block is disabled in zlib defailts,
  23761. // don't enable it for binary compatibility
  23762. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23763. // Trace((stderr, "inflate.c too far\n"));
  23764. // copy -= state.whave;
  23765. // if (copy > state.length) { copy = state.length; }
  23766. // if (copy > left) { copy = left; }
  23767. // left -= copy;
  23768. // state.length -= copy;
  23769. // do {
  23770. // output[put++] = 0;
  23771. // } while (--copy);
  23772. // if (state.length === 0) { state.mode = LEN; }
  23773. // break;
  23774. //#endif
  23775. }
  23776. if (copy > state.wnext) {
  23777. copy -= state.wnext;
  23778. from = state.wsize - copy;
  23779. }
  23780. else {
  23781. from = state.wnext - copy;
  23782. }
  23783. if (copy > state.length) { copy = state.length; }
  23784. from_source = state.window;
  23785. }
  23786. else { /* copy from output */
  23787. from_source = output;
  23788. from = put - state.offset;
  23789. copy = state.length;
  23790. }
  23791. if (copy > left) { copy = left; }
  23792. left -= copy;
  23793. state.length -= copy;
  23794. do {
  23795. output[put++] = from_source[from++];
  23796. } while (--copy);
  23797. if (state.length === 0) { state.mode = LEN; }
  23798. break;
  23799. case LIT:
  23800. if (left === 0) { break inf_leave; }
  23801. output[put++] = state.length;
  23802. left--;
  23803. state.mode = LEN;
  23804. break;
  23805. case CHECK:
  23806. if (state.wrap) {
  23807. //=== NEEDBITS(32);
  23808. while (bits < 32) {
  23809. if (have === 0) { break inf_leave; }
  23810. have--;
  23811. // Use '|' insdead of '+' to make sure that result is signed
  23812. hold |= input[next++] << bits;
  23813. bits += 8;
  23814. }
  23815. //===//
  23816. _out -= left;
  23817. strm.total_out += _out;
  23818. state.total += _out;
  23819. if (_out) {
  23820. strm.adler = state.check =
  23821. /*UPDATE(state.check, put - _out, _out);*/
  23822. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23823. }
  23824. _out = left;
  23825. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23826. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23827. strm.msg = 'incorrect data check';
  23828. state.mode = BAD;
  23829. break;
  23830. }
  23831. //=== INITBITS();
  23832. hold = 0;
  23833. bits = 0;
  23834. //===//
  23835. //Tracev((stderr, "inflate: check matches trailer\n"));
  23836. }
  23837. state.mode = LENGTH;
  23838. /* falls through */
  23839. case LENGTH:
  23840. if (state.wrap && state.flags) {
  23841. //=== NEEDBITS(32);
  23842. while (bits < 32) {
  23843. if (have === 0) { break inf_leave; }
  23844. have--;
  23845. hold += input[next++] << bits;
  23846. bits += 8;
  23847. }
  23848. //===//
  23849. if (hold !== (state.total & 0xffffffff)) {
  23850. strm.msg = 'incorrect length check';
  23851. state.mode = BAD;
  23852. break;
  23853. }
  23854. //=== INITBITS();
  23855. hold = 0;
  23856. bits = 0;
  23857. //===//
  23858. //Tracev((stderr, "inflate: length matches trailer\n"));
  23859. }
  23860. state.mode = DONE;
  23861. /* falls through */
  23862. case DONE:
  23863. ret = Z_STREAM_END;
  23864. break inf_leave;
  23865. case BAD:
  23866. ret = Z_DATA_ERROR;
  23867. break inf_leave;
  23868. case MEM:
  23869. return Z_MEM_ERROR;
  23870. case SYNC:
  23871. /* falls through */
  23872. default:
  23873. return Z_STREAM_ERROR;
  23874. }
  23875. }
  23876. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23877. /*
  23878. Return from inflate(), updating the total counts and the check value.
  23879. If there was no progress during the inflate() call, return a buffer
  23880. error. Call updatewindow() to create and/or update the window state.
  23881. Note: a memory error from inflate() is non-recoverable.
  23882. */
  23883. //--- RESTORE() ---
  23884. strm.next_out = put;
  23885. strm.avail_out = left;
  23886. strm.next_in = next;
  23887. strm.avail_in = have;
  23888. state.hold = hold;
  23889. state.bits = bits;
  23890. //---
  23891. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23892. (state.mode < CHECK || flush !== Z_FINISH))) {
  23893. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23894. state.mode = MEM;
  23895. return Z_MEM_ERROR;
  23896. }
  23897. }
  23898. _in -= strm.avail_in;
  23899. _out -= strm.avail_out;
  23900. strm.total_in += _in;
  23901. strm.total_out += _out;
  23902. state.total += _out;
  23903. if (state.wrap && _out) {
  23904. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23905. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23906. }
  23907. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23908. (state.mode === TYPE ? 128 : 0) +
  23909. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23910. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23911. ret = Z_BUF_ERROR;
  23912. }
  23913. return ret;
  23914. }
  23915. function inflateEnd(strm) {
  23916. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23917. return Z_STREAM_ERROR;
  23918. }
  23919. var state = strm.state;
  23920. if (state.window) {
  23921. state.window = null;
  23922. }
  23923. strm.state = null;
  23924. return Z_OK;
  23925. }
  23926. function inflateGetHeader(strm, head) {
  23927. var state;
  23928. /* check state */
  23929. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23930. state = strm.state;
  23931. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23932. /* save header structure */
  23933. state.head = head;
  23934. head.done = false;
  23935. return Z_OK;
  23936. }
  23937. exports.inflateReset = inflateReset;
  23938. exports.inflateReset2 = inflateReset2;
  23939. exports.inflateResetKeep = inflateResetKeep;
  23940. exports.inflateInit = inflateInit;
  23941. exports.inflateInit2 = inflateInit2;
  23942. exports.inflate = inflate;
  23943. exports.inflateEnd = inflateEnd;
  23944. exports.inflateGetHeader = inflateGetHeader;
  23945. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23946. /* Not implemented
  23947. exports.inflateCopy = inflateCopy;
  23948. exports.inflateGetDictionary = inflateGetDictionary;
  23949. exports.inflateMark = inflateMark;
  23950. exports.inflatePrime = inflatePrime;
  23951. exports.inflateSetDictionary = inflateSetDictionary;
  23952. exports.inflateSync = inflateSync;
  23953. exports.inflateSyncPoint = inflateSyncPoint;
  23954. exports.inflateUndermine = inflateUndermine;
  23955. */
  23956. },{"../utils/common":75,"./adler32":77,"./crc32":79,"./inffast":82,"./inftrees":84}],84:[function(require,module,exports){
  23957. 'use strict';
  23958. var utils = require('../utils/common');
  23959. var MAXBITS = 15;
  23960. var ENOUGH_LENS = 852;
  23961. var ENOUGH_DISTS = 592;
  23962. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23963. var CODES = 0;
  23964. var LENS = 1;
  23965. var DISTS = 2;
  23966. var lbase = [ /* Length codes 257..285 base */
  23967. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23968. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23969. ];
  23970. var lext = [ /* Length codes 257..285 extra */
  23971. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23972. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23973. ];
  23974. var dbase = [ /* Distance codes 0..29 base */
  23975. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23976. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23977. 8193, 12289, 16385, 24577, 0, 0
  23978. ];
  23979. var dext = [ /* Distance codes 0..29 extra */
  23980. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23981. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23982. 28, 28, 29, 29, 64, 64
  23983. ];
  23984. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23985. {
  23986. var bits = opts.bits;
  23987. //here = opts.here; /* table entry for duplication */
  23988. var len = 0; /* a code's length in bits */
  23989. var sym = 0; /* index of code symbols */
  23990. var min = 0, max = 0; /* minimum and maximum code lengths */
  23991. var root = 0; /* number of index bits for root table */
  23992. var curr = 0; /* number of index bits for current table */
  23993. var drop = 0; /* code bits to drop for sub-table */
  23994. var left = 0; /* number of prefix codes available */
  23995. var used = 0; /* code entries in table used */
  23996. var huff = 0; /* Huffman code */
  23997. var incr; /* for incrementing code, index */
  23998. var fill; /* index for replicating entries */
  23999. var low; /* low bits for current root entry */
  24000. var mask; /* mask for low root bits */
  24001. var next; /* next available space in table */
  24002. var base = null; /* base value table to use */
  24003. var base_index = 0;
  24004. // var shoextra; /* extra bits table to use */
  24005. var end; /* use base and extra for symbol > end */
  24006. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  24007. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  24008. var extra = null;
  24009. var extra_index = 0;
  24010. var here_bits, here_op, here_val;
  24011. /*
  24012. Process a set of code lengths to create a canonical Huffman code. The
  24013. code lengths are lens[0..codes-1]. Each length corresponds to the
  24014. symbols 0..codes-1. The Huffman code is generated by first sorting the
  24015. symbols by length from short to long, and retaining the symbol order
  24016. for codes with equal lengths. Then the code starts with all zero bits
  24017. for the first code of the shortest length, and the codes are integer
  24018. increments for the same length, and zeros are appended as the length
  24019. increases. For the deflate format, these bits are stored backwards
  24020. from their more natural integer increment ordering, and so when the
  24021. decoding tables are built in the large loop below, the integer codes
  24022. are incremented backwards.
  24023. This routine assumes, but does not check, that all of the entries in
  24024. lens[] are in the range 0..MAXBITS. The caller must assure this.
  24025. 1..MAXBITS is interpreted as that code length. zero means that that
  24026. symbol does not occur in this code.
  24027. The codes are sorted by computing a count of codes for each length,
  24028. creating from that a table of starting indices for each length in the
  24029. sorted table, and then entering the symbols in order in the sorted
  24030. table. The sorted table is work[], with that space being provided by
  24031. the caller.
  24032. The length counts are used for other purposes as well, i.e. finding
  24033. the minimum and maximum length codes, determining if there are any
  24034. codes at all, checking for a valid set of lengths, and looking ahead
  24035. at length counts to determine sub-table sizes when building the
  24036. decoding tables.
  24037. */
  24038. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  24039. for (len = 0; len <= MAXBITS; len++) {
  24040. count[len] = 0;
  24041. }
  24042. for (sym = 0; sym < codes; sym++) {
  24043. count[lens[lens_index + sym]]++;
  24044. }
  24045. /* bound code lengths, force root to be within code lengths */
  24046. root = bits;
  24047. for (max = MAXBITS; max >= 1; max--) {
  24048. if (count[max] !== 0) { break; }
  24049. }
  24050. if (root > max) {
  24051. root = max;
  24052. }
  24053. if (max === 0) { /* no symbols to code at all */
  24054. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  24055. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  24056. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  24057. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24058. //table.op[opts.table_index] = 64;
  24059. //table.bits[opts.table_index] = 1;
  24060. //table.val[opts.table_index++] = 0;
  24061. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24062. opts.bits = 1;
  24063. return 0; /* no symbols, but wait for decoding to report error */
  24064. }
  24065. for (min = 1; min < max; min++) {
  24066. if (count[min] !== 0) { break; }
  24067. }
  24068. if (root < min) {
  24069. root = min;
  24070. }
  24071. /* check for an over-subscribed or incomplete set of lengths */
  24072. left = 1;
  24073. for (len = 1; len <= MAXBITS; len++) {
  24074. left <<= 1;
  24075. left -= count[len];
  24076. if (left < 0) {
  24077. return -1;
  24078. } /* over-subscribed */
  24079. }
  24080. if (left > 0 && (type === CODES || max !== 1)) {
  24081. return -1; /* incomplete set */
  24082. }
  24083. /* generate offsets into symbol table for each length for sorting */
  24084. offs[1] = 0;
  24085. for (len = 1; len < MAXBITS; len++) {
  24086. offs[len + 1] = offs[len] + count[len];
  24087. }
  24088. /* sort symbols by length, by symbol order within each length */
  24089. for (sym = 0; sym < codes; sym++) {
  24090. if (lens[lens_index + sym] !== 0) {
  24091. work[offs[lens[lens_index + sym]]++] = sym;
  24092. }
  24093. }
  24094. /*
  24095. Create and fill in decoding tables. In this loop, the table being
  24096. filled is at next and has curr index bits. The code being used is huff
  24097. with length len. That code is converted to an index by dropping drop
  24098. bits off of the bottom. For codes where len is less than drop + curr,
  24099. those top drop + curr - len bits are incremented through all values to
  24100. fill the table with replicated entries.
  24101. root is the number of index bits for the root table. When len exceeds
  24102. root, sub-tables are created pointed to by the root entry with an index
  24103. of the low root bits of huff. This is saved in low to check for when a
  24104. new sub-table should be started. drop is zero when the root table is
  24105. being filled, and drop is root when sub-tables are being filled.
  24106. When a new sub-table is needed, it is necessary to look ahead in the
  24107. code lengths to determine what size sub-table is needed. The length
  24108. counts are used for this, and so count[] is decremented as codes are
  24109. entered in the tables.
  24110. used keeps track of how many table entries have been allocated from the
  24111. provided *table space. It is checked for LENS and DIST tables against
  24112. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  24113. the initial root table size constants. See the comments in inftrees.h
  24114. for more information.
  24115. sym increments through all symbols, and the loop terminates when
  24116. all codes of length max, i.e. all codes, have been processed. This
  24117. routine permits incomplete codes, so another loop after this one fills
  24118. in the rest of the decoding tables with invalid code markers.
  24119. */
  24120. /* set up for code type */
  24121. // poor man optimization - use if-else instead of switch,
  24122. // to avoid deopts in old v8
  24123. if (type === CODES) {
  24124. base = extra = work; /* dummy value--not used */
  24125. end = 19;
  24126. } else if (type === LENS) {
  24127. base = lbase;
  24128. base_index -= 257;
  24129. extra = lext;
  24130. extra_index -= 257;
  24131. end = 256;
  24132. } else { /* DISTS */
  24133. base = dbase;
  24134. extra = dext;
  24135. end = -1;
  24136. }
  24137. /* initialize opts for loop */
  24138. huff = 0; /* starting code */
  24139. sym = 0; /* starting code symbol */
  24140. len = min; /* starting code length */
  24141. next = table_index; /* current table to fill in */
  24142. curr = root; /* current table index bits */
  24143. drop = 0; /* current bits to drop from code for index */
  24144. low = -1; /* trigger new sub-table when len > root */
  24145. used = 1 << root; /* use root table entries */
  24146. mask = used - 1; /* mask for comparing low */
  24147. /* check available table space */
  24148. if ((type === LENS && used > ENOUGH_LENS) ||
  24149. (type === DISTS && used > ENOUGH_DISTS)) {
  24150. return 1;
  24151. }
  24152. var i=0;
  24153. /* process all codes and make table entries */
  24154. for (;;) {
  24155. i++;
  24156. /* create table entry */
  24157. here_bits = len - drop;
  24158. if (work[sym] < end) {
  24159. here_op = 0;
  24160. here_val = work[sym];
  24161. }
  24162. else if (work[sym] > end) {
  24163. here_op = extra[extra_index + work[sym]];
  24164. here_val = base[base_index + work[sym]];
  24165. }
  24166. else {
  24167. here_op = 32 + 64; /* end of block */
  24168. here_val = 0;
  24169. }
  24170. /* replicate for those indices with low len bits equal to huff */
  24171. incr = 1 << (len - drop);
  24172. fill = 1 << curr;
  24173. min = fill; /* save offset to next table */
  24174. do {
  24175. fill -= incr;
  24176. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  24177. } while (fill !== 0);
  24178. /* backwards increment the len-bit code huff */
  24179. incr = 1 << (len - 1);
  24180. while (huff & incr) {
  24181. incr >>= 1;
  24182. }
  24183. if (incr !== 0) {
  24184. huff &= incr - 1;
  24185. huff += incr;
  24186. } else {
  24187. huff = 0;
  24188. }
  24189. /* go to next symbol, update count, len */
  24190. sym++;
  24191. if (--count[len] === 0) {
  24192. if (len === max) { break; }
  24193. len = lens[lens_index + work[sym]];
  24194. }
  24195. /* create new sub-table if needed */
  24196. if (len > root && (huff & mask) !== low) {
  24197. /* if first time, transition to sub-tables */
  24198. if (drop === 0) {
  24199. drop = root;
  24200. }
  24201. /* increment past last table */
  24202. next += min; /* here min is 1 << curr */
  24203. /* determine length of next table */
  24204. curr = len - drop;
  24205. left = 1 << curr;
  24206. while (curr + drop < max) {
  24207. left -= count[curr + drop];
  24208. if (left <= 0) { break; }
  24209. curr++;
  24210. left <<= 1;
  24211. }
  24212. /* check for enough space */
  24213. used += 1 << curr;
  24214. if ((type === LENS && used > ENOUGH_LENS) ||
  24215. (type === DISTS && used > ENOUGH_DISTS)) {
  24216. return 1;
  24217. }
  24218. /* point entry in root table to sub-table */
  24219. low = huff & mask;
  24220. /*table.op[low] = curr;
  24221. table.bits[low] = root;
  24222. table.val[low] = next - opts.table_index;*/
  24223. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  24224. }
  24225. }
  24226. /* fill in remaining table entry if code is incomplete (guaranteed to have
  24227. at most one remaining entry, since if the code is incomplete, the
  24228. maximum code length that was allowed to get this far is one bit) */
  24229. if (huff !== 0) {
  24230. //table.op[next + huff] = 64; /* invalid code marker */
  24231. //table.bits[next + huff] = len - drop;
  24232. //table.val[next + huff] = 0;
  24233. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24234. }
  24235. /* set return parameters */
  24236. //opts.table_index += used;
  24237. opts.bits = root;
  24238. return 0;
  24239. };
  24240. },{"../utils/common":75}],85:[function(require,module,exports){
  24241. 'use strict';
  24242. module.exports = {
  24243. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24244. '1': 'stream end', /* Z_STREAM_END 1 */
  24245. '0': '', /* Z_OK 0 */
  24246. '-1': 'file error', /* Z_ERRNO (-1) */
  24247. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24248. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24249. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24250. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24251. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24252. };
  24253. },{}],86:[function(require,module,exports){
  24254. 'use strict';
  24255. var utils = require('../utils/common');
  24256. /* Public constants ==========================================================*/
  24257. /* ===========================================================================*/
  24258. //var Z_FILTERED = 1;
  24259. //var Z_HUFFMAN_ONLY = 2;
  24260. //var Z_RLE = 3;
  24261. var Z_FIXED = 4;
  24262. //var Z_DEFAULT_STRATEGY = 0;
  24263. /* Possible values of the data_type field (though see inflate()) */
  24264. var Z_BINARY = 0;
  24265. var Z_TEXT = 1;
  24266. //var Z_ASCII = 1; // = Z_TEXT
  24267. var Z_UNKNOWN = 2;
  24268. /*============================================================================*/
  24269. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24270. // From zutil.h
  24271. var STORED_BLOCK = 0;
  24272. var STATIC_TREES = 1;
  24273. var DYN_TREES = 2;
  24274. /* The three kinds of block type */
  24275. var MIN_MATCH = 3;
  24276. var MAX_MATCH = 258;
  24277. /* The minimum and maximum match lengths */
  24278. // From deflate.h
  24279. /* ===========================================================================
  24280. * Internal compression state.
  24281. */
  24282. var LENGTH_CODES = 29;
  24283. /* number of length codes, not counting the special END_BLOCK code */
  24284. var LITERALS = 256;
  24285. /* number of literal bytes 0..255 */
  24286. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24287. /* number of Literal or Length codes, including the END_BLOCK code */
  24288. var D_CODES = 30;
  24289. /* number of distance codes */
  24290. var BL_CODES = 19;
  24291. /* number of codes used to transfer the bit lengths */
  24292. var HEAP_SIZE = 2*L_CODES + 1;
  24293. /* maximum heap size */
  24294. var MAX_BITS = 15;
  24295. /* All codes must not exceed MAX_BITS bits */
  24296. var Buf_size = 16;
  24297. /* size of bit buffer in bi_buf */
  24298. /* ===========================================================================
  24299. * Constants
  24300. */
  24301. var MAX_BL_BITS = 7;
  24302. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24303. var END_BLOCK = 256;
  24304. /* end of block literal code */
  24305. var REP_3_6 = 16;
  24306. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24307. var REPZ_3_10 = 17;
  24308. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24309. var REPZ_11_138 = 18;
  24310. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24311. var extra_lbits = /* extra bits for each length code */
  24312. [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];
  24313. var extra_dbits = /* extra bits for each distance code */
  24314. [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];
  24315. var extra_blbits = /* extra bits for each bit length code */
  24316. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24317. var bl_order =
  24318. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24319. /* The lengths of the bit length codes are sent in order of decreasing
  24320. * probability, to avoid transmitting the lengths for unused bit length codes.
  24321. */
  24322. /* ===========================================================================
  24323. * Local data. These are initialized only once.
  24324. */
  24325. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24326. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24327. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24328. var static_ltree = new Array((L_CODES+2) * 2);
  24329. zero(static_ltree);
  24330. /* The static literal tree. Since the bit lengths are imposed, there is no
  24331. * need for the L_CODES extra codes used during heap construction. However
  24332. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24333. * below).
  24334. */
  24335. var static_dtree = new Array(D_CODES * 2);
  24336. zero(static_dtree);
  24337. /* The static distance tree. (Actually a trivial tree since all codes use
  24338. * 5 bits.)
  24339. */
  24340. var _dist_code = new Array(DIST_CODE_LEN);
  24341. zero(_dist_code);
  24342. /* Distance codes. The first 256 values correspond to the distances
  24343. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24344. * the 15 bit distances.
  24345. */
  24346. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24347. zero(_length_code);
  24348. /* length code for each normalized match length (0 == MIN_MATCH) */
  24349. var base_length = new Array(LENGTH_CODES);
  24350. zero(base_length);
  24351. /* First normalized length for each code (0 = MIN_MATCH) */
  24352. var base_dist = new Array(D_CODES);
  24353. zero(base_dist);
  24354. /* First normalized distance for each code (0 = distance of 1) */
  24355. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24356. this.static_tree = static_tree; /* static tree or NULL */
  24357. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24358. this.extra_base = extra_base; /* base index for extra_bits */
  24359. this.elems = elems; /* max number of elements in the tree */
  24360. this.max_length = max_length; /* max bit length for the codes */
  24361. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24362. this.has_stree = static_tree && static_tree.length;
  24363. };
  24364. var static_l_desc;
  24365. var static_d_desc;
  24366. var static_bl_desc;
  24367. var TreeDesc = function(dyn_tree, stat_desc) {
  24368. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24369. this.max_code = 0; /* largest code with non zero frequency */
  24370. this.stat_desc = stat_desc; /* the corresponding static tree */
  24371. };
  24372. function d_code(dist) {
  24373. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24374. }
  24375. /* ===========================================================================
  24376. * Output a short LSB first on the stream.
  24377. * IN assertion: there is enough room in pendingBuf.
  24378. */
  24379. function put_short (s, w) {
  24380. // put_byte(s, (uch)((w) & 0xff));
  24381. // put_byte(s, (uch)((ush)(w) >> 8));
  24382. s.pending_buf[s.pending++] = (w) & 0xff;
  24383. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24384. }
  24385. /* ===========================================================================
  24386. * Send a value on a given number of bits.
  24387. * IN assertion: length <= 16 and value fits in length bits.
  24388. */
  24389. function send_bits(s, value, length) {
  24390. if (s.bi_valid > (Buf_size - length)) {
  24391. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24392. put_short(s, s.bi_buf);
  24393. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24394. s.bi_valid += length - Buf_size;
  24395. } else {
  24396. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24397. s.bi_valid += length;
  24398. }
  24399. }
  24400. function send_code(s, c, tree) {
  24401. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24402. }
  24403. /* ===========================================================================
  24404. * Reverse the first len bits of a code, using straightforward code (a faster
  24405. * method would use a table)
  24406. * IN assertion: 1 <= len <= 15
  24407. */
  24408. function bi_reverse(code, len) {
  24409. var res = 0;
  24410. do {
  24411. res |= code & 1;
  24412. code >>>= 1;
  24413. res <<= 1;
  24414. } while (--len > 0);
  24415. return res >>> 1;
  24416. }
  24417. /* ===========================================================================
  24418. * Flush the bit buffer, keeping at most 7 bits in it.
  24419. */
  24420. function bi_flush(s) {
  24421. if (s.bi_valid === 16) {
  24422. put_short(s, s.bi_buf);
  24423. s.bi_buf = 0;
  24424. s.bi_valid = 0;
  24425. } else if (s.bi_valid >= 8) {
  24426. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24427. s.bi_buf >>= 8;
  24428. s.bi_valid -= 8;
  24429. }
  24430. }
  24431. /* ===========================================================================
  24432. * Compute the optimal bit lengths for a tree and update the total bit length
  24433. * for the current block.
  24434. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24435. * above are the tree nodes sorted by increasing frequency.
  24436. * OUT assertions: the field len is set to the optimal bit length, the
  24437. * array bl_count contains the frequencies for each bit length.
  24438. * The length opt_len is updated; static_len is also updated if stree is
  24439. * not null.
  24440. */
  24441. function gen_bitlen(s, desc)
  24442. // deflate_state *s;
  24443. // tree_desc *desc; /* the tree descriptor */
  24444. {
  24445. var tree = desc.dyn_tree;
  24446. var max_code = desc.max_code;
  24447. var stree = desc.stat_desc.static_tree;
  24448. var has_stree = desc.stat_desc.has_stree;
  24449. var extra = desc.stat_desc.extra_bits;
  24450. var base = desc.stat_desc.extra_base;
  24451. var max_length = desc.stat_desc.max_length;
  24452. var h; /* heap index */
  24453. var n, m; /* iterate over the tree elements */
  24454. var bits; /* bit length */
  24455. var xbits; /* extra bits */
  24456. var f; /* frequency */
  24457. var overflow = 0; /* number of elements with bit length too large */
  24458. for (bits = 0; bits <= MAX_BITS; bits++) {
  24459. s.bl_count[bits] = 0;
  24460. }
  24461. /* In a first pass, compute the optimal bit lengths (which may
  24462. * overflow in the case of the bit length tree).
  24463. */
  24464. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24465. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24466. n = s.heap[h];
  24467. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24468. if (bits > max_length) {
  24469. bits = max_length;
  24470. overflow++;
  24471. }
  24472. tree[n*2 + 1]/*.Len*/ = bits;
  24473. /* We overwrite tree[n].Dad which is no longer needed */
  24474. if (n > max_code) { continue; } /* not a leaf node */
  24475. s.bl_count[bits]++;
  24476. xbits = 0;
  24477. if (n >= base) {
  24478. xbits = extra[n-base];
  24479. }
  24480. f = tree[n * 2]/*.Freq*/;
  24481. s.opt_len += f * (bits + xbits);
  24482. if (has_stree) {
  24483. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24484. }
  24485. }
  24486. if (overflow === 0) { return; }
  24487. // Trace((stderr,"\nbit length overflow\n"));
  24488. /* This happens for example on obj2 and pic of the Calgary corpus */
  24489. /* Find the first bit length which could increase: */
  24490. do {
  24491. bits = max_length-1;
  24492. while (s.bl_count[bits] === 0) { bits--; }
  24493. s.bl_count[bits]--; /* move one leaf down the tree */
  24494. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24495. s.bl_count[max_length]--;
  24496. /* The brother of the overflow item also moves one step up,
  24497. * but this does not affect bl_count[max_length]
  24498. */
  24499. overflow -= 2;
  24500. } while (overflow > 0);
  24501. /* Now recompute all bit lengths, scanning in increasing frequency.
  24502. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24503. * lengths instead of fixing only the wrong ones. This idea is taken
  24504. * from 'ar' written by Haruhiko Okumura.)
  24505. */
  24506. for (bits = max_length; bits !== 0; bits--) {
  24507. n = s.bl_count[bits];
  24508. while (n !== 0) {
  24509. m = s.heap[--h];
  24510. if (m > max_code) { continue; }
  24511. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24512. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24513. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24514. tree[m*2 + 1]/*.Len*/ = bits;
  24515. }
  24516. n--;
  24517. }
  24518. }
  24519. }
  24520. /* ===========================================================================
  24521. * Generate the codes for a given tree and bit counts (which need not be
  24522. * optimal).
  24523. * IN assertion: the array bl_count contains the bit length statistics for
  24524. * the given tree and the field len is set for all tree elements.
  24525. * OUT assertion: the field code is set for all tree elements of non
  24526. * zero code length.
  24527. */
  24528. function gen_codes(tree, max_code, bl_count)
  24529. // ct_data *tree; /* the tree to decorate */
  24530. // int max_code; /* largest code with non zero frequency */
  24531. // ushf *bl_count; /* number of codes at each bit length */
  24532. {
  24533. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24534. var code = 0; /* running code value */
  24535. var bits; /* bit index */
  24536. var n; /* code index */
  24537. /* The distribution counts are first used to generate the code values
  24538. * without bit reversal.
  24539. */
  24540. for (bits = 1; bits <= MAX_BITS; bits++) {
  24541. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24542. }
  24543. /* Check that the bit counts in bl_count are consistent. The last code
  24544. * must be all ones.
  24545. */
  24546. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24547. // "inconsistent bit counts");
  24548. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24549. for (n = 0; n <= max_code; n++) {
  24550. var len = tree[n*2 + 1]/*.Len*/;
  24551. if (len === 0) { continue; }
  24552. /* Now reverse the bits */
  24553. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24554. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24555. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24556. }
  24557. }
  24558. /* ===========================================================================
  24559. * Initialize the various 'constant' tables.
  24560. */
  24561. function tr_static_init() {
  24562. var n; /* iterates over tree elements */
  24563. var bits; /* bit counter */
  24564. var length; /* length value */
  24565. var code; /* code value */
  24566. var dist; /* distance index */
  24567. var bl_count = new Array(MAX_BITS+1);
  24568. /* number of codes at each bit length for an optimal tree */
  24569. // do check in _tr_init()
  24570. //if (static_init_done) return;
  24571. /* For some embedded targets, global variables are not initialized: */
  24572. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24573. static_l_desc.static_tree = static_ltree;
  24574. static_l_desc.extra_bits = extra_lbits;
  24575. static_d_desc.static_tree = static_dtree;
  24576. static_d_desc.extra_bits = extra_dbits;
  24577. static_bl_desc.extra_bits = extra_blbits;
  24578. #endif*/
  24579. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24580. length = 0;
  24581. for (code = 0; code < LENGTH_CODES-1; code++) {
  24582. base_length[code] = length;
  24583. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24584. _length_code[length++] = code;
  24585. }
  24586. }
  24587. //Assert (length == 256, "tr_static_init: length != 256");
  24588. /* Note that the length 255 (match length 258) can be represented
  24589. * in two different ways: code 284 + 5 bits or code 285, so we
  24590. * overwrite length_code[255] to use the best encoding:
  24591. */
  24592. _length_code[length-1] = code;
  24593. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24594. dist = 0;
  24595. for (code = 0 ; code < 16; code++) {
  24596. base_dist[code] = dist;
  24597. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24598. _dist_code[dist++] = code;
  24599. }
  24600. }
  24601. //Assert (dist == 256, "tr_static_init: dist != 256");
  24602. dist >>= 7; /* from now on, all distances are divided by 128 */
  24603. for (; code < D_CODES; code++) {
  24604. base_dist[code] = dist << 7;
  24605. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24606. _dist_code[256 + dist++] = code;
  24607. }
  24608. }
  24609. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24610. /* Construct the codes of the static literal tree */
  24611. for (bits = 0; bits <= MAX_BITS; bits++) {
  24612. bl_count[bits] = 0;
  24613. }
  24614. n = 0;
  24615. while (n <= 143) {
  24616. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24617. n++;
  24618. bl_count[8]++;
  24619. }
  24620. while (n <= 255) {
  24621. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24622. n++;
  24623. bl_count[9]++;
  24624. }
  24625. while (n <= 279) {
  24626. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24627. n++;
  24628. bl_count[7]++;
  24629. }
  24630. while (n <= 287) {
  24631. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24632. n++;
  24633. bl_count[8]++;
  24634. }
  24635. /* Codes 286 and 287 do not exist, but we must include them in the
  24636. * tree construction to get a canonical Huffman tree (longest code
  24637. * all ones)
  24638. */
  24639. gen_codes(static_ltree, L_CODES+1, bl_count);
  24640. /* The static distance tree is trivial: */
  24641. for (n = 0; n < D_CODES; n++) {
  24642. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24643. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24644. }
  24645. // Now data ready and we can init static trees
  24646. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24647. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24648. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24649. //static_init_done = true;
  24650. }
  24651. /* ===========================================================================
  24652. * Initialize a new block.
  24653. */
  24654. function init_block(s) {
  24655. var n; /* iterates over tree elements */
  24656. /* Initialize the trees. */
  24657. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24658. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24659. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24660. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24661. s.opt_len = s.static_len = 0;
  24662. s.last_lit = s.matches = 0;
  24663. }
  24664. /* ===========================================================================
  24665. * Flush the bit buffer and align the output on a byte boundary
  24666. */
  24667. function bi_windup(s)
  24668. {
  24669. if (s.bi_valid > 8) {
  24670. put_short(s, s.bi_buf);
  24671. } else if (s.bi_valid > 0) {
  24672. //put_byte(s, (Byte)s->bi_buf);
  24673. s.pending_buf[s.pending++] = s.bi_buf;
  24674. }
  24675. s.bi_buf = 0;
  24676. s.bi_valid = 0;
  24677. }
  24678. /* ===========================================================================
  24679. * Copy a stored block, storing first the length and its
  24680. * one's complement if requested.
  24681. */
  24682. function copy_block(s, buf, len, header)
  24683. //DeflateState *s;
  24684. //charf *buf; /* the input data */
  24685. //unsigned len; /* its length */
  24686. //int header; /* true if block header must be written */
  24687. {
  24688. bi_windup(s); /* align on byte boundary */
  24689. if (header) {
  24690. put_short(s, len);
  24691. put_short(s, ~len);
  24692. }
  24693. // while (len--) {
  24694. // put_byte(s, *buf++);
  24695. // }
  24696. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24697. s.pending += len;
  24698. }
  24699. /* ===========================================================================
  24700. * Compares to subtrees, using the tree depth as tie breaker when
  24701. * the subtrees have equal frequency. This minimizes the worst case length.
  24702. */
  24703. function smaller(tree, n, m, depth) {
  24704. var _n2 = n*2;
  24705. var _m2 = m*2;
  24706. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24707. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24708. }
  24709. /* ===========================================================================
  24710. * Restore the heap property by moving down the tree starting at node k,
  24711. * exchanging a node with the smallest of its two sons if necessary, stopping
  24712. * when the heap property is re-established (each father smaller than its
  24713. * two sons).
  24714. */
  24715. function pqdownheap(s, tree, k)
  24716. // deflate_state *s;
  24717. // ct_data *tree; /* the tree to restore */
  24718. // int k; /* node to move down */
  24719. {
  24720. var v = s.heap[k];
  24721. var j = k << 1; /* left son of k */
  24722. while (j <= s.heap_len) {
  24723. /* Set j to the smallest of the two sons: */
  24724. if (j < s.heap_len &&
  24725. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24726. j++;
  24727. }
  24728. /* Exit if v is smaller than both sons */
  24729. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24730. /* Exchange v with the smallest son */
  24731. s.heap[k] = s.heap[j];
  24732. k = j;
  24733. /* And continue down the tree, setting j to the left son of k */
  24734. j <<= 1;
  24735. }
  24736. s.heap[k] = v;
  24737. }
  24738. // inlined manually
  24739. // var SMALLEST = 1;
  24740. /* ===========================================================================
  24741. * Send the block data compressed using the given Huffman trees
  24742. */
  24743. function compress_block(s, ltree, dtree)
  24744. // deflate_state *s;
  24745. // const ct_data *ltree; /* literal tree */
  24746. // const ct_data *dtree; /* distance tree */
  24747. {
  24748. var dist; /* distance of matched string */
  24749. var lc; /* match length or unmatched char (if dist == 0) */
  24750. var lx = 0; /* running index in l_buf */
  24751. var code; /* the code to send */
  24752. var extra; /* number of extra bits to send */
  24753. if (s.last_lit !== 0) {
  24754. do {
  24755. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24756. lc = s.pending_buf[s.l_buf + lx];
  24757. lx++;
  24758. if (dist === 0) {
  24759. send_code(s, lc, ltree); /* send a literal byte */
  24760. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24761. } else {
  24762. /* Here, lc is the match length - MIN_MATCH */
  24763. code = _length_code[lc];
  24764. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24765. extra = extra_lbits[code];
  24766. if (extra !== 0) {
  24767. lc -= base_length[code];
  24768. send_bits(s, lc, extra); /* send the extra length bits */
  24769. }
  24770. dist--; /* dist is now the match distance - 1 */
  24771. code = d_code(dist);
  24772. //Assert (code < D_CODES, "bad d_code");
  24773. send_code(s, code, dtree); /* send the distance code */
  24774. extra = extra_dbits[code];
  24775. if (extra !== 0) {
  24776. dist -= base_dist[code];
  24777. send_bits(s, dist, extra); /* send the extra distance bits */
  24778. }
  24779. } /* literal or match pair ? */
  24780. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24781. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24782. // "pendingBuf overflow");
  24783. } while (lx < s.last_lit);
  24784. }
  24785. send_code(s, END_BLOCK, ltree);
  24786. }
  24787. /* ===========================================================================
  24788. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24789. * Update the total bit length for the current block.
  24790. * IN assertion: the field freq is set for all tree elements.
  24791. * OUT assertions: the fields len and code are set to the optimal bit length
  24792. * and corresponding code. The length opt_len is updated; static_len is
  24793. * also updated if stree is not null. The field max_code is set.
  24794. */
  24795. function build_tree(s, desc)
  24796. // deflate_state *s;
  24797. // tree_desc *desc; /* the tree descriptor */
  24798. {
  24799. var tree = desc.dyn_tree;
  24800. var stree = desc.stat_desc.static_tree;
  24801. var has_stree = desc.stat_desc.has_stree;
  24802. var elems = desc.stat_desc.elems;
  24803. var n, m; /* iterate over heap elements */
  24804. var max_code = -1; /* largest code with non zero frequency */
  24805. var node; /* new node being created */
  24806. /* Construct the initial heap, with least frequent element in
  24807. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24808. * heap[0] is not used.
  24809. */
  24810. s.heap_len = 0;
  24811. s.heap_max = HEAP_SIZE;
  24812. for (n = 0; n < elems; n++) {
  24813. if (tree[n * 2]/*.Freq*/ !== 0) {
  24814. s.heap[++s.heap_len] = max_code = n;
  24815. s.depth[n] = 0;
  24816. } else {
  24817. tree[n*2 + 1]/*.Len*/ = 0;
  24818. }
  24819. }
  24820. /* The pkzip format requires that at least one distance code exists,
  24821. * and that at least one bit should be sent even if there is only one
  24822. * possible code. So to avoid special checks later on we force at least
  24823. * two codes of non zero frequency.
  24824. */
  24825. while (s.heap_len < 2) {
  24826. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24827. tree[node * 2]/*.Freq*/ = 1;
  24828. s.depth[node] = 0;
  24829. s.opt_len--;
  24830. if (has_stree) {
  24831. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24832. }
  24833. /* node is 0 or 1 so it does not have extra bits */
  24834. }
  24835. desc.max_code = max_code;
  24836. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24837. * establish sub-heaps of increasing lengths:
  24838. */
  24839. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24840. /* Construct the Huffman tree by repeatedly combining the least two
  24841. * frequent nodes.
  24842. */
  24843. node = elems; /* next internal node of the tree */
  24844. do {
  24845. //pqremove(s, tree, n); /* n = node of least frequency */
  24846. /*** pqremove ***/
  24847. n = s.heap[1/*SMALLEST*/];
  24848. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24849. pqdownheap(s, tree, 1/*SMALLEST*/);
  24850. /***/
  24851. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24852. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24853. s.heap[--s.heap_max] = m;
  24854. /* Create a new node father of n and m */
  24855. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24856. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24857. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24858. /* and insert the new node in the heap */
  24859. s.heap[1/*SMALLEST*/] = node++;
  24860. pqdownheap(s, tree, 1/*SMALLEST*/);
  24861. } while (s.heap_len >= 2);
  24862. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24863. /* At this point, the fields freq and dad are set. We can now
  24864. * generate the bit lengths.
  24865. */
  24866. gen_bitlen(s, desc);
  24867. /* The field len is now set, we can generate the bit codes */
  24868. gen_codes(tree, max_code, s.bl_count);
  24869. }
  24870. /* ===========================================================================
  24871. * Scan a literal or distance tree to determine the frequencies of the codes
  24872. * in the bit length tree.
  24873. */
  24874. function scan_tree(s, tree, max_code)
  24875. // deflate_state *s;
  24876. // ct_data *tree; /* the tree to be scanned */
  24877. // int max_code; /* and its largest code of non zero frequency */
  24878. {
  24879. var n; /* iterates over all tree elements */
  24880. var prevlen = -1; /* last emitted length */
  24881. var curlen; /* length of current code */
  24882. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24883. var count = 0; /* repeat count of the current code */
  24884. var max_count = 7; /* max repeat count */
  24885. var min_count = 4; /* min repeat count */
  24886. if (nextlen === 0) {
  24887. max_count = 138;
  24888. min_count = 3;
  24889. }
  24890. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24891. for (n = 0; n <= max_code; n++) {
  24892. curlen = nextlen;
  24893. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24894. if (++count < max_count && curlen === nextlen) {
  24895. continue;
  24896. } else if (count < min_count) {
  24897. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24898. } else if (curlen !== 0) {
  24899. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24900. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24901. } else if (count <= 10) {
  24902. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24903. } else {
  24904. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24905. }
  24906. count = 0;
  24907. prevlen = curlen;
  24908. if (nextlen === 0) {
  24909. max_count = 138;
  24910. min_count = 3;
  24911. } else if (curlen === nextlen) {
  24912. max_count = 6;
  24913. min_count = 3;
  24914. } else {
  24915. max_count = 7;
  24916. min_count = 4;
  24917. }
  24918. }
  24919. }
  24920. /* ===========================================================================
  24921. * Send a literal or distance tree in compressed form, using the codes in
  24922. * bl_tree.
  24923. */
  24924. function send_tree(s, tree, max_code)
  24925. // deflate_state *s;
  24926. // ct_data *tree; /* the tree to be scanned */
  24927. // int max_code; /* and its largest code of non zero frequency */
  24928. {
  24929. var n; /* iterates over all tree elements */
  24930. var prevlen = -1; /* last emitted length */
  24931. var curlen; /* length of current code */
  24932. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24933. var count = 0; /* repeat count of the current code */
  24934. var max_count = 7; /* max repeat count */
  24935. var min_count = 4; /* min repeat count */
  24936. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24937. if (nextlen === 0) {
  24938. max_count = 138;
  24939. min_count = 3;
  24940. }
  24941. for (n = 0; n <= max_code; n++) {
  24942. curlen = nextlen;
  24943. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24944. if (++count < max_count && curlen === nextlen) {
  24945. continue;
  24946. } else if (count < min_count) {
  24947. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24948. } else if (curlen !== 0) {
  24949. if (curlen !== prevlen) {
  24950. send_code(s, curlen, s.bl_tree);
  24951. count--;
  24952. }
  24953. //Assert(count >= 3 && count <= 6, " 3_6?");
  24954. send_code(s, REP_3_6, s.bl_tree);
  24955. send_bits(s, count-3, 2);
  24956. } else if (count <= 10) {
  24957. send_code(s, REPZ_3_10, s.bl_tree);
  24958. send_bits(s, count-3, 3);
  24959. } else {
  24960. send_code(s, REPZ_11_138, s.bl_tree);
  24961. send_bits(s, count-11, 7);
  24962. }
  24963. count = 0;
  24964. prevlen = curlen;
  24965. if (nextlen === 0) {
  24966. max_count = 138;
  24967. min_count = 3;
  24968. } else if (curlen === nextlen) {
  24969. max_count = 6;
  24970. min_count = 3;
  24971. } else {
  24972. max_count = 7;
  24973. min_count = 4;
  24974. }
  24975. }
  24976. }
  24977. /* ===========================================================================
  24978. * Construct the Huffman tree for the bit lengths and return the index in
  24979. * bl_order of the last bit length code to send.
  24980. */
  24981. function build_bl_tree(s) {
  24982. var max_blindex; /* index of last bit length code of non zero freq */
  24983. /* Determine the bit length frequencies for literal and distance trees */
  24984. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24985. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24986. /* Build the bit length tree: */
  24987. build_tree(s, s.bl_desc);
  24988. /* opt_len now includes the length of the tree representations, except
  24989. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24990. */
  24991. /* Determine the number of bit length codes to send. The pkzip format
  24992. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24993. * 3 but the actual value used is 4.)
  24994. */
  24995. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24996. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24997. break;
  24998. }
  24999. }
  25000. /* Update opt_len to include the bit length tree and counts */
  25001. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  25002. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  25003. // s->opt_len, s->static_len));
  25004. return max_blindex;
  25005. }
  25006. /* ===========================================================================
  25007. * Send the header for a block using dynamic Huffman trees: the counts, the
  25008. * lengths of the bit length codes, the literal tree and the distance tree.
  25009. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  25010. */
  25011. function send_all_trees(s, lcodes, dcodes, blcodes)
  25012. // deflate_state *s;
  25013. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  25014. {
  25015. var rank; /* index in bl_order */
  25016. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  25017. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  25018. // "too many codes");
  25019. //Tracev((stderr, "\nbl counts: "));
  25020. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  25021. send_bits(s, dcodes-1, 5);
  25022. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  25023. for (rank = 0; rank < blcodes; rank++) {
  25024. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  25025. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  25026. }
  25027. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  25028. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  25029. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  25030. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  25031. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  25032. }
  25033. /* ===========================================================================
  25034. * Check if the data type is TEXT or BINARY, using the following algorithm:
  25035. * - TEXT if the two conditions below are satisfied:
  25036. * a) There are no non-portable control characters belonging to the
  25037. * "black list" (0..6, 14..25, 28..31).
  25038. * b) There is at least one printable character belonging to the
  25039. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  25040. * - BINARY otherwise.
  25041. * - The following partially-portable control characters form a
  25042. * "gray list" that is ignored in this detection algorithm:
  25043. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  25044. * IN assertion: the fields Freq of dyn_ltree are set.
  25045. */
  25046. function detect_data_type(s) {
  25047. /* black_mask is the bit mask of black-listed bytes
  25048. * set bits 0..6, 14..25, and 28..31
  25049. * 0xf3ffc07f = binary 11110011111111111100000001111111
  25050. */
  25051. var black_mask = 0xf3ffc07f;
  25052. var n;
  25053. /* Check for non-textual ("black-listed") bytes. */
  25054. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  25055. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  25056. return Z_BINARY;
  25057. }
  25058. }
  25059. /* Check for textual ("white-listed") bytes. */
  25060. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  25061. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  25062. return Z_TEXT;
  25063. }
  25064. for (n = 32; n < LITERALS; n++) {
  25065. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  25066. return Z_TEXT;
  25067. }
  25068. }
  25069. /* There are no "black-listed" or "white-listed" bytes:
  25070. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  25071. */
  25072. return Z_BINARY;
  25073. }
  25074. var static_init_done = false;
  25075. /* ===========================================================================
  25076. * Initialize the tree data structures for a new zlib stream.
  25077. */
  25078. function _tr_init(s)
  25079. {
  25080. if (!static_init_done) {
  25081. tr_static_init();
  25082. static_init_done = true;
  25083. }
  25084. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  25085. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  25086. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  25087. s.bi_buf = 0;
  25088. s.bi_valid = 0;
  25089. /* Initialize the first block of the first file: */
  25090. init_block(s);
  25091. }
  25092. /* ===========================================================================
  25093. * Send a stored block
  25094. */
  25095. function _tr_stored_block(s, buf, stored_len, last)
  25096. //DeflateState *s;
  25097. //charf *buf; /* input block */
  25098. //ulg stored_len; /* length of input block */
  25099. //int last; /* one if this is the last block for a file */
  25100. {
  25101. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  25102. copy_block(s, buf, stored_len, true); /* with header */
  25103. }
  25104. /* ===========================================================================
  25105. * Send one empty static block to give enough lookahead for inflate.
  25106. * This takes 10 bits, of which 7 may remain in the bit buffer.
  25107. */
  25108. function _tr_align(s) {
  25109. send_bits(s, STATIC_TREES<<1, 3);
  25110. send_code(s, END_BLOCK, static_ltree);
  25111. bi_flush(s);
  25112. }
  25113. /* ===========================================================================
  25114. * Determine the best encoding for the current block: dynamic trees, static
  25115. * trees or store, and output the encoded block to the zip file.
  25116. */
  25117. function _tr_flush_block(s, buf, stored_len, last)
  25118. //DeflateState *s;
  25119. //charf *buf; /* input block, or NULL if too old */
  25120. //ulg stored_len; /* length of input block */
  25121. //int last; /* one if this is the last block for a file */
  25122. {
  25123. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  25124. var max_blindex = 0; /* index of last bit length code of non zero freq */
  25125. /* Build the Huffman trees unless a stored block is forced */
  25126. if (s.level > 0) {
  25127. /* Check if the file is binary or text */
  25128. if (s.strm.data_type === Z_UNKNOWN) {
  25129. s.strm.data_type = detect_data_type(s);
  25130. }
  25131. /* Construct the literal and distance trees */
  25132. build_tree(s, s.l_desc);
  25133. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  25134. // s->static_len));
  25135. build_tree(s, s.d_desc);
  25136. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  25137. // s->static_len));
  25138. /* At this point, opt_len and static_len are the total bit lengths of
  25139. * the compressed block data, excluding the tree representations.
  25140. */
  25141. /* Build the bit length tree for the above two trees, and get the index
  25142. * in bl_order of the last bit length code to send.
  25143. */
  25144. max_blindex = build_bl_tree(s);
  25145. /* Determine the best encoding. Compute the block lengths in bytes. */
  25146. opt_lenb = (s.opt_len+3+7) >>> 3;
  25147. static_lenb = (s.static_len+3+7) >>> 3;
  25148. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  25149. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  25150. // s->last_lit));
  25151. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  25152. } else {
  25153. // Assert(buf != (char*)0, "lost buf");
  25154. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  25155. }
  25156. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  25157. /* 4: two words for the lengths */
  25158. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  25159. * Otherwise we can't have processed more than WSIZE input bytes since
  25160. * the last block flush, because compression would have been
  25161. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  25162. * transform a block into a stored block.
  25163. */
  25164. _tr_stored_block(s, buf, stored_len, last);
  25165. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  25166. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  25167. compress_block(s, static_ltree, static_dtree);
  25168. } else {
  25169. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  25170. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  25171. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  25172. }
  25173. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  25174. /* The above check is made mod 2^32, for files larger than 512 MB
  25175. * and uLong implemented on 32 bits.
  25176. */
  25177. init_block(s);
  25178. if (last) {
  25179. bi_windup(s);
  25180. }
  25181. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  25182. // s->compressed_len-7*last));
  25183. }
  25184. /* ===========================================================================
  25185. * Save the match info and tally the frequency counts. Return true if
  25186. * the current block must be flushed.
  25187. */
  25188. function _tr_tally(s, dist, lc)
  25189. // deflate_state *s;
  25190. // unsigned dist; /* distance of matched string */
  25191. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  25192. {
  25193. //var out_length, in_length, dcode;
  25194. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  25195. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  25196. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  25197. s.last_lit++;
  25198. if (dist === 0) {
  25199. /* lc is the unmatched char */
  25200. s.dyn_ltree[lc*2]/*.Freq*/++;
  25201. } else {
  25202. s.matches++;
  25203. /* Here, lc is the match length - MIN_MATCH */
  25204. dist--; /* dist = match distance - 1 */
  25205. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  25206. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  25207. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  25208. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  25209. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  25210. }
  25211. // (!) This block is disabled in zlib defailts,
  25212. // don't enable it for binary compatibility
  25213. //#ifdef TRUNCATE_BLOCK
  25214. // /* Try to guess if it is profitable to stop the current block here */
  25215. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  25216. // /* Compute an upper bound for the compressed length */
  25217. // out_length = s.last_lit*8;
  25218. // in_length = s.strstart - s.block_start;
  25219. //
  25220. // for (dcode = 0; dcode < D_CODES; dcode++) {
  25221. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  25222. // }
  25223. // out_length >>>= 3;
  25224. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  25225. // // s->last_lit, in_length, out_length,
  25226. // // 100L - out_length*100L/in_length));
  25227. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  25228. // return true;
  25229. // }
  25230. // }
  25231. //#endif
  25232. return (s.last_lit === s.lit_bufsize-1);
  25233. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25234. * on 16 bit machines and because stored blocks are restricted to
  25235. * 64K-1 bytes.
  25236. */
  25237. }
  25238. exports._tr_init = _tr_init;
  25239. exports._tr_stored_block = _tr_stored_block;
  25240. exports._tr_flush_block = _tr_flush_block;
  25241. exports._tr_tally = _tr_tally;
  25242. exports._tr_align = _tr_align;
  25243. },{"../utils/common":75}],87:[function(require,module,exports){
  25244. 'use strict';
  25245. function ZStream() {
  25246. /* next input byte */
  25247. this.input = null; // JS specific, because we have no pointers
  25248. this.next_in = 0;
  25249. /* number of bytes available at input */
  25250. this.avail_in = 0;
  25251. /* total number of input bytes read so far */
  25252. this.total_in = 0;
  25253. /* next output byte should be put there */
  25254. this.output = null; // JS specific, because we have no pointers
  25255. this.next_out = 0;
  25256. /* remaining free space at output */
  25257. this.avail_out = 0;
  25258. /* total number of bytes output so far */
  25259. this.total_out = 0;
  25260. /* last error message, NULL if no error */
  25261. this.msg = ''/*Z_NULL*/;
  25262. /* not visible by applications */
  25263. this.state = null;
  25264. /* best guess about the data type: binary or text */
  25265. this.data_type = 2/*Z_UNKNOWN*/;
  25266. /* adler32 value of the uncompressed data */
  25267. this.adler = 0;
  25268. }
  25269. module.exports = ZStream;
  25270. },{}],88:[function(require,module,exports){
  25271. module.exports = require('./lib/retry');
  25272. },{"./lib/retry":89}],89:[function(require,module,exports){
  25273. var RetryOperation = require('./retry_operation');
  25274. exports.operation = function(options) {
  25275. var timeouts = exports.timeouts(options);
  25276. return new RetryOperation(timeouts);
  25277. };
  25278. exports.timeouts = function(options) {
  25279. if (options instanceof Array) {
  25280. return [].concat(options);
  25281. }
  25282. var opts = {
  25283. retries: 10,
  25284. factor: 2,
  25285. minTimeout: 1 * 1000,
  25286. maxTimeout: Infinity,
  25287. randomize: false
  25288. };
  25289. for (var key in options) {
  25290. opts[key] = options[key];
  25291. }
  25292. if (opts.minTimeout > opts.maxTimeout) {
  25293. throw new Error('minTimeout is greater than maxTimeout');
  25294. }
  25295. var timeouts = [];
  25296. for (var i = 0; i < opts.retries; i++) {
  25297. timeouts.push(this._createTimeout(i, opts));
  25298. }
  25299. // sort the array numerically ascending
  25300. timeouts.sort(function(a,b) {
  25301. return a - b;
  25302. });
  25303. return timeouts;
  25304. };
  25305. exports._createTimeout = function(attempt, opts) {
  25306. var random = (opts.randomize)
  25307. ? (Math.random() + 1)
  25308. : 1;
  25309. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25310. timeout = Math.min(timeout, opts.maxTimeout);
  25311. return timeout;
  25312. };
  25313. },{"./retry_operation":90}],90:[function(require,module,exports){
  25314. function RetryOperation(timeouts) {
  25315. this._timeouts = timeouts;
  25316. this._fn = null;
  25317. this._errors = [];
  25318. this._attempts = 1;
  25319. this._operationTimeout = null;
  25320. this._operationTimeoutCb = null;
  25321. this._timeout = null;
  25322. }
  25323. module.exports = RetryOperation;
  25324. RetryOperation.prototype.retry = function(err) {
  25325. if (this._timeout) {
  25326. clearTimeout(this._timeout);
  25327. }
  25328. if (!err) {
  25329. return false;
  25330. }
  25331. this._errors.push(err);
  25332. var timeout = this._timeouts.shift();
  25333. if (timeout === undefined) {
  25334. return false;
  25335. }
  25336. this._attempts++;
  25337. var self = this;
  25338. setTimeout(function() {
  25339. self._fn(self._attempts);
  25340. if (self._operationTimeoutCb) {
  25341. self._timeout = setTimeout(function() {
  25342. self._operationTimeoutCb(self._attempts);
  25343. }, self._operationTimeout);
  25344. }
  25345. }, timeout);
  25346. return true;
  25347. };
  25348. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25349. this._fn = fn;
  25350. if (timeoutOps) {
  25351. if (timeoutOps.timeout) {
  25352. this._operationTimeout = timeoutOps.timeout;
  25353. }
  25354. if (timeoutOps.cb) {
  25355. this._operationTimeoutCb = timeoutOps.cb;
  25356. }
  25357. }
  25358. this._fn(this._attempts);
  25359. var self = this;
  25360. if (this._operationTimeoutCb) {
  25361. this._timeout = setTimeout(function() {
  25362. self._operationTimeoutCb();
  25363. }, self._operationTimeout);
  25364. }
  25365. };
  25366. RetryOperation.prototype.try = function(fn) {
  25367. console.log('Using RetryOperation.try() is deprecated');
  25368. this.attempt(fn);
  25369. };
  25370. RetryOperation.prototype.start = function(fn) {
  25371. console.log('Using RetryOperation.start() is deprecated');
  25372. this.attempt(fn);
  25373. };
  25374. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25375. RetryOperation.prototype.errors = function() {
  25376. return this._errors;
  25377. };
  25378. RetryOperation.prototype.attempts = function() {
  25379. return this._attempts;
  25380. };
  25381. RetryOperation.prototype.mainError = function() {
  25382. if (this._errors.length === 0) {
  25383. return null;
  25384. }
  25385. var counts = {};
  25386. var mainError = null;
  25387. var mainErrorCount = 0;
  25388. for (var i = 0; i < this._errors.length; i++) {
  25389. var error = this._errors[i];
  25390. var message = error.message;
  25391. var count = (counts[message] || 0) + 1;
  25392. counts[message] = count;
  25393. if (count >= mainErrorCount) {
  25394. mainError = error;
  25395. mainErrorCount = count;
  25396. }
  25397. }
  25398. return mainError;
  25399. };
  25400. },{}],91:[function(require,module,exports){
  25401. module.exports = function arrayEquals(array) {
  25402. // if the other array is a falsy value, return
  25403. if (!array)
  25404. return false;
  25405. // compare lengths - can save a lot of time
  25406. if (this.length != array.length)
  25407. return false;
  25408. for (var i = 0, l = this.length; i < l; i++) {
  25409. // Check if we have nested arrays
  25410. if (this[i] instanceof Array && array[i] instanceof Array) {
  25411. // recurse into the nested arrays
  25412. if (!arrayEquals.apply(this[i], [array[i]]))
  25413. return false;
  25414. } else if (this[i] != array[i]) {
  25415. // Warning - two different object instances will never be equal:
  25416. // {x:20} != {x:20}
  25417. return false;
  25418. }
  25419. }
  25420. return true;
  25421. }
  25422. },{}],92:[function(require,module,exports){
  25423. exports.Interop = require('./interop');
  25424. },{"./interop":93}],93:[function(require,module,exports){
  25425. "use strict";
  25426. var transform = require('./transform');
  25427. var arrayEquals = require('./array-equals');
  25428. function Interop() {
  25429. /**
  25430. * This map holds the most recent Unified Plan offer/answer SDP that was
  25431. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25432. * the SDP string as values.
  25433. *
  25434. * @type {{}}
  25435. */
  25436. this.cache = {};
  25437. }
  25438. module.exports = Interop;
  25439. /**
  25440. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25441. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25442. * application.
  25443. *
  25444. * @param desc
  25445. * @returns {*}
  25446. */
  25447. Interop.prototype.toPlanB = function(desc) {
  25448. //#region Preliminary input validation.
  25449. if (typeof desc !== 'object' || desc === null ||
  25450. typeof desc.sdp !== 'string') {
  25451. console.warn('An empty description was passed as an argument.');
  25452. return desc;
  25453. }
  25454. // Objectify the SDP for easier manipulation.
  25455. var session = transform.parse(desc.sdp);
  25456. // If the SDP contains no media, there's nothing to transform.
  25457. if (typeof session.media === 'undefined' ||
  25458. !Array.isArray(session.media) || session.media.length === 0) {
  25459. console.warn('The description has no media.');
  25460. return desc;
  25461. }
  25462. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25463. // SDP has a video, an audio and a data "channel" at most.
  25464. if (session.media.length <= 3 && session.media.every(function(m) {
  25465. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25466. })) {
  25467. console.warn('This description does not look like Unified Plan.');
  25468. return desc;
  25469. }
  25470. //#endregion
  25471. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25472. // -> Unified Plan transformation.
  25473. this.cache[desc.type] = desc.sdp;
  25474. //#region Convert from Unified Plan to Plan B.
  25475. // We rebuild the session.media array.
  25476. var media = session.media;
  25477. session.media = [];
  25478. // Associative array that maps channel types to channel objects for fast
  25479. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25480. // obj.
  25481. var type2bl = {};
  25482. // Used to build the group:BUNDLE value after the channels construction
  25483. // loop.
  25484. var types = [];
  25485. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25486. media.forEach(function(unifiedLine) {
  25487. // rtcp-mux is required in the Plan B SDP.
  25488. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25489. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25490. unifiedLine.direction !== 'inactive') {
  25491. throw new Error('Cannot convert to Plan B because m-lines ' +
  25492. 'without the rtcp-mux attribute were found.');
  25493. }
  25494. if (unifiedLine.type === 'application') {
  25495. session.media.push(unifiedLine);
  25496. types.push(unifiedLine.mid);
  25497. return;
  25498. }
  25499. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25500. // as the channel basis.
  25501. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25502. type2bl[unifiedLine.type] = unifiedLine;
  25503. }
  25504. // Add sources to the channel and handle a=msid.
  25505. if (typeof unifiedLine.sources === 'object') {
  25506. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25507. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25508. type2bl[unifiedLine.type].sources = {};
  25509. // Assign the sources to the channel.
  25510. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25511. if (typeof unifiedLine.msid !== 'undefined') {
  25512. // In Plan B the msid is an SSRC attribute. Also, we don't
  25513. // care about the obsolete label and mslabel attributes.
  25514. //
  25515. // Note that it is not guaranteed that the unifiedLine will have
  25516. // an msid. recvonly channels in particular don't have one.
  25517. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25518. }
  25519. // NOTE ssrcs in ssrc groups will share msids, as
  25520. // draft-uberti-rtcweb-plan-00 mandates.
  25521. });
  25522. }
  25523. // Add ssrc groups to the channel.
  25524. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25525. Array.isArray(unifiedLine.ssrcGroups)) {
  25526. // Create the ssrcGroups array, if it's not defined.
  25527. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25528. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25529. type2bl[unifiedLine.type].ssrcGroups = [];
  25530. }
  25531. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25532. }
  25533. if (type2bl[unifiedLine.type] === unifiedLine) {
  25534. // Copy ICE related stuff from the principal media line.
  25535. unifiedLine.candidates = media[0].candidates;
  25536. unifiedLine.iceUfrag = media[0].iceUfrag;
  25537. unifiedLine.icePwd = media[0].icePwd;
  25538. unifiedLine.fingerprint = media[0].fingerprint;
  25539. // Plan B mids are in ['audio', 'video', 'data']
  25540. unifiedLine.mid = unifiedLine.type;
  25541. // Plan B doesn't support/need the bundle-only attribute.
  25542. delete unifiedLine.bundleOnly;
  25543. // In Plan B the msid is an SSRC attribute.
  25544. delete unifiedLine.msid;
  25545. // Used to build the group:BUNDLE value after this loop.
  25546. types.push(unifiedLine.type);
  25547. // Add the channel to the new media array.
  25548. session.media.push(unifiedLine);
  25549. }
  25550. });
  25551. // We regenerate the BUNDLE group with the new mids.
  25552. session.groups.some(function(group) {
  25553. if (group.type === 'BUNDLE') {
  25554. group.mids = types.join(' ');
  25555. return true;
  25556. }
  25557. });
  25558. // msid semantic
  25559. session.msidSemantic = {
  25560. semantic: 'WMS',
  25561. token: '*'
  25562. };
  25563. var resStr = transform.write(session);
  25564. return new RTCSessionDescription({
  25565. type: desc.type,
  25566. sdp: resStr
  25567. });
  25568. //#endregion
  25569. };
  25570. /**
  25571. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25572. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25573. * to FF.
  25574. *
  25575. * @param desc
  25576. * @returns {*}
  25577. */
  25578. Interop.prototype.toUnifiedPlan = function(desc) {
  25579. //#region Preliminary input validation.
  25580. if (typeof desc !== 'object' || desc === null ||
  25581. typeof desc.sdp !== 'string') {
  25582. console.warn('An empty description was passed as an argument.');
  25583. return desc;
  25584. }
  25585. var session = transform.parse(desc.sdp);
  25586. // If the SDP contains no media, there's nothing to transform.
  25587. if (typeof session.media === 'undefined' ||
  25588. !Array.isArray(session.media) || session.media.length === 0) {
  25589. console.warn('The description has no media.');
  25590. return desc;
  25591. }
  25592. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25593. // a video, an audio and a data "channel" at most.
  25594. if (session.media.length > 3 || !session.media.every(function(m) {
  25595. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25596. })) {
  25597. console.warn('This description does not look like Plan B.');
  25598. return desc;
  25599. }
  25600. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25601. var mids = [];
  25602. session.media.forEach(function(m) {
  25603. mids.push(m.mid);
  25604. });
  25605. var hasBundle = false;
  25606. if (typeof session.groups !== 'undefined' &&
  25607. Array.isArray(session.groups)) {
  25608. hasBundle = session.groups.every(function(g) {
  25609. return g.type !== 'BUNDLE' ||
  25610. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25611. });
  25612. }
  25613. if (!hasBundle) {
  25614. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25615. " are not bundled were found.");
  25616. }
  25617. //#endregion
  25618. //#region Convert from Plan B to Unified Plan.
  25619. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25620. // rebuild an equivalent Unified Plan offer/answer.
  25621. //
  25622. // For example, if this is a local answer (in Unified Plan style) that we
  25623. // convert to Plan B prior to handing it over to the application (the
  25624. // PeerConnection wrapper called us, for instance, after a successful
  25625. // createAnswer), we want to remember the m-line at which we've seen the
  25626. // (local) SSRC. That's because when the application wants to do call the
  25627. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25628. // Unified Plan), we need to know to which m-line to assign the (local)
  25629. // SSRC. We also need to know all the other m-lines that the original
  25630. // answer had and include them in the transformed answer as well.
  25631. //
  25632. // Another example is if this is a remote offer that we convert to Plan B
  25633. // prior to giving it to the application, we want to remember the mid at
  25634. // which we've seen the (remote) SSRC.
  25635. //
  25636. // In the iteration that follows, we use the cached Unified Plan (if it
  25637. // exists) to assign mids to ssrcs.
  25638. var cached;
  25639. if (typeof this.cache[desc.type] !== 'undefined') {
  25640. cached = transform.parse(this.cache[desc.type]);
  25641. }
  25642. // A helper map that sends mids to m-line objects. We use it later to
  25643. // rebuild the Unified Plan style session.media array.
  25644. var mid2ul = {};
  25645. session.media.forEach(function(bLine) {
  25646. if ((typeof bLine.rtcpMux !== 'string' ||
  25647. bLine.rtcpMux !== 'rtcp-mux') &&
  25648. bLine.direction !== 'inactive') {
  25649. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25650. "without the rtcp-mux attribute were found.");
  25651. }
  25652. if (bLine.type === 'application') {
  25653. mid2ul[bLine.mid] = bLine;
  25654. return;
  25655. }
  25656. // With rtcp-mux and bundle all the channels should have the same ICE
  25657. // stuff.
  25658. var sources = bLine.sources;
  25659. var ssrcGroups = bLine.ssrcGroups;
  25660. var candidates = bLine.candidates;
  25661. var iceUfrag = bLine.iceUfrag;
  25662. var icePwd = bLine.icePwd;
  25663. var fingerprint = bLine.fingerprint;
  25664. var port = bLine.port;
  25665. // We'll use the "bLine" object as a prototype for each new "mLine"
  25666. // that we create, but first we need to clean it up a bit.
  25667. delete bLine.sources;
  25668. delete bLine.ssrcGroups;
  25669. delete bLine.candidates;
  25670. delete bLine.iceUfrag;
  25671. delete bLine.icePwd;
  25672. delete bLine.fingerprint;
  25673. delete bLine.port;
  25674. delete bLine.mid;
  25675. // inverted ssrc group map
  25676. var ssrc2group = {};
  25677. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25678. ssrcGroups.forEach(function (ssrcGroup) {
  25679. // TODO(gp) find out how to receive simulcast with FF. For the
  25680. // time being, hide it.
  25681. if (ssrcGroup.semantics === 'SIM') {
  25682. return;
  25683. }
  25684. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25685. Array.isArray(ssrcGroup.ssrcs)) {
  25686. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25687. if (typeof ssrc2group[ssrc] === 'undefined') {
  25688. ssrc2group[ssrc] = [];
  25689. }
  25690. ssrc2group[ssrc].push(ssrcGroup);
  25691. });
  25692. }
  25693. });
  25694. }
  25695. // ssrc to m-line index.
  25696. var ssrc2ml = {};
  25697. if (typeof sources === 'object') {
  25698. // Explode the Plan B channel sources with one m-line per source.
  25699. Object.keys(sources).forEach(function(ssrc) {
  25700. // The (unified) m-line for this SSRC. We either create it from
  25701. // scratch or, if it's a grouped SSRC, we re-use a related
  25702. // mline. In other words, if the source is grouped with another
  25703. // source, put the two together in the same m-line.
  25704. var unifiedLine;
  25705. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25706. Array.isArray(ssrc2group[ssrc])) {
  25707. ssrc2group[ssrc].some(function (ssrcGroup) {
  25708. // ssrcGroup.ssrcs *is* an Array, no need to check
  25709. // again here.
  25710. return ssrcGroup.ssrcs.some(function (related) {
  25711. if (typeof ssrc2ml[related] === 'object') {
  25712. unifiedLine = ssrc2ml[related];
  25713. return true;
  25714. }
  25715. });
  25716. });
  25717. }
  25718. if (typeof unifiedLine === 'object') {
  25719. // the m-line already exists. Just add the source.
  25720. unifiedLine.sources[ssrc] = sources[ssrc];
  25721. delete sources[ssrc].msid;
  25722. } else {
  25723. // Use the "bLine" as a prototype for the "unifiedLine".
  25724. unifiedLine = Object.create(bLine);
  25725. ssrc2ml[ssrc] = unifiedLine;
  25726. if (typeof sources[ssrc].msid !== 'undefined') {
  25727. // Assign the msid of the source to the m-line. Note
  25728. // that it is not guaranteed that the source will have
  25729. // msid. In particular "recvonly" sources don't have an
  25730. // msid. Note that "recvonly" is a term only defined
  25731. // for m-lines.
  25732. unifiedLine.msid = sources[ssrc].msid;
  25733. delete sources[ssrc].msid;
  25734. }
  25735. // We assign one SSRC per media line.
  25736. unifiedLine.sources = {};
  25737. unifiedLine.sources[ssrc] = sources[ssrc];
  25738. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25739. // Use the cached Unified Plan SDP (if it exists) to assign
  25740. // SSRCs to mids.
  25741. if (typeof cached !== 'undefined' &&
  25742. typeof cached.media !== 'undefined' &&
  25743. Array.isArray(cached.media)) {
  25744. cached.media.forEach(function (m) {
  25745. if (typeof m.sources === 'object') {
  25746. Object.keys(m.sources).forEach(function (s) {
  25747. if (s === ssrc) {
  25748. unifiedLine.mid = m.mid;
  25749. }
  25750. });
  25751. }
  25752. });
  25753. }
  25754. if (typeof unifiedLine.mid === 'undefined') {
  25755. // If this is an SSRC that we see for the first time
  25756. // assign it a new mid. This is typically the case when
  25757. // this method is called to transform a remote
  25758. // description for the first time or when there is a
  25759. // new SSRC in the remote description because a new
  25760. // peer has joined the conference. Local SSRCs should
  25761. // have already been added to the map in the toPlanB
  25762. // method.
  25763. //
  25764. // Because FF generates answers in Unified Plan style,
  25765. // we MUST already have a cached answer with all the
  25766. // local SSRCs mapped to some m-line/mid.
  25767. if (desc.type === 'answer') {
  25768. throw new Error("An unmapped SSRC was found.");
  25769. }
  25770. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25771. }
  25772. // Include the candidates in the 1st media line.
  25773. unifiedLine.candidates = candidates;
  25774. unifiedLine.iceUfrag = iceUfrag;
  25775. unifiedLine.icePwd = icePwd;
  25776. unifiedLine.fingerprint = fingerprint;
  25777. unifiedLine.port = port;
  25778. mid2ul[unifiedLine.mid] = unifiedLine;
  25779. }
  25780. });
  25781. }
  25782. });
  25783. // Rebuild the media array in the right order and add the missing mLines
  25784. // (missing from the Plan B SDP).
  25785. session.media = [];
  25786. mids = []; // reuse
  25787. if (desc.type === 'answer') {
  25788. // The media lines in the answer must match the media lines in the
  25789. // offer. The order is important too. Here we assume that Firefox is the
  25790. // answerer, so we merely have to use the reconstructed (unified) answer
  25791. // to update the cached (unified) answer accordingly.
  25792. //
  25793. // In the general case, one would have to use the cached (unified) offer
  25794. // to find the m-lines that are missing from the reconstructed answer,
  25795. // potentially grabbing them from the cached (unified) answer. One has
  25796. // to be carefull with this approach because inactive m-lines do not
  25797. // always have an mid, making it tricky (impossible?) to find where
  25798. // exactly and which m-lines are missing from the reconstructed answer.
  25799. for (var i = 0; i < cached.media.length; i++) {
  25800. var unifiedLine = cached.media[i];
  25801. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25802. // The mid isn't in the reconstructed (unified) answer.
  25803. // This is either a (unified) m-line containing a remote
  25804. // track only, or a (unified) m-line containing a remote
  25805. // track and a local track that has been removed.
  25806. // In either case, it MUST exist in the cached
  25807. // (unified) answer.
  25808. //
  25809. // In case this is a removed local track, clean-up
  25810. // the (unified) m-line and make sure it's 'recvonly' or
  25811. // 'inactive'.
  25812. delete unifiedLine.msid;
  25813. delete unifiedLine.sources;
  25814. delete unifiedLine.ssrcGroups;
  25815. if (!unifiedLine.direction
  25816. || unifiedLine.direction === 'sendrecv')
  25817. unifiedLine.direction = 'recvonly';
  25818. if (!unifiedLine.direction
  25819. || unifiedLine.direction === 'sendonly')
  25820. unifiedLine.direction = 'inactive';
  25821. } else {
  25822. // This is an (unified) m-line/channel that contains a local
  25823. // track (sendrecv or sendonly channel) or it's a unified
  25824. // recvonly m-line/channel. In either case, since we're
  25825. // going from PlanB -> Unified Plan this m-line MUST
  25826. // exist in the cached answer.
  25827. }
  25828. session.media.push(unifiedLine);
  25829. if (typeof unifiedLine.mid === 'string') {
  25830. // inactive lines don't/may not have an mid.
  25831. mids.push(unifiedLine.mid);
  25832. }
  25833. }
  25834. } else {
  25835. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25836. // under any circumstances. If we are no longer interested in sending a
  25837. // track, we just remove the msid and ssrc attributes and set it to
  25838. // either a=recvonly (as the reofferer, we must use recvonly if the
  25839. // other side was previously sending on the m-section, but we can also
  25840. // leave the possibility open if it wasn't previously in use), or
  25841. // a=inacive.
  25842. if (typeof cached !== 'undefined' &&
  25843. typeof cached.media !== 'undefined' &&
  25844. Array.isArray(cached.media)) {
  25845. cached.media.forEach(function(unifiedLine) {
  25846. mids.push(unifiedLine.mid);
  25847. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25848. session.media.push(mid2ul[unifiedLine.mid]);
  25849. } else {
  25850. delete unifiedLine.msid;
  25851. delete unifiedLine.sources;
  25852. delete unifiedLine.ssrcGroups;
  25853. if (!unifiedLine.direction
  25854. || unifiedLine.direction === 'sendrecv')
  25855. unifiedLine.direction = 'recvonly';
  25856. if (!unifiedLine.direction
  25857. || unifiedLine.direction === 'sendonly')
  25858. unifiedLine.direction = 'inactive';
  25859. session.media.push(unifiedLine);
  25860. }
  25861. });
  25862. }
  25863. // Add all the remaining (new) m-lines of the transformed SDP.
  25864. Object.keys(mid2ul).forEach(function(mid) {
  25865. if (mids.indexOf(mid) === -1) {
  25866. mids.push(mid);
  25867. if (typeof mid2ul[mid].direction === 'recvonly') {
  25868. // This is a remote recvonly channel. Add its SSRC to the
  25869. // appropriate sendrecv or sendonly channel.
  25870. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25871. session.media.some(function (unifiedLine) {
  25872. if ((unifiedLine.direction === 'sendrecv' ||
  25873. unifiedLine.direction === 'sendonly') &&
  25874. unifiedLine.type === mid2ul[mid].type) {
  25875. // mid2ul[mid] shouldn't have any ssrc-groups
  25876. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25877. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25878. });
  25879. return true;
  25880. }
  25881. });
  25882. } else {
  25883. session.media.push(mid2ul[mid]);
  25884. }
  25885. }
  25886. });
  25887. }
  25888. // We regenerate the BUNDLE group (since we regenerated the mids)
  25889. session.groups.some(function(group) {
  25890. if (group.type === 'BUNDLE') {
  25891. group.mids = mids.join(' ');
  25892. return true;
  25893. }
  25894. });
  25895. // msid semantic
  25896. session.msidSemantic = {
  25897. semantic: 'WMS',
  25898. token: '*'
  25899. };
  25900. var resStr = transform.write(session);
  25901. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25902. // function.
  25903. this.cache[desc.type] = resStr;
  25904. return new RTCSessionDescription({
  25905. type: desc.type,
  25906. sdp: resStr
  25907. });
  25908. //#endregion
  25909. };
  25910. },{"./array-equals":91,"./transform":94}],94:[function(require,module,exports){
  25911. var transform = require('sdp-transform');
  25912. exports.write = function(session, opts) {
  25913. if (typeof session !== 'undefined' &&
  25914. typeof session.media !== 'undefined' &&
  25915. Array.isArray(session.media)) {
  25916. session.media.forEach(function (mLine) {
  25917. // expand sources to ssrcs
  25918. if (typeof mLine.sources !== 'undefined' &&
  25919. Object.keys(mLine.sources).length !== 0) {
  25920. mLine.ssrcs = [];
  25921. Object.keys(mLine.sources).forEach(function (ssrc) {
  25922. var source = mLine.sources[ssrc];
  25923. Object.keys(source).forEach(function (attribute) {
  25924. mLine.ssrcs.push({
  25925. id: ssrc,
  25926. attribute: attribute,
  25927. value: source[attribute]
  25928. });
  25929. });
  25930. });
  25931. delete mLine.sources;
  25932. }
  25933. // join ssrcs in ssrc groups
  25934. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25935. Array.isArray(mLine.ssrcGroups)) {
  25936. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25937. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25938. Array.isArray(ssrcGroup.ssrcs)) {
  25939. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25940. }
  25941. });
  25942. }
  25943. });
  25944. }
  25945. // join group mids
  25946. if (typeof session !== 'undefined' &&
  25947. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25948. session.groups.forEach(function (g) {
  25949. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25950. g.mids = g.mids.join(' ');
  25951. }
  25952. });
  25953. }
  25954. return transform.write(session, opts);
  25955. };
  25956. exports.parse = function(sdp) {
  25957. var session = transform.parse(sdp);
  25958. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25959. Array.isArray(session.media)) {
  25960. session.media.forEach(function (mLine) {
  25961. // group sources attributes by ssrc
  25962. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25963. mLine.sources = {};
  25964. mLine.ssrcs.forEach(function (ssrc) {
  25965. if (!mLine.sources[ssrc.id])
  25966. mLine.sources[ssrc.id] = {};
  25967. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25968. });
  25969. delete mLine.ssrcs;
  25970. }
  25971. // split ssrcs in ssrc groups
  25972. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25973. Array.isArray(mLine.ssrcGroups)) {
  25974. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25975. if (typeof ssrcGroup.ssrcs === 'string') {
  25976. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25977. }
  25978. });
  25979. }
  25980. });
  25981. }
  25982. // split group mids
  25983. if (typeof session !== 'undefined' &&
  25984. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25985. session.groups.forEach(function (g) {
  25986. if (typeof g.mids === 'string') {
  25987. g.mids = g.mids.split(' ');
  25988. }
  25989. });
  25990. }
  25991. return session;
  25992. };
  25993. },{"sdp-transform":96}],95:[function(require,module,exports){
  25994. var grammar = module.exports = {
  25995. v: [{
  25996. name: 'version',
  25997. reg: /^(\d*)$/
  25998. }],
  25999. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26000. // NB: sessionId will be a String in most cases because it is huge
  26001. name: 'origin',
  26002. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26003. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26004. format: "%s %s %d %s IP%d %s"
  26005. }],
  26006. // default parsing of these only (though some of these feel outdated)
  26007. s: [{ name: 'name' }],
  26008. i: [{ name: 'description' }],
  26009. u: [{ name: 'uri' }],
  26010. e: [{ name: 'email' }],
  26011. p: [{ name: 'phone' }],
  26012. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26013. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26014. //k: [{}], // outdated thing ignored
  26015. t: [{ //t=0 0
  26016. name: 'timing',
  26017. reg: /^(\d*) (\d*)/,
  26018. names: ['start', 'stop'],
  26019. format: "%d %d"
  26020. }],
  26021. c: [{ //c=IN IP4 10.47.197.26
  26022. name: 'connection',
  26023. reg: /^IN IP(\d) (\S*)/,
  26024. names: ['version', 'ip'],
  26025. format: "IN IP%d %s"
  26026. }],
  26027. b: [{ //b=AS:4000
  26028. push: 'bandwidth',
  26029. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26030. names: ['type', 'limit'],
  26031. format: "%s:%s"
  26032. }],
  26033. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26034. // NB: special - pushes to session
  26035. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26036. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26037. names: ['type', 'port', 'protocol', 'payloads'],
  26038. format: "%s %d %s %s"
  26039. }],
  26040. a: [
  26041. { //a=rtpmap:110 opus/48000/2
  26042. push: 'rtp',
  26043. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26044. names: ['payload', 'codec', 'rate', 'encoding'],
  26045. format: function (o) {
  26046. return (o.encoding) ?
  26047. "rtpmap:%d %s/%s/%s":
  26048. "rtpmap:%d %s/%s";
  26049. }
  26050. },
  26051. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26052. push: 'fmtp',
  26053. reg: /^fmtp:(\d*) (\S*)/,
  26054. names: ['payload', 'config'],
  26055. format: "fmtp:%d %s"
  26056. },
  26057. { //a=control:streamid=0
  26058. name: 'control',
  26059. reg: /^control:(.*)/,
  26060. format: "control:%s"
  26061. },
  26062. { //a=rtcp:65179 IN IP4 193.84.77.194
  26063. name: 'rtcp',
  26064. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26065. names: ['port', 'netType', 'ipVer', 'address'],
  26066. format: function (o) {
  26067. return (o.address != null) ?
  26068. "rtcp:%d %s IP%d %s":
  26069. "rtcp:%d";
  26070. }
  26071. },
  26072. { //a=rtcp-fb:98 trr-int 100
  26073. push: 'rtcpFbTrrInt',
  26074. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26075. names: ['payload', 'value'],
  26076. format: "rtcp-fb:%d trr-int %d"
  26077. },
  26078. { //a=rtcp-fb:98 nack rpsi
  26079. push: 'rtcpFb',
  26080. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26081. names: ['payload', 'type', 'subtype'],
  26082. format: function (o) {
  26083. return (o.subtype != null) ?
  26084. "rtcp-fb:%s %s %s":
  26085. "rtcp-fb:%s %s";
  26086. }
  26087. },
  26088. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26089. //a=extmap:1/recvonly URI-gps-string
  26090. push: 'ext',
  26091. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26092. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26093. format: function (o) {
  26094. return (o.config != null) ?
  26095. "extmap:%s %s %s":
  26096. "extmap:%s %s";
  26097. }
  26098. },
  26099. {
  26100. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26101. push: 'crypto',
  26102. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26103. names: ['id', 'suite', 'config', 'sessionConfig'],
  26104. format: function (o) {
  26105. return (o.sessionConfig != null) ?
  26106. "crypto:%d %s %s %s":
  26107. "crypto:%d %s %s";
  26108. }
  26109. },
  26110. { //a=setup:actpass
  26111. name: 'setup',
  26112. reg: /^setup:(\w*)/,
  26113. format: "setup:%s"
  26114. },
  26115. { //a=mid:1
  26116. name: 'mid',
  26117. reg: /^mid:([^\s]*)/,
  26118. format: "mid:%s"
  26119. },
  26120. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26121. name: 'msid',
  26122. reg: /^msid:(.*)/,
  26123. format: "msid:%s"
  26124. },
  26125. { //a=ptime:20
  26126. name: 'ptime',
  26127. reg: /^ptime:(\d*)/,
  26128. format: "ptime:%d"
  26129. },
  26130. { //a=maxptime:60
  26131. name: 'maxptime',
  26132. reg: /^maxptime:(\d*)/,
  26133. format: "maxptime:%d"
  26134. },
  26135. { //a=sendrecv
  26136. name: 'direction',
  26137. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26138. },
  26139. { //a=ice-lite
  26140. name: 'icelite',
  26141. reg: /^(ice-lite)/
  26142. },
  26143. { //a=ice-ufrag:F7gI
  26144. name: 'iceUfrag',
  26145. reg: /^ice-ufrag:(\S*)/,
  26146. format: "ice-ufrag:%s"
  26147. },
  26148. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26149. name: 'icePwd',
  26150. reg: /^ice-pwd:(\S*)/,
  26151. format: "ice-pwd:%s"
  26152. },
  26153. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26154. name: 'fingerprint',
  26155. reg: /^fingerprint:(\S*) (\S*)/,
  26156. names: ['type', 'hash'],
  26157. format: "fingerprint:%s %s"
  26158. },
  26159. {
  26160. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26161. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26162. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26163. push:'candidates',
  26164. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26165. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26166. format: function (o) {
  26167. var str = "candidate:%s %d %s %d %s %d typ %s";
  26168. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26169. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26170. if (o.generation != null) {
  26171. str += " generation %d";
  26172. }
  26173. return str;
  26174. }
  26175. },
  26176. { //a=end-of-candidates (keep after the candidates line for readability)
  26177. name: 'endOfCandidates',
  26178. reg: /^(end-of-candidates)/
  26179. },
  26180. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26181. name: 'remoteCandidates',
  26182. reg: /^remote-candidates:(.*)/,
  26183. format: "remote-candidates:%s"
  26184. },
  26185. { //a=ice-options:google-ice
  26186. name: 'iceOptions',
  26187. reg: /^ice-options:(\S*)/,
  26188. format: "ice-options:%s"
  26189. },
  26190. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26191. push: "ssrcs",
  26192. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26193. names: ['id', 'attribute', 'value'],
  26194. format: "ssrc:%d %s:%s"
  26195. },
  26196. { //a=ssrc-group:FEC 1 2
  26197. push: "ssrcGroups",
  26198. reg: /^ssrc-group:(\w*) (.*)/,
  26199. names: ['semantics', 'ssrcs'],
  26200. format: "ssrc-group:%s %s"
  26201. },
  26202. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26203. name: "msidSemantic",
  26204. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26205. names: ['semantic', 'token'],
  26206. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26207. },
  26208. { //a=group:BUNDLE audio video
  26209. push: 'groups',
  26210. reg: /^group:(\w*) (.*)/,
  26211. names: ['type', 'mids'],
  26212. format: "group:%s %s"
  26213. },
  26214. { //a=rtcp-mux
  26215. name: 'rtcpMux',
  26216. reg: /^(rtcp-mux)/
  26217. },
  26218. { //a=rtcp-rsize
  26219. name: 'rtcpRsize',
  26220. reg: /^(rtcp-rsize)/
  26221. },
  26222. { // any a= that we don't understand is kepts verbatim on media.invalid
  26223. push: 'invalid',
  26224. names: ["value"]
  26225. }
  26226. ]
  26227. };
  26228. // set sensible defaults to avoid polluting the grammar with boring details
  26229. Object.keys(grammar).forEach(function (key) {
  26230. var objs = grammar[key];
  26231. objs.forEach(function (obj) {
  26232. if (!obj.reg) {
  26233. obj.reg = /(.*)/;
  26234. }
  26235. if (!obj.format) {
  26236. obj.format = "%s";
  26237. }
  26238. });
  26239. });
  26240. },{}],96:[function(require,module,exports){
  26241. var parser = require('./parser');
  26242. var writer = require('./writer');
  26243. exports.write = writer;
  26244. exports.parse = parser.parse;
  26245. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26246. exports.parsePayloads = parser.parsePayloads;
  26247. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26248. },{"./parser":97,"./writer":98}],97:[function(require,module,exports){
  26249. var toIntIfInt = function (v) {
  26250. return String(Number(v)) === v ? Number(v) : v;
  26251. };
  26252. var attachProperties = function (match, location, names, rawName) {
  26253. if (rawName && !names) {
  26254. location[rawName] = toIntIfInt(match[1]);
  26255. }
  26256. else {
  26257. for (var i = 0; i < names.length; i += 1) {
  26258. if (match[i+1] != null) {
  26259. location[names[i]] = toIntIfInt(match[i+1]);
  26260. }
  26261. }
  26262. }
  26263. };
  26264. var parseReg = function (obj, location, content) {
  26265. var needsBlank = obj.name && obj.names;
  26266. if (obj.push && !location[obj.push]) {
  26267. location[obj.push] = [];
  26268. }
  26269. else if (needsBlank && !location[obj.name]) {
  26270. location[obj.name] = {};
  26271. }
  26272. var keyLocation = obj.push ?
  26273. {} : // blank object that will be pushed
  26274. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26275. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26276. if (obj.push) {
  26277. location[obj.push].push(keyLocation);
  26278. }
  26279. };
  26280. var grammar = require('./grammar');
  26281. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26282. exports.parse = function (sdp) {
  26283. var session = {}
  26284. , media = []
  26285. , location = session; // points at where properties go under (one of the above)
  26286. // parse lines we understand
  26287. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26288. var type = l[0];
  26289. var content = l.slice(2);
  26290. if (type === 'm') {
  26291. media.push({rtp: [], fmtp: []});
  26292. location = media[media.length-1]; // point at latest media line
  26293. }
  26294. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26295. var obj = grammar[type][j];
  26296. if (obj.reg.test(content)) {
  26297. return parseReg(obj, location, content);
  26298. }
  26299. }
  26300. });
  26301. session.media = media; // link it up
  26302. return session;
  26303. };
  26304. var fmtpReducer = function (acc, expr) {
  26305. var s = expr.split('=');
  26306. if (s.length === 2) {
  26307. acc[s[0]] = toIntIfInt(s[1]);
  26308. }
  26309. return acc;
  26310. };
  26311. exports.parseFmtpConfig = function (str) {
  26312. return str.split(';').reduce(fmtpReducer, {});
  26313. };
  26314. exports.parsePayloads = function (str) {
  26315. return str.split(' ').map(Number);
  26316. };
  26317. exports.parseRemoteCandidates = function (str) {
  26318. var candidates = [];
  26319. var parts = str.split(' ').map(toIntIfInt);
  26320. for (var i = 0; i < parts.length; i += 3) {
  26321. candidates.push({
  26322. component: parts[i],
  26323. ip: parts[i + 1],
  26324. port: parts[i + 2]
  26325. });
  26326. }
  26327. return candidates;
  26328. };
  26329. },{"./grammar":95}],98:[function(require,module,exports){
  26330. var grammar = require('./grammar');
  26331. // customized util.format - discards excess arguments and can void middle ones
  26332. var formatRegExp = /%[sdv%]/g;
  26333. var format = function (formatStr) {
  26334. var i = 1;
  26335. var args = arguments;
  26336. var len = args.length;
  26337. return formatStr.replace(formatRegExp, function (x) {
  26338. if (i >= len) {
  26339. return x; // missing argument
  26340. }
  26341. var arg = args[i];
  26342. i += 1;
  26343. switch (x) {
  26344. case '%%':
  26345. return '%';
  26346. case '%s':
  26347. return String(arg);
  26348. case '%d':
  26349. return Number(arg);
  26350. case '%v':
  26351. return '';
  26352. }
  26353. });
  26354. // NB: we discard excess arguments - they are typically undefined from makeLine
  26355. };
  26356. var makeLine = function (type, obj, location) {
  26357. var str = obj.format instanceof Function ?
  26358. (obj.format(obj.push ? location : location[obj.name])) :
  26359. obj.format;
  26360. var args = [type + '=' + str];
  26361. if (obj.names) {
  26362. for (var i = 0; i < obj.names.length; i += 1) {
  26363. var n = obj.names[i];
  26364. if (obj.name) {
  26365. args.push(location[obj.name][n]);
  26366. }
  26367. else { // for mLine and push attributes
  26368. args.push(location[obj.names[i]]);
  26369. }
  26370. }
  26371. }
  26372. else {
  26373. args.push(location[obj.name]);
  26374. }
  26375. return format.apply(null, args);
  26376. };
  26377. // RFC specified order
  26378. // TODO: extend this with all the rest
  26379. var defaultOuterOrder = [
  26380. 'v', 'o', 's', 'i',
  26381. 'u', 'e', 'p', 'c',
  26382. 'b', 't', 'r', 'z', 'a'
  26383. ];
  26384. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26385. module.exports = function (session, opts) {
  26386. opts = opts || {};
  26387. // ensure certain properties exist
  26388. if (session.version == null) {
  26389. session.version = 0; // "v=0" must be there (only defined version atm)
  26390. }
  26391. if (session.name == null) {
  26392. session.name = " "; // "s= " must be there if no meaningful name set
  26393. }
  26394. session.media.forEach(function (mLine) {
  26395. if (mLine.payloads == null) {
  26396. mLine.payloads = "";
  26397. }
  26398. });
  26399. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26400. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26401. var sdp = [];
  26402. // loop through outerOrder for matching properties on session
  26403. outerOrder.forEach(function (type) {
  26404. grammar[type].forEach(function (obj) {
  26405. if (obj.name in session && session[obj.name] != null) {
  26406. sdp.push(makeLine(type, obj, session));
  26407. }
  26408. else if (obj.push in session && session[obj.push] != null) {
  26409. session[obj.push].forEach(function (el) {
  26410. sdp.push(makeLine(type, obj, el));
  26411. });
  26412. }
  26413. });
  26414. });
  26415. // then for each media line, follow the innerOrder
  26416. session.media.forEach(function (mLine) {
  26417. sdp.push(makeLine('m', grammar.m[0], mLine));
  26418. innerOrder.forEach(function (type) {
  26419. grammar[type].forEach(function (obj) {
  26420. if (obj.name in mLine && mLine[obj.name] != null) {
  26421. sdp.push(makeLine(type, obj, mLine));
  26422. }
  26423. else if (obj.push in mLine && mLine[obj.push] != null) {
  26424. mLine[obj.push].forEach(function (el) {
  26425. sdp.push(makeLine(type, obj, el));
  26426. });
  26427. }
  26428. });
  26429. });
  26430. });
  26431. return sdp.join('\r\n') + '\r\n';
  26432. };
  26433. },{"./grammar":95}],99:[function(require,module,exports){
  26434. var transform = require('sdp-transform');
  26435. var transformUtils = require('./transform-utils');
  26436. var parseSsrcs = transformUtils.parseSsrcs;
  26437. var writeSsrcs = transformUtils.writeSsrcs;
  26438. //region Constants
  26439. var DEFAULT_NUM_OF_LAYERS = 3;
  26440. //endregion
  26441. //region Ctor
  26442. function Simulcast(options) {
  26443. this.options = options ? options : {};
  26444. if (!this.options.numOfLayers) {
  26445. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  26446. }
  26447. this.layers = [];
  26448. }
  26449. //endregion
  26450. //region Stateless private utility functions
  26451. /**
  26452. * Returns a random integer between min (included) and max (excluded)
  26453. * Using Math.round() gives a non-uniform distribution!
  26454. * @returns {number}
  26455. */
  26456. function generateSSRC() {
  26457. var min = 0, max = 0xffffffff;
  26458. return Math.floor(Math.random() * (max - min)) + min;
  26459. };
  26460. function processVideo(session, action) {
  26461. if (session == null || !Array.isArray(session.media)) {
  26462. return;
  26463. }
  26464. session.media.forEach(function (mLine) {
  26465. if (mLine.type === 'video') {
  26466. action(mLine);
  26467. }
  26468. });
  26469. }
  26470. function validateDescription(desc)
  26471. {
  26472. return desc && desc != null
  26473. && desc.type && desc.type != ''
  26474. && desc.sdp && desc.sdp != '';
  26475. }
  26476. function explodeRemoteSimulcast(mLine) {
  26477. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26478. return;
  26479. }
  26480. var sources = parseSsrcs(mLine);
  26481. var order = [];
  26482. // Find the SIM group and explode its sources.
  26483. var j = mLine.ssrcGroups.length;
  26484. while (j--) {
  26485. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  26486. continue;
  26487. }
  26488. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  26489. for (var i = 0; i < simulcastSsrcs.length; i++) {
  26490. var ssrc = simulcastSsrcs[i];
  26491. order.push(ssrc);
  26492. var parts = sources[ssrc].msid.split(' ');
  26493. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  26494. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  26495. // Remove all the groups that this SSRC participates in.
  26496. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26497. if (relatedGroup.semantics === 'SIM') {
  26498. return;
  26499. }
  26500. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26501. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26502. return;
  26503. }
  26504. // Nuke all the related SSRCs.
  26505. relatedSsrcs.forEach(function (relatedSSRC) {
  26506. sources[relatedSSRC].msid = sources[ssrc].msid;
  26507. sources[relatedSSRC].cname = sources[ssrc].cname;
  26508. if (relatedSSRC !== ssrc) {
  26509. order.push(relatedSSRC);
  26510. }
  26511. });
  26512. // Schedule the related group for nuking.
  26513. })
  26514. }
  26515. mLine.ssrcs = writeSsrcs(sources, order);
  26516. mLine.ssrcGroups.splice(j, 1);
  26517. };
  26518. }
  26519. function squeezeRemoteSimulcast(mLine) {
  26520. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26521. return;
  26522. }
  26523. var sources = parseSsrcs(mLine);
  26524. // Find the SIM group and nuke it.
  26525. mLine.ssrcGroups.some(function (simulcastGroup) {
  26526. if (simulcastGroup.semantics !== 'SIM') {
  26527. return false;
  26528. }
  26529. // Schedule the SIM group for nuking.
  26530. simulcastGroup.nuke = true;
  26531. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  26532. // Nuke all the higher layer SSRCs.
  26533. for (var i = 1; i < simulcastSsrcs.length; i++) {
  26534. var ssrc = simulcastSsrcs[i];
  26535. delete sources[ssrc];
  26536. // Remove all the groups that this SSRC participates in.
  26537. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26538. if (relatedGroup.semantics === 'SIM') {
  26539. return;
  26540. }
  26541. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26542. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26543. return;
  26544. }
  26545. // Nuke all the related SSRCs.
  26546. relatedSsrcs.forEach(function (relatedSSRC) {
  26547. delete sources[relatedSSRC];
  26548. });
  26549. // Schedule the related group for nuking.
  26550. relatedGroup.nuke = true;
  26551. })
  26552. }
  26553. return true;
  26554. });
  26555. mLine.ssrcs = writeSsrcs(sources);
  26556. // Nuke all the scheduled groups.
  26557. var i = mLine.ssrcGroups.length;
  26558. while (i--) {
  26559. if (mLine.ssrcGroups[i].nuke) {
  26560. mLine.ssrcGroups.splice(i, 1);
  26561. }
  26562. }
  26563. }
  26564. function removeGoogConference(mLine) {
  26565. if (!mLine || !Array.isArray(mLine.invalid)) {
  26566. return;
  26567. }
  26568. var i = mLine.invalid.length;
  26569. while (i--) {
  26570. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26571. mLine.invalid.splice(i, 1);
  26572. }
  26573. }
  26574. }
  26575. function assertGoogConference(mLine) {
  26576. if (!mLine) {
  26577. return;
  26578. }
  26579. if (!Array.isArray(mLine.invalid)) {
  26580. mLine.invalid = [];
  26581. }
  26582. if (!mLine.invalid.some(
  26583. function (i) { return i.value === 'x-google-flag:conference' })) {
  26584. mLine.invalid.push({'value': 'x-google-flag:conference'});
  26585. }
  26586. }
  26587. //endregion
  26588. //region "Private" functions
  26589. /**
  26590. *
  26591. * @param mLine
  26592. * @private
  26593. */
  26594. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26595. if (!mLine || mLine.type !== 'video') {
  26596. return;
  26597. }
  26598. var sources = parseSsrcs(mLine);
  26599. if (Object.keys(sources).length === 0) {
  26600. // no sources, disable simulcast.
  26601. if (this.layers.length !== 0) {
  26602. this.layers = [];
  26603. }
  26604. return;
  26605. }
  26606. // find the base layer (we'll reuse its msid and cname).
  26607. var baseLayerSSRC = Object.keys(sources)[0];
  26608. var baseLayer = sources[baseLayerSSRC];
  26609. // todo(gp) handle screen sharing.
  26610. // check if base CNAME has changed and reinitialise layers.
  26611. if (this.layers.length > 0
  26612. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26613. this.layers = [];
  26614. }
  26615. // (re)initialise layers
  26616. if (this.layers.length < 1) {
  26617. // first push the base layer.
  26618. this.layers.push({
  26619. ssrc: baseLayerSSRC,
  26620. msid: baseLayer.msid,
  26621. cname: baseLayer.cname
  26622. });
  26623. var rtx = false; // RFC 4588
  26624. if (Array.isArray(mLine.rtp)) {
  26625. rtx = mLine.rtp.some(
  26626. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26627. }
  26628. if (rtx) {
  26629. this.layers[0].rtx = generateSSRC();
  26630. }
  26631. // now push additional layers.
  26632. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26633. var layer = { ssrc: generateSSRC() };
  26634. if (rtx) {
  26635. layer.rtx = generateSSRC();
  26636. }
  26637. this.layers.push(layer);
  26638. }
  26639. }
  26640. };
  26641. /**
  26642. *
  26643. * @param mLine
  26644. * @private
  26645. */
  26646. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26647. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26648. var sources = {};
  26649. var msid = this.layers[0].msid;
  26650. var cname = this.layers[0].cname;
  26651. var simulcastSsrcs = [];
  26652. var ssrcGroups = [];
  26653. for (var i = 0; i < this.layers.length; i++) {
  26654. var layer = this.layers[i];
  26655. sources[layer.ssrc] = { msid: msid, cname: cname };
  26656. simulcastSsrcs.push(layer.ssrc);
  26657. if (layer.rtx) {
  26658. sources[layer.rtx] = {
  26659. msid: msid,
  26660. cname: cname
  26661. }
  26662. ssrcGroups.push({
  26663. semantics: 'FID',
  26664. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  26665. });
  26666. }
  26667. }
  26668. ssrcGroups.push({
  26669. semantics: 'SIM',
  26670. ssrcs: simulcastSsrcs.join(' ')
  26671. });
  26672. mLine.ssrcGroups = ssrcGroups;
  26673. mLine.ssrcs = writeSsrcs(sources);
  26674. }
  26675. }
  26676. //endregion
  26677. //region "Public" functions
  26678. Simulcast.prototype.isSupported = function () {
  26679. return window.chrome;
  26680. // TODO this needs improvements. For example I doubt that Chrome in Android
  26681. // has simulcast support. Also, only recent versions of Chromium have native
  26682. // simulcast support.
  26683. }
  26684. /**
  26685. *
  26686. * @param desc
  26687. * @returns {RTCSessionDescription}
  26688. */
  26689. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26690. if (!validateDescription(desc)) {
  26691. return desc;
  26692. }
  26693. var session = transform.parse(desc.sdp);
  26694. var self = this;
  26695. processVideo(session, function (mLine) {
  26696. // Handle simulcast reception.
  26697. if (self.options.explodeRemoteSimulcast) {
  26698. explodeRemoteSimulcast(mLine);
  26699. } else {
  26700. squeezeRemoteSimulcast(mLine);
  26701. }
  26702. // If native simulcast is enabled, we must append the x-goog-conference
  26703. // attribute to the SDP.
  26704. if (self.layers.length < 1) {
  26705. removeGoogConference(mLine);
  26706. } else {
  26707. assertGoogConference(mLine);
  26708. }
  26709. });
  26710. return new RTCSessionDescription({
  26711. type: desc.type,
  26712. sdp: transform.write(session)
  26713. });
  26714. };
  26715. /**
  26716. *
  26717. * @param desc
  26718. * @returns {RTCSessionDescription}
  26719. */
  26720. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26721. if (!validateDescription(desc) || !this.isSupported()) {
  26722. return desc;
  26723. }
  26724. var session = transform.parse(desc.sdp);
  26725. var self = this;
  26726. processVideo(session, function (mLine) {
  26727. // Initialize native simulcast layers, if not already done.
  26728. self._maybeInitializeLayers(mLine);
  26729. // Update the SDP with the simulcast layers.
  26730. self._restoreSimulcastView(mLine);
  26731. });
  26732. return new RTCSessionDescription({
  26733. type: desc.type,
  26734. sdp: transform.write(session)
  26735. });
  26736. };
  26737. //endregion
  26738. module.exports = Simulcast;
  26739. },{"./transform-utils":100,"sdp-transform":102}],100:[function(require,module,exports){
  26740. exports.writeSsrcs = function(sources, order) {
  26741. var ssrcs = [];
  26742. // expand sources to ssrcs
  26743. if (typeof sources !== 'undefined' &&
  26744. Object.keys(sources).length !== 0) {
  26745. if (Array.isArray(order)) {
  26746. for (var i = 0; i < order.length; i++) {
  26747. var ssrc = order[i];
  26748. var source = sources[ssrc];
  26749. Object.keys(source).forEach(function (attribute) {
  26750. ssrcs.push({
  26751. id: ssrc,
  26752. attribute: attribute,
  26753. value: source[attribute]
  26754. });
  26755. });
  26756. }
  26757. } else {
  26758. Object.keys(sources).forEach(function (ssrc) {
  26759. var source = sources[ssrc];
  26760. Object.keys(source).forEach(function (attribute) {
  26761. ssrcs.push({
  26762. id: ssrc,
  26763. attribute: attribute,
  26764. value: source[attribute]
  26765. });
  26766. });
  26767. });
  26768. }
  26769. }
  26770. return ssrcs;
  26771. };
  26772. exports.parseSsrcs = function (mLine) {
  26773. var sources = {};
  26774. // group sources attributes by ssrc.
  26775. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26776. mLine.ssrcs.forEach(function (ssrc) {
  26777. if (!sources[ssrc.id])
  26778. sources[ssrc.id] = {};
  26779. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26780. });
  26781. }
  26782. return sources;
  26783. };
  26784. },{}],101:[function(require,module,exports){
  26785. arguments[4][95][0].apply(exports,arguments)
  26786. },{"dup":95}],102:[function(require,module,exports){
  26787. arguments[4][96][0].apply(exports,arguments)
  26788. },{"./parser":103,"./writer":104,"dup":96}],103:[function(require,module,exports){
  26789. arguments[4][97][0].apply(exports,arguments)
  26790. },{"./grammar":101,"dup":97}],104:[function(require,module,exports){
  26791. arguments[4][98][0].apply(exports,arguments)
  26792. },{"./grammar":101,"dup":98}],105:[function(require,module,exports){
  26793. var grammar = module.exports = {
  26794. v: [{
  26795. name: 'version',
  26796. reg: /^(\d*)$/
  26797. }],
  26798. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26799. // NB: sessionId will be a String in most cases because it is huge
  26800. name: 'origin',
  26801. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26802. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26803. format: "%s %s %d %s IP%d %s"
  26804. }],
  26805. // default parsing of these only (though some of these feel outdated)
  26806. s: [{ name: 'name' }],
  26807. i: [{ name: 'description' }],
  26808. u: [{ name: 'uri' }],
  26809. e: [{ name: 'email' }],
  26810. p: [{ name: 'phone' }],
  26811. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26812. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26813. //k: [{}], // outdated thing ignored
  26814. t: [{ //t=0 0
  26815. name: 'timing',
  26816. reg: /^(\d*) (\d*)/,
  26817. names: ['start', 'stop'],
  26818. format: "%d %d"
  26819. }],
  26820. c: [{ //c=IN IP4 10.47.197.26
  26821. name: 'connection',
  26822. reg: /^IN IP(\d) (\S*)/,
  26823. names: ['version', 'ip'],
  26824. format: "IN IP%d %s"
  26825. }],
  26826. b: [{ //b=AS:4000
  26827. push: 'bandwidth',
  26828. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26829. names: ['type', 'limit'],
  26830. format: "%s:%s"
  26831. }],
  26832. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26833. // NB: special - pushes to session
  26834. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26835. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26836. names: ['type', 'port', 'protocol', 'payloads'],
  26837. format: "%s %d %s %s"
  26838. }],
  26839. a: [
  26840. { //a=rtpmap:110 opus/48000/2
  26841. push: 'rtp',
  26842. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26843. names: ['payload', 'codec', 'rate', 'encoding'],
  26844. format: function (o) {
  26845. return (o.encoding) ?
  26846. "rtpmap:%d %s/%s/%s":
  26847. "rtpmap:%d %s/%s";
  26848. }
  26849. },
  26850. {
  26851. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26852. //a=fmtp:111 minptime=10; useinbandfec=1
  26853. push: 'fmtp',
  26854. reg: /^fmtp:(\d*) ([\S| ]*)/,
  26855. names: ['payload', 'config'],
  26856. format: "fmtp:%d %s"
  26857. },
  26858. { //a=control:streamid=0
  26859. name: 'control',
  26860. reg: /^control:(.*)/,
  26861. format: "control:%s"
  26862. },
  26863. { //a=rtcp:65179 IN IP4 193.84.77.194
  26864. name: 'rtcp',
  26865. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26866. names: ['port', 'netType', 'ipVer', 'address'],
  26867. format: function (o) {
  26868. return (o.address != null) ?
  26869. "rtcp:%d %s IP%d %s":
  26870. "rtcp:%d";
  26871. }
  26872. },
  26873. { //a=rtcp-fb:98 trr-int 100
  26874. push: 'rtcpFbTrrInt',
  26875. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26876. names: ['payload', 'value'],
  26877. format: "rtcp-fb:%d trr-int %d"
  26878. },
  26879. { //a=rtcp-fb:98 nack rpsi
  26880. push: 'rtcpFb',
  26881. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26882. names: ['payload', 'type', 'subtype'],
  26883. format: function (o) {
  26884. return (o.subtype != null) ?
  26885. "rtcp-fb:%s %s %s":
  26886. "rtcp-fb:%s %s";
  26887. }
  26888. },
  26889. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26890. //a=extmap:1/recvonly URI-gps-string
  26891. push: 'ext',
  26892. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26893. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26894. format: function (o) {
  26895. return (o.config != null) ?
  26896. "extmap:%s %s %s":
  26897. "extmap:%s %s";
  26898. }
  26899. },
  26900. {
  26901. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26902. push: 'crypto',
  26903. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26904. names: ['id', 'suite', 'config', 'sessionConfig'],
  26905. format: function (o) {
  26906. return (o.sessionConfig != null) ?
  26907. "crypto:%d %s %s %s":
  26908. "crypto:%d %s %s";
  26909. }
  26910. },
  26911. { //a=setup:actpass
  26912. name: 'setup',
  26913. reg: /^setup:(\w*)/,
  26914. format: "setup:%s"
  26915. },
  26916. { //a=mid:1
  26917. name: 'mid',
  26918. reg: /^mid:([^\s]*)/,
  26919. format: "mid:%s"
  26920. },
  26921. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26922. name: 'msid',
  26923. reg: /^msid:(.*)/,
  26924. format: "msid:%s"
  26925. },
  26926. { //a=ptime:20
  26927. name: 'ptime',
  26928. reg: /^ptime:(\d*)/,
  26929. format: "ptime:%d"
  26930. },
  26931. { //a=maxptime:60
  26932. name: 'maxptime',
  26933. reg: /^maxptime:(\d*)/,
  26934. format: "maxptime:%d"
  26935. },
  26936. { //a=sendrecv
  26937. name: 'direction',
  26938. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26939. },
  26940. { //a=ice-lite
  26941. name: 'icelite',
  26942. reg: /^(ice-lite)/
  26943. },
  26944. { //a=ice-ufrag:F7gI
  26945. name: 'iceUfrag',
  26946. reg: /^ice-ufrag:(\S*)/,
  26947. format: "ice-ufrag:%s"
  26948. },
  26949. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26950. name: 'icePwd',
  26951. reg: /^ice-pwd:(\S*)/,
  26952. format: "ice-pwd:%s"
  26953. },
  26954. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26955. name: 'fingerprint',
  26956. reg: /^fingerprint:(\S*) (\S*)/,
  26957. names: ['type', 'hash'],
  26958. format: "fingerprint:%s %s"
  26959. },
  26960. {
  26961. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26962. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26963. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26964. push:'candidates',
  26965. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26966. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26967. format: function (o) {
  26968. var str = "candidate:%s %d %s %d %s %d typ %s";
  26969. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26970. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26971. if (o.generation != null) {
  26972. str += " generation %d";
  26973. }
  26974. return str;
  26975. }
  26976. },
  26977. { //a=end-of-candidates (keep after the candidates line for readability)
  26978. name: 'endOfCandidates',
  26979. reg: /^(end-of-candidates)/
  26980. },
  26981. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26982. name: 'remoteCandidates',
  26983. reg: /^remote-candidates:(.*)/,
  26984. format: "remote-candidates:%s"
  26985. },
  26986. { //a=ice-options:google-ice
  26987. name: 'iceOptions',
  26988. reg: /^ice-options:(\S*)/,
  26989. format: "ice-options:%s"
  26990. },
  26991. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26992. push: "ssrcs",
  26993. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26994. names: ['id', 'attribute', 'value'],
  26995. format: "ssrc:%d %s:%s"
  26996. },
  26997. { //a=ssrc-group:FEC 1 2
  26998. push: "ssrcGroups",
  26999. reg: /^ssrc-group:(\w*) (.*)/,
  27000. names: ['semantics', 'ssrcs'],
  27001. format: "ssrc-group:%s %s"
  27002. },
  27003. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  27004. name: "msidSemantic",
  27005. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  27006. names: ['semantic', 'token'],
  27007. format: "msid-semantic: %s %s" // space after ":" is not accidental
  27008. },
  27009. { //a=group:BUNDLE audio video
  27010. push: 'groups',
  27011. reg: /^group:(\w*) (.*)/,
  27012. names: ['type', 'mids'],
  27013. format: "group:%s %s"
  27014. },
  27015. { //a=rtcp-mux
  27016. name: 'rtcpMux',
  27017. reg: /^(rtcp-mux)/
  27018. },
  27019. { //a=rtcp-rsize
  27020. name: 'rtcpRsize',
  27021. reg: /^(rtcp-rsize)/
  27022. },
  27023. { // any a= that we don't understand is kepts verbatim on media.invalid
  27024. push: 'invalid',
  27025. names: ["value"]
  27026. }
  27027. ]
  27028. };
  27029. // set sensible defaults to avoid polluting the grammar with boring details
  27030. Object.keys(grammar).forEach(function (key) {
  27031. var objs = grammar[key];
  27032. objs.forEach(function (obj) {
  27033. if (!obj.reg) {
  27034. obj.reg = /(.*)/;
  27035. }
  27036. if (!obj.format) {
  27037. obj.format = "%s";
  27038. }
  27039. });
  27040. });
  27041. },{}],106:[function(require,module,exports){
  27042. arguments[4][96][0].apply(exports,arguments)
  27043. },{"./parser":107,"./writer":108,"dup":96}],107:[function(require,module,exports){
  27044. var toIntIfInt = function (v) {
  27045. return String(Number(v)) === v ? Number(v) : v;
  27046. };
  27047. var attachProperties = function (match, location, names, rawName) {
  27048. if (rawName && !names) {
  27049. location[rawName] = toIntIfInt(match[1]);
  27050. }
  27051. else {
  27052. for (var i = 0; i < names.length; i += 1) {
  27053. if (match[i+1] != null) {
  27054. location[names[i]] = toIntIfInt(match[i+1]);
  27055. }
  27056. }
  27057. }
  27058. };
  27059. var parseReg = function (obj, location, content) {
  27060. var needsBlank = obj.name && obj.names;
  27061. if (obj.push && !location[obj.push]) {
  27062. location[obj.push] = [];
  27063. }
  27064. else if (needsBlank && !location[obj.name]) {
  27065. location[obj.name] = {};
  27066. }
  27067. var keyLocation = obj.push ?
  27068. {} : // blank object that will be pushed
  27069. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  27070. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  27071. if (obj.push) {
  27072. location[obj.push].push(keyLocation);
  27073. }
  27074. };
  27075. var grammar = require('./grammar');
  27076. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  27077. exports.parse = function (sdp) {
  27078. var session = {}
  27079. , media = []
  27080. , location = session; // points at where properties go under (one of the above)
  27081. // parse lines we understand
  27082. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  27083. var type = l[0];
  27084. var content = l.slice(2);
  27085. if (type === 'm') {
  27086. media.push({rtp: [], fmtp: []});
  27087. location = media[media.length-1]; // point at latest media line
  27088. }
  27089. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  27090. var obj = grammar[type][j];
  27091. if (obj.reg.test(content)) {
  27092. return parseReg(obj, location, content);
  27093. }
  27094. }
  27095. });
  27096. session.media = media; // link it up
  27097. return session;
  27098. };
  27099. var fmtpReducer = function (acc, expr) {
  27100. var s = expr.split('=');
  27101. if (s.length === 2) {
  27102. acc[s[0]] = toIntIfInt(s[1]);
  27103. }
  27104. return acc;
  27105. };
  27106. exports.parseFmtpConfig = function (str) {
  27107. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  27108. };
  27109. exports.parsePayloads = function (str) {
  27110. return str.split(' ').map(Number);
  27111. };
  27112. exports.parseRemoteCandidates = function (str) {
  27113. var candidates = [];
  27114. var parts = str.split(' ').map(toIntIfInt);
  27115. for (var i = 0; i < parts.length; i += 3) {
  27116. candidates.push({
  27117. component: parts[i],
  27118. ip: parts[i + 1],
  27119. port: parts[i + 2]
  27120. });
  27121. }
  27122. return candidates;
  27123. };
  27124. },{"./grammar":105}],108:[function(require,module,exports){
  27125. arguments[4][98][0].apply(exports,arguments)
  27126. },{"./grammar":105,"dup":98}],109:[function(require,module,exports){
  27127. module.exports = require('./lib/');
  27128. },{"./lib/":110}],110:[function(require,module,exports){
  27129. /**
  27130. * Module dependencies.
  27131. */
  27132. var url = require('./url');
  27133. var parser = require('socket.io-parser');
  27134. var Manager = require('./manager');
  27135. var debug = require('debug')('socket.io-client');
  27136. /**
  27137. * Module exports.
  27138. */
  27139. module.exports = exports = lookup;
  27140. /**
  27141. * Managers cache.
  27142. */
  27143. var cache = exports.managers = {};
  27144. /**
  27145. * Looks up an existing `Manager` for multiplexing.
  27146. * If the user summons:
  27147. *
  27148. * `io('http://localhost/a');`
  27149. * `io('http://localhost/b');`
  27150. *
  27151. * We reuse the existing instance based on same scheme/port/host,
  27152. * and we initialize sockets for each namespace.
  27153. *
  27154. * @api public
  27155. */
  27156. function lookup(uri, opts) {
  27157. if (typeof uri == 'object') {
  27158. opts = uri;
  27159. uri = undefined;
  27160. }
  27161. opts = opts || {};
  27162. var parsed = url(uri);
  27163. var source = parsed.source;
  27164. var id = parsed.id;
  27165. var io;
  27166. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  27167. debug('ignoring socket cache for %s', source);
  27168. io = Manager(source, opts);
  27169. } else {
  27170. if (!cache[id]) {
  27171. debug('new io instance for %s', source);
  27172. cache[id] = Manager(source, opts);
  27173. }
  27174. io = cache[id];
  27175. }
  27176. return io.socket(parsed.path);
  27177. }
  27178. /**
  27179. * Protocol version.
  27180. *
  27181. * @api public
  27182. */
  27183. exports.protocol = parser.protocol;
  27184. /**
  27185. * `connect`.
  27186. *
  27187. * @param {String} uri
  27188. * @api public
  27189. */
  27190. exports.connect = lookup;
  27191. /**
  27192. * Expose constructors for standalone build.
  27193. *
  27194. * @api public
  27195. */
  27196. exports.Manager = require('./manager');
  27197. exports.Socket = require('./socket');
  27198. },{"./manager":111,"./socket":113,"./url":114,"debug":118,"socket.io-parser":154}],111:[function(require,module,exports){
  27199. /**
  27200. * Module dependencies.
  27201. */
  27202. var url = require('./url');
  27203. var eio = require('engine.io-client');
  27204. var Socket = require('./socket');
  27205. var Emitter = require('component-emitter');
  27206. var parser = require('socket.io-parser');
  27207. var on = require('./on');
  27208. var bind = require('component-bind');
  27209. var object = require('object-component');
  27210. var debug = require('debug')('socket.io-client:manager');
  27211. var indexOf = require('indexof');
  27212. var Backoff = require('backo2');
  27213. /**
  27214. * Module exports
  27215. */
  27216. module.exports = Manager;
  27217. /**
  27218. * `Manager` constructor.
  27219. *
  27220. * @param {String} engine instance or engine uri/opts
  27221. * @param {Object} options
  27222. * @api public
  27223. */
  27224. function Manager(uri, opts){
  27225. if (!(this instanceof Manager)) return new Manager(uri, opts);
  27226. if (uri && ('object' == typeof uri)) {
  27227. opts = uri;
  27228. uri = undefined;
  27229. }
  27230. opts = opts || {};
  27231. opts.path = opts.path || '/socket.io';
  27232. this.nsps = {};
  27233. this.subs = [];
  27234. this.opts = opts;
  27235. this.reconnection(opts.reconnection !== false);
  27236. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  27237. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  27238. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  27239. this.randomizationFactor(opts.randomizationFactor || 0.5);
  27240. this.backoff = new Backoff({
  27241. min: this.reconnectionDelay(),
  27242. max: this.reconnectionDelayMax(),
  27243. jitter: this.randomizationFactor()
  27244. });
  27245. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  27246. this.readyState = 'closed';
  27247. this.uri = uri;
  27248. this.connected = [];
  27249. this.encoding = false;
  27250. this.packetBuffer = [];
  27251. this.encoder = new parser.Encoder();
  27252. this.decoder = new parser.Decoder();
  27253. this.autoConnect = opts.autoConnect !== false;
  27254. if (this.autoConnect) this.open();
  27255. }
  27256. /**
  27257. * Propagate given event to sockets and emit on `this`
  27258. *
  27259. * @api private
  27260. */
  27261. Manager.prototype.emitAll = function() {
  27262. this.emit.apply(this, arguments);
  27263. for (var nsp in this.nsps) {
  27264. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  27265. }
  27266. };
  27267. /**
  27268. * Update `socket.id` of all sockets
  27269. *
  27270. * @api private
  27271. */
  27272. Manager.prototype.updateSocketIds = function(){
  27273. for (var nsp in this.nsps) {
  27274. this.nsps[nsp].id = this.engine.id;
  27275. }
  27276. };
  27277. /**
  27278. * Mix in `Emitter`.
  27279. */
  27280. Emitter(Manager.prototype);
  27281. /**
  27282. * Sets the `reconnection` config.
  27283. *
  27284. * @param {Boolean} true/false if it should automatically reconnect
  27285. * @return {Manager} self or value
  27286. * @api public
  27287. */
  27288. Manager.prototype.reconnection = function(v){
  27289. if (!arguments.length) return this._reconnection;
  27290. this._reconnection = !!v;
  27291. return this;
  27292. };
  27293. /**
  27294. * Sets the reconnection attempts config.
  27295. *
  27296. * @param {Number} max reconnection attempts before giving up
  27297. * @return {Manager} self or value
  27298. * @api public
  27299. */
  27300. Manager.prototype.reconnectionAttempts = function(v){
  27301. if (!arguments.length) return this._reconnectionAttempts;
  27302. this._reconnectionAttempts = v;
  27303. return this;
  27304. };
  27305. /**
  27306. * Sets the delay between reconnections.
  27307. *
  27308. * @param {Number} delay
  27309. * @return {Manager} self or value
  27310. * @api public
  27311. */
  27312. Manager.prototype.reconnectionDelay = function(v){
  27313. if (!arguments.length) return this._reconnectionDelay;
  27314. this._reconnectionDelay = v;
  27315. this.backoff && this.backoff.setMin(v);
  27316. return this;
  27317. };
  27318. Manager.prototype.randomizationFactor = function(v){
  27319. if (!arguments.length) return this._randomizationFactor;
  27320. this._randomizationFactor = v;
  27321. this.backoff && this.backoff.setJitter(v);
  27322. return this;
  27323. };
  27324. /**
  27325. * Sets the maximum delay between reconnections.
  27326. *
  27327. * @param {Number} delay
  27328. * @return {Manager} self or value
  27329. * @api public
  27330. */
  27331. Manager.prototype.reconnectionDelayMax = function(v){
  27332. if (!arguments.length) return this._reconnectionDelayMax;
  27333. this._reconnectionDelayMax = v;
  27334. this.backoff && this.backoff.setMax(v);
  27335. return this;
  27336. };
  27337. /**
  27338. * Sets the connection timeout. `false` to disable
  27339. *
  27340. * @return {Manager} self or value
  27341. * @api public
  27342. */
  27343. Manager.prototype.timeout = function(v){
  27344. if (!arguments.length) return this._timeout;
  27345. this._timeout = v;
  27346. return this;
  27347. };
  27348. /**
  27349. * Starts trying to reconnect if reconnection is enabled and we have not
  27350. * started reconnecting yet
  27351. *
  27352. * @api private
  27353. */
  27354. Manager.prototype.maybeReconnectOnOpen = function() {
  27355. // Only try to reconnect if it's the first time we're connecting
  27356. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  27357. // keeps reconnection from firing twice for the same reconnection loop
  27358. this.reconnect();
  27359. }
  27360. };
  27361. /**
  27362. * Sets the current transport `socket`.
  27363. *
  27364. * @param {Function} optional, callback
  27365. * @return {Manager} self
  27366. * @api public
  27367. */
  27368. Manager.prototype.open =
  27369. Manager.prototype.connect = function(fn){
  27370. debug('readyState %s', this.readyState);
  27371. if (~this.readyState.indexOf('open')) return this;
  27372. debug('opening %s', this.uri);
  27373. this.engine = eio(this.uri, this.opts);
  27374. var socket = this.engine;
  27375. var self = this;
  27376. this.readyState = 'opening';
  27377. this.skipReconnect = false;
  27378. // emit `open`
  27379. var openSub = on(socket, 'open', function() {
  27380. self.onopen();
  27381. fn && fn();
  27382. });
  27383. // emit `connect_error`
  27384. var errorSub = on(socket, 'error', function(data){
  27385. debug('connect_error');
  27386. self.cleanup();
  27387. self.readyState = 'closed';
  27388. self.emitAll('connect_error', data);
  27389. if (fn) {
  27390. var err = new Error('Connection error');
  27391. err.data = data;
  27392. fn(err);
  27393. } else {
  27394. // Only do this if there is no fn to handle the error
  27395. self.maybeReconnectOnOpen();
  27396. }
  27397. });
  27398. // emit `connect_timeout`
  27399. if (false !== this._timeout) {
  27400. var timeout = this._timeout;
  27401. debug('connect attempt will timeout after %d', timeout);
  27402. // set timer
  27403. var timer = setTimeout(function(){
  27404. debug('connect attempt timed out after %d', timeout);
  27405. openSub.destroy();
  27406. socket.close();
  27407. socket.emit('error', 'timeout');
  27408. self.emitAll('connect_timeout', timeout);
  27409. }, timeout);
  27410. this.subs.push({
  27411. destroy: function(){
  27412. clearTimeout(timer);
  27413. }
  27414. });
  27415. }
  27416. this.subs.push(openSub);
  27417. this.subs.push(errorSub);
  27418. return this;
  27419. };
  27420. /**
  27421. * Called upon transport open.
  27422. *
  27423. * @api private
  27424. */
  27425. Manager.prototype.onopen = function(){
  27426. debug('open');
  27427. // clear old subs
  27428. this.cleanup();
  27429. // mark as open
  27430. this.readyState = 'open';
  27431. this.emit('open');
  27432. // add new subs
  27433. var socket = this.engine;
  27434. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  27435. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  27436. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  27437. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  27438. };
  27439. /**
  27440. * Called with data.
  27441. *
  27442. * @api private
  27443. */
  27444. Manager.prototype.ondata = function(data){
  27445. this.decoder.add(data);
  27446. };
  27447. /**
  27448. * Called when parser fully decodes a packet.
  27449. *
  27450. * @api private
  27451. */
  27452. Manager.prototype.ondecoded = function(packet) {
  27453. this.emit('packet', packet);
  27454. };
  27455. /**
  27456. * Called upon socket error.
  27457. *
  27458. * @api private
  27459. */
  27460. Manager.prototype.onerror = function(err){
  27461. debug('error', err);
  27462. this.emitAll('error', err);
  27463. };
  27464. /**
  27465. * Creates a new socket for the given `nsp`.
  27466. *
  27467. * @return {Socket}
  27468. * @api public
  27469. */
  27470. Manager.prototype.socket = function(nsp){
  27471. var socket = this.nsps[nsp];
  27472. if (!socket) {
  27473. socket = new Socket(this, nsp);
  27474. this.nsps[nsp] = socket;
  27475. var self = this;
  27476. socket.on('connect', function(){
  27477. socket.id = self.engine.id;
  27478. if (!~indexOf(self.connected, socket)) {
  27479. self.connected.push(socket);
  27480. }
  27481. });
  27482. }
  27483. return socket;
  27484. };
  27485. /**
  27486. * Called upon a socket close.
  27487. *
  27488. * @param {Socket} socket
  27489. */
  27490. Manager.prototype.destroy = function(socket){
  27491. var index = indexOf(this.connected, socket);
  27492. if (~index) this.connected.splice(index, 1);
  27493. if (this.connected.length) return;
  27494. this.close();
  27495. };
  27496. /**
  27497. * Writes a packet.
  27498. *
  27499. * @param {Object} packet
  27500. * @api private
  27501. */
  27502. Manager.prototype.packet = function(packet){
  27503. debug('writing packet %j', packet);
  27504. var self = this;
  27505. if (!self.encoding) {
  27506. // encode, then write to engine with result
  27507. self.encoding = true;
  27508. this.encoder.encode(packet, function(encodedPackets) {
  27509. for (var i = 0; i < encodedPackets.length; i++) {
  27510. self.engine.write(encodedPackets[i]);
  27511. }
  27512. self.encoding = false;
  27513. self.processPacketQueue();
  27514. });
  27515. } else { // add packet to the queue
  27516. self.packetBuffer.push(packet);
  27517. }
  27518. };
  27519. /**
  27520. * If packet buffer is non-empty, begins encoding the
  27521. * next packet in line.
  27522. *
  27523. * @api private
  27524. */
  27525. Manager.prototype.processPacketQueue = function() {
  27526. if (this.packetBuffer.length > 0 && !this.encoding) {
  27527. var pack = this.packetBuffer.shift();
  27528. this.packet(pack);
  27529. }
  27530. };
  27531. /**
  27532. * Clean up transport subscriptions and packet buffer.
  27533. *
  27534. * @api private
  27535. */
  27536. Manager.prototype.cleanup = function(){
  27537. var sub;
  27538. while (sub = this.subs.shift()) sub.destroy();
  27539. this.packetBuffer = [];
  27540. this.encoding = false;
  27541. this.decoder.destroy();
  27542. };
  27543. /**
  27544. * Close the current socket.
  27545. *
  27546. * @api private
  27547. */
  27548. Manager.prototype.close =
  27549. Manager.prototype.disconnect = function(){
  27550. this.skipReconnect = true;
  27551. this.backoff.reset();
  27552. this.readyState = 'closed';
  27553. this.engine && this.engine.close();
  27554. };
  27555. /**
  27556. * Called upon engine close.
  27557. *
  27558. * @api private
  27559. */
  27560. Manager.prototype.onclose = function(reason){
  27561. debug('close');
  27562. this.cleanup();
  27563. this.backoff.reset();
  27564. this.readyState = 'closed';
  27565. this.emit('close', reason);
  27566. if (this._reconnection && !this.skipReconnect) {
  27567. this.reconnect();
  27568. }
  27569. };
  27570. /**
  27571. * Attempt a reconnection.
  27572. *
  27573. * @api private
  27574. */
  27575. Manager.prototype.reconnect = function(){
  27576. if (this.reconnecting || this.skipReconnect) return this;
  27577. var self = this;
  27578. if (this.backoff.attempts >= this._reconnectionAttempts) {
  27579. debug('reconnect failed');
  27580. this.backoff.reset();
  27581. this.emitAll('reconnect_failed');
  27582. this.reconnecting = false;
  27583. } else {
  27584. var delay = this.backoff.duration();
  27585. debug('will wait %dms before reconnect attempt', delay);
  27586. this.reconnecting = true;
  27587. var timer = setTimeout(function(){
  27588. if (self.skipReconnect) return;
  27589. debug('attempting reconnect');
  27590. self.emitAll('reconnect_attempt', self.backoff.attempts);
  27591. self.emitAll('reconnecting', self.backoff.attempts);
  27592. // check again for the case socket closed in above events
  27593. if (self.skipReconnect) return;
  27594. self.open(function(err){
  27595. if (err) {
  27596. debug('reconnect attempt error');
  27597. self.reconnecting = false;
  27598. self.reconnect();
  27599. self.emitAll('reconnect_error', err.data);
  27600. } else {
  27601. debug('reconnect success');
  27602. self.onreconnect();
  27603. }
  27604. });
  27605. }, delay);
  27606. this.subs.push({
  27607. destroy: function(){
  27608. clearTimeout(timer);
  27609. }
  27610. });
  27611. }
  27612. };
  27613. /**
  27614. * Called upon successful reconnect.
  27615. *
  27616. * @api private
  27617. */
  27618. Manager.prototype.onreconnect = function(){
  27619. var attempt = this.backoff.attempts;
  27620. this.reconnecting = false;
  27621. this.backoff.reset();
  27622. this.updateSocketIds();
  27623. this.emitAll('reconnect', attempt);
  27624. };
  27625. },{"./on":112,"./socket":113,"./url":114,"backo2":115,"component-bind":116,"component-emitter":117,"debug":118,"engine.io-client":119,"indexof":150,"object-component":151,"socket.io-parser":154}],112:[function(require,module,exports){
  27626. /**
  27627. * Module exports.
  27628. */
  27629. module.exports = on;
  27630. /**
  27631. * Helper for subscriptions.
  27632. *
  27633. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  27634. * @param {String} event name
  27635. * @param {Function} callback
  27636. * @api public
  27637. */
  27638. function on(obj, ev, fn) {
  27639. obj.on(ev, fn);
  27640. return {
  27641. destroy: function(){
  27642. obj.removeListener(ev, fn);
  27643. }
  27644. };
  27645. }
  27646. },{}],113:[function(require,module,exports){
  27647. /**
  27648. * Module dependencies.
  27649. */
  27650. var parser = require('socket.io-parser');
  27651. var Emitter = require('component-emitter');
  27652. var toArray = require('to-array');
  27653. var on = require('./on');
  27654. var bind = require('component-bind');
  27655. var debug = require('debug')('socket.io-client:socket');
  27656. var hasBin = require('has-binary');
  27657. /**
  27658. * Module exports.
  27659. */
  27660. module.exports = exports = Socket;
  27661. /**
  27662. * Internal events (blacklisted).
  27663. * These events can't be emitted by the user.
  27664. *
  27665. * @api private
  27666. */
  27667. var events = {
  27668. connect: 1,
  27669. connect_error: 1,
  27670. connect_timeout: 1,
  27671. disconnect: 1,
  27672. error: 1,
  27673. reconnect: 1,
  27674. reconnect_attempt: 1,
  27675. reconnect_failed: 1,
  27676. reconnect_error: 1,
  27677. reconnecting: 1
  27678. };
  27679. /**
  27680. * Shortcut to `Emitter#emit`.
  27681. */
  27682. var emit = Emitter.prototype.emit;
  27683. /**
  27684. * `Socket` constructor.
  27685. *
  27686. * @api public
  27687. */
  27688. function Socket(io, nsp){
  27689. this.io = io;
  27690. this.nsp = nsp;
  27691. this.json = this; // compat
  27692. this.ids = 0;
  27693. this.acks = {};
  27694. if (this.io.autoConnect) this.open();
  27695. this.receiveBuffer = [];
  27696. this.sendBuffer = [];
  27697. this.connected = false;
  27698. this.disconnected = true;
  27699. }
  27700. /**
  27701. * Mix in `Emitter`.
  27702. */
  27703. Emitter(Socket.prototype);
  27704. /**
  27705. * Subscribe to open, close and packet events
  27706. *
  27707. * @api private
  27708. */
  27709. Socket.prototype.subEvents = function() {
  27710. if (this.subs) return;
  27711. var io = this.io;
  27712. this.subs = [
  27713. on(io, 'open', bind(this, 'onopen')),
  27714. on(io, 'packet', bind(this, 'onpacket')),
  27715. on(io, 'close', bind(this, 'onclose'))
  27716. ];
  27717. };
  27718. /**
  27719. * "Opens" the socket.
  27720. *
  27721. * @api public
  27722. */
  27723. Socket.prototype.open =
  27724. Socket.prototype.connect = function(){
  27725. if (this.connected) return this;
  27726. this.subEvents();
  27727. this.io.open(); // ensure open
  27728. if ('open' == this.io.readyState) this.onopen();
  27729. return this;
  27730. };
  27731. /**
  27732. * Sends a `message` event.
  27733. *
  27734. * @return {Socket} self
  27735. * @api public
  27736. */
  27737. Socket.prototype.send = function(){
  27738. var args = toArray(arguments);
  27739. args.unshift('message');
  27740. this.emit.apply(this, args);
  27741. return this;
  27742. };
  27743. /**
  27744. * Override `emit`.
  27745. * If the event is in `events`, it's emitted normally.
  27746. *
  27747. * @param {String} event name
  27748. * @return {Socket} self
  27749. * @api public
  27750. */
  27751. Socket.prototype.emit = function(ev){
  27752. if (events.hasOwnProperty(ev)) {
  27753. emit.apply(this, arguments);
  27754. return this;
  27755. }
  27756. var args = toArray(arguments);
  27757. var parserType = parser.EVENT; // default
  27758. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  27759. var packet = { type: parserType, data: args };
  27760. // event ack callback
  27761. if ('function' == typeof args[args.length - 1]) {
  27762. debug('emitting packet with ack id %d', this.ids);
  27763. this.acks[this.ids] = args.pop();
  27764. packet.id = this.ids++;
  27765. }
  27766. if (this.connected) {
  27767. this.packet(packet);
  27768. } else {
  27769. this.sendBuffer.push(packet);
  27770. }
  27771. return this;
  27772. };
  27773. /**
  27774. * Sends a packet.
  27775. *
  27776. * @param {Object} packet
  27777. * @api private
  27778. */
  27779. Socket.prototype.packet = function(packet){
  27780. packet.nsp = this.nsp;
  27781. this.io.packet(packet);
  27782. };
  27783. /**
  27784. * Called upon engine `open`.
  27785. *
  27786. * @api private
  27787. */
  27788. Socket.prototype.onopen = function(){
  27789. debug('transport is open - connecting');
  27790. // write connect packet if necessary
  27791. if ('/' != this.nsp) {
  27792. this.packet({ type: parser.CONNECT });
  27793. }
  27794. };
  27795. /**
  27796. * Called upon engine `close`.
  27797. *
  27798. * @param {String} reason
  27799. * @api private
  27800. */
  27801. Socket.prototype.onclose = function(reason){
  27802. debug('close (%s)', reason);
  27803. this.connected = false;
  27804. this.disconnected = true;
  27805. delete this.id;
  27806. this.emit('disconnect', reason);
  27807. };
  27808. /**
  27809. * Called with socket packet.
  27810. *
  27811. * @param {Object} packet
  27812. * @api private
  27813. */
  27814. Socket.prototype.onpacket = function(packet){
  27815. if (packet.nsp != this.nsp) return;
  27816. switch (packet.type) {
  27817. case parser.CONNECT:
  27818. this.onconnect();
  27819. break;
  27820. case parser.EVENT:
  27821. this.onevent(packet);
  27822. break;
  27823. case parser.BINARY_EVENT:
  27824. this.onevent(packet);
  27825. break;
  27826. case parser.ACK:
  27827. this.onack(packet);
  27828. break;
  27829. case parser.BINARY_ACK:
  27830. this.onack(packet);
  27831. break;
  27832. case parser.DISCONNECT:
  27833. this.ondisconnect();
  27834. break;
  27835. case parser.ERROR:
  27836. this.emit('error', packet.data);
  27837. break;
  27838. }
  27839. };
  27840. /**
  27841. * Called upon a server event.
  27842. *
  27843. * @param {Object} packet
  27844. * @api private
  27845. */
  27846. Socket.prototype.onevent = function(packet){
  27847. var args = packet.data || [];
  27848. debug('emitting event %j', args);
  27849. if (null != packet.id) {
  27850. debug('attaching ack callback to event');
  27851. args.push(this.ack(packet.id));
  27852. }
  27853. if (this.connected) {
  27854. emit.apply(this, args);
  27855. } else {
  27856. this.receiveBuffer.push(args);
  27857. }
  27858. };
  27859. /**
  27860. * Produces an ack callback to emit with an event.
  27861. *
  27862. * @api private
  27863. */
  27864. Socket.prototype.ack = function(id){
  27865. var self = this;
  27866. var sent = false;
  27867. return function(){
  27868. // prevent double callbacks
  27869. if (sent) return;
  27870. sent = true;
  27871. var args = toArray(arguments);
  27872. debug('sending ack %j', args);
  27873. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  27874. self.packet({
  27875. type: type,
  27876. id: id,
  27877. data: args
  27878. });
  27879. };
  27880. };
  27881. /**
  27882. * Called upon a server acknowlegement.
  27883. *
  27884. * @param {Object} packet
  27885. * @api private
  27886. */
  27887. Socket.prototype.onack = function(packet){
  27888. debug('calling ack %s with %j', packet.id, packet.data);
  27889. var fn = this.acks[packet.id];
  27890. fn.apply(this, packet.data);
  27891. delete this.acks[packet.id];
  27892. };
  27893. /**
  27894. * Called upon server connect.
  27895. *
  27896. * @api private
  27897. */
  27898. Socket.prototype.onconnect = function(){
  27899. this.connected = true;
  27900. this.disconnected = false;
  27901. this.emit('connect');
  27902. this.emitBuffered();
  27903. };
  27904. /**
  27905. * Emit buffered events (received and emitted).
  27906. *
  27907. * @api private
  27908. */
  27909. Socket.prototype.emitBuffered = function(){
  27910. var i;
  27911. for (i = 0; i < this.receiveBuffer.length; i++) {
  27912. emit.apply(this, this.receiveBuffer[i]);
  27913. }
  27914. this.receiveBuffer = [];
  27915. for (i = 0; i < this.sendBuffer.length; i++) {
  27916. this.packet(this.sendBuffer[i]);
  27917. }
  27918. this.sendBuffer = [];
  27919. };
  27920. /**
  27921. * Called upon server disconnect.
  27922. *
  27923. * @api private
  27924. */
  27925. Socket.prototype.ondisconnect = function(){
  27926. debug('server disconnect (%s)', this.nsp);
  27927. this.destroy();
  27928. this.onclose('io server disconnect');
  27929. };
  27930. /**
  27931. * Called upon forced client/server side disconnections,
  27932. * this method ensures the manager stops tracking us and
  27933. * that reconnections don't get triggered for this.
  27934. *
  27935. * @api private.
  27936. */
  27937. Socket.prototype.destroy = function(){
  27938. if (this.subs) {
  27939. // clean subscriptions to avoid reconnections
  27940. for (var i = 0; i < this.subs.length; i++) {
  27941. this.subs[i].destroy();
  27942. }
  27943. this.subs = null;
  27944. }
  27945. this.io.destroy(this);
  27946. };
  27947. /**
  27948. * Disconnects the socket manually.
  27949. *
  27950. * @return {Socket} self
  27951. * @api public
  27952. */
  27953. Socket.prototype.close =
  27954. Socket.prototype.disconnect = function(){
  27955. if (this.connected) {
  27956. debug('performing disconnect (%s)', this.nsp);
  27957. this.packet({ type: parser.DISCONNECT });
  27958. }
  27959. // remove socket from pool
  27960. this.destroy();
  27961. if (this.connected) {
  27962. // fire events
  27963. this.onclose('io client disconnect');
  27964. }
  27965. return this;
  27966. };
  27967. },{"./on":112,"component-bind":116,"component-emitter":117,"debug":118,"has-binary":148,"socket.io-parser":154,"to-array":158}],114:[function(require,module,exports){
  27968. (function (global){
  27969. /**
  27970. * Module dependencies.
  27971. */
  27972. var parseuri = require('parseuri');
  27973. var debug = require('debug')('socket.io-client:url');
  27974. /**
  27975. * Module exports.
  27976. */
  27977. module.exports = url;
  27978. /**
  27979. * URL parser.
  27980. *
  27981. * @param {String} url
  27982. * @param {Object} An object meant to mimic window.location.
  27983. * Defaults to window.location.
  27984. * @api public
  27985. */
  27986. function url(uri, loc){
  27987. var obj = uri;
  27988. // default to window.location
  27989. var loc = loc || global.location;
  27990. if (null == uri) uri = loc.protocol + '//' + loc.host;
  27991. // relative path support
  27992. if ('string' == typeof uri) {
  27993. if ('/' == uri.charAt(0)) {
  27994. if ('/' == uri.charAt(1)) {
  27995. uri = loc.protocol + uri;
  27996. } else {
  27997. uri = loc.hostname + uri;
  27998. }
  27999. }
  28000. if (!/^(https?|wss?):\/\//.test(uri)) {
  28001. debug('protocol-less url %s', uri);
  28002. if ('undefined' != typeof loc) {
  28003. uri = loc.protocol + '//' + uri;
  28004. } else {
  28005. uri = 'https://' + uri;
  28006. }
  28007. }
  28008. // parse
  28009. debug('parse %s', uri);
  28010. obj = parseuri(uri);
  28011. }
  28012. // make sure we treat `localhost:80` and `localhost` equally
  28013. if (!obj.port) {
  28014. if (/^(http|ws)$/.test(obj.protocol)) {
  28015. obj.port = '80';
  28016. }
  28017. else if (/^(http|ws)s$/.test(obj.protocol)) {
  28018. obj.port = '443';
  28019. }
  28020. }
  28021. obj.path = obj.path || '/';
  28022. // define unique id
  28023. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  28024. // define href
  28025. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  28026. return obj;
  28027. }
  28028. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  28029. },{"debug":118,"parseuri":152}],115:[function(require,module,exports){
  28030. /**
  28031. * Expose `Backoff`.
  28032. */
  28033. module.exports = Backoff;
  28034. /**
  28035. * Initialize backoff timer with `opts`.
  28036. *
  28037. * - `min` initial timeout in milliseconds [100]
  28038. * - `max` max timeout [10000]
  28039. * - `jitter` [0]
  28040. * - `factor` [2]
  28041. *
  28042. * @param {Object} opts
  28043. * @api public
  28044. */
  28045. function Backoff(opts) {
  28046. opts = opts || {};
  28047. this.ms = opts.min || 100;
  28048. this.max = opts.max || 10000;
  28049. this.factor = opts.factor || 2;
  28050. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  28051. this.attempts = 0;
  28052. }
  28053. /**
  28054. * Return the backoff duration.
  28055. *
  28056. * @return {Number}
  28057. * @api public
  28058. */
  28059. Backoff.prototype.duration = function(){
  28060. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  28061. if (this.jitter) {
  28062. var rand = Math.random();
  28063. var deviation = Math.floor(rand * this.jitter * ms);
  28064. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  28065. }
  28066. return Math.min(ms, this.max) | 0;
  28067. };
  28068. /**
  28069. * Reset the number of attempts.
  28070. *
  28071. * @api public
  28072. */
  28073. Backoff.prototype.reset = function(){
  28074. this.attempts = 0;
  28075. };
  28076. /**
  28077. * Set the minimum duration
  28078. *
  28079. * @api public
  28080. */
  28081. Backoff.prototype.setMin = function(min){
  28082. this.ms = min;
  28083. };
  28084. /**
  28085. * Set the maximum duration
  28086. *
  28087. * @api public
  28088. */
  28089. Backoff.prototype.setMax = function(max){
  28090. this.max = max;
  28091. };
  28092. /**
  28093. * Set the jitter
  28094. *
  28095. * @api public
  28096. */
  28097. Backoff.prototype.setJitter = function(jitter){
  28098. this.jitter = jitter;
  28099. };
  28100. },{}],116:[function(require,module,exports){
  28101. /**
  28102. * Slice reference.
  28103. */
  28104. var slice = [].slice;
  28105. /**
  28106. * Bind `obj` to `fn`.
  28107. *
  28108. * @param {Object} obj
  28109. * @param {Function|String} fn or string
  28110. * @return {Function}
  28111. * @api public
  28112. */
  28113. module.exports = function(obj, fn){
  28114. if ('string' == typeof fn) fn = obj[fn];
  28115. if ('function' != typeof fn) throw new Error('bind() requires a function');
  28116. var args = slice.call(arguments, 2);
  28117. return function(){
  28118. return fn.apply(obj, args.concat(slice.call(arguments)));
  28119. }
  28120. };
  28121. },{}],117:[function(require,module,exports){
  28122. /**
  28123. * Expose `Emitter`.
  28124. */
  28125. module.exports = Emitter;
  28126. /**
  28127. * Initialize a new `Emitter`.
  28128. *
  28129. * @api public
  28130. */
  28131. function Emitter(obj) {
  28132. if (obj) return mixin(obj);
  28133. };
  28134. /**
  28135. * Mixin the emitter properties.
  28136. *
  28137. * @param {Object} obj
  28138. * @return {Object}
  28139. * @api private
  28140. */
  28141. function mixin(obj) {
  28142. for (var key in Emitter.prototype) {
  28143. obj[key] = Emitter.prototype[key];
  28144. }
  28145. return obj;
  28146. }
  28147. /**
  28148. * Listen on the given `event` with `fn`.
  28149. *
  28150. * @param {String} event
  28151. * @param {Function} fn
  28152. * @return {Emitter}
  28153. * @api public
  28154. */
  28155. Emitter.prototype.on =
  28156. Emitter.prototype.addEventListener = function(event, fn){
  28157. this._callbacks = this._callbacks || {};
  28158. (this._callbacks[event] = this._callbacks[event] || [])
  28159. .push(fn);
  28160. return this;
  28161. };
  28162. /**
  28163. * Adds an `event` listener that will be invoked a single
  28164. * time then automatically removed.
  28165. *
  28166. * @param {String} event
  28167. * @param {Function} fn
  28168. * @return {Emitter}
  28169. * @api public
  28170. */
  28171. Emitter.prototype.once = function(event, fn){
  28172. var self = this;
  28173. this._callbacks = this._callbacks || {};
  28174. function on() {
  28175. self.off(event, on);
  28176. fn.apply(this, arguments);
  28177. }
  28178. on.fn = fn;
  28179. this.on(event, on);
  28180. return this;
  28181. };
  28182. /**
  28183. * Remove the given callback for `event` or all
  28184. * registered callbacks.
  28185. *
  28186. * @param {String} event
  28187. * @param {Function} fn
  28188. * @return {Emitter}
  28189. * @api public
  28190. */
  28191. Emitter.prototype.off =
  28192. Emitter.prototype.removeListener =
  28193. Emitter.prototype.removeAllListeners =
  28194. Emitter.prototype.removeEventListener = function(event, fn){
  28195. this._callbacks = this._callbacks || {};
  28196. // all
  28197. if (0 == arguments.length) {
  28198. this._callbacks = {};
  28199. return this;
  28200. }
  28201. // specific event
  28202. var callbacks = this._callbacks[event];
  28203. if (!callbacks) return this;
  28204. // remove all handlers
  28205. if (1 == arguments.length) {
  28206. delete this._callbacks[event];
  28207. return this;
  28208. }
  28209. // remove specific handler
  28210. var cb;
  28211. for (var i = 0; i < callbacks.length; i++) {
  28212. cb = callbacks[i];
  28213. if (cb === fn || cb.fn === fn) {
  28214. callbacks.splice(i, 1);
  28215. break;
  28216. }
  28217. }
  28218. return this;
  28219. };
  28220. /**
  28221. * Emit `event` with the given args.
  28222. *
  28223. * @param {String} event
  28224. * @param {Mixed} ...
  28225. * @return {Emitter}
  28226. */
  28227. Emitter.prototype.emit = function(event){
  28228. this._callbacks = this._callbacks || {};
  28229. var args = [].slice.call(arguments, 1)
  28230. , callbacks = this._callbacks[event];
  28231. if (callbacks) {
  28232. callbacks = callbacks.slice(0);
  28233. for (var i = 0, len = callbacks.length; i < len; ++i) {
  28234. callbacks[i].apply(this, args);
  28235. }
  28236. }
  28237. return this;
  28238. };
  28239. /**
  28240. * Return array of callbacks for `event`.
  28241. *
  28242. * @param {String} event
  28243. * @return {Array}
  28244. * @api public
  28245. */
  28246. Emitter.prototype.listeners = function(event){
  28247. this._callbacks = this._callbacks || {};
  28248. return this._callbacks[event] || [];
  28249. };
  28250. /**
  28251. * Check if this emitter has `event` handlers.
  28252. *
  28253. * @param {String} event
  28254. * @return {Boolean}
  28255. * @api public
  28256. */
  28257. Emitter.prototype.hasListeners = function(event){
  28258. return !! this.listeners(event).length;
  28259. };
  28260. },{}],118:[function(require,module,exports){
  28261. /**
  28262. * Expose `debug()` as the module.
  28263. */
  28264. module.exports = debug;
  28265. /**
  28266. * Create a debugger with the given `name`.
  28267. *
  28268. * @param {String} name
  28269. * @return {Type}
  28270. * @api public
  28271. */
  28272. function debug(name) {
  28273. if (!debug.enabled(name)) return function(){};
  28274. return function(fmt){
  28275. fmt = coerce(fmt);
  28276. var curr = new Date;
  28277. var ms = curr - (debug[name] || curr);
  28278. debug[name] = curr;
  28279. fmt = name
  28280. + ' '
  28281. + fmt
  28282. + ' +' + debug.humanize(ms);
  28283. // This hackery is required for IE8
  28284. // where `console.log` doesn't have 'apply'
  28285. window.console
  28286. && console.log
  28287. && Function.prototype.apply.call(console.log, console, arguments);
  28288. }
  28289. }
  28290. /**
  28291. * The currently active debug mode names.
  28292. */
  28293. debug.names = [];
  28294. debug.skips = [];
  28295. /**
  28296. * Enables a debug mode by name. This can include modes
  28297. * separated by a colon and wildcards.
  28298. *
  28299. * @param {String} name
  28300. * @api public
  28301. */
  28302. debug.enable = function(name) {
  28303. try {
  28304. localStorage.debug = name;
  28305. } catch(e){}
  28306. var split = (name || '').split(/[\s,]+/)
  28307. , len = split.length;
  28308. for (var i = 0; i < len; i++) {
  28309. name = split[i].replace('*', '.*?');
  28310. if (name[0] === '-') {
  28311. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  28312. }
  28313. else {
  28314. debug.names.push(new RegExp('^' + name + '$'));
  28315. }
  28316. }
  28317. };
  28318. /**
  28319. * Disable debug output.
  28320. *
  28321. * @api public
  28322. */
  28323. debug.disable = function(){
  28324. debug.enable('');
  28325. };
  28326. /**
  28327. * Humanize the given `ms`.
  28328. *
  28329. * @param {Number} m
  28330. * @return {String}
  28331. * @api private
  28332. */
  28333. debug.humanize = function(ms) {
  28334. var sec = 1000
  28335. , min = 60 * 1000
  28336. , hour = 60 * min;
  28337. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  28338. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  28339. if (ms >= sec) return (ms / sec | 0) + 's';
  28340. return ms + 'ms';
  28341. };
  28342. /**
  28343. * Returns true if the given mode name is enabled, false otherwise.
  28344. *
  28345. * @param {String} name
  28346. * @return {Boolean}
  28347. * @api public
  28348. */
  28349. debug.enabled = function(name) {
  28350. for (var i = 0, len = debug.skips.length; i < len; i++) {
  28351. if (debug.skips[i].test(name)) {
  28352. return false;
  28353. }
  28354. }
  28355. for (var i = 0, len = debug.names.length; i < len; i++) {
  28356. if (debug.names[i].test(name)) {
  28357. return true;
  28358. }
  28359. }
  28360. return false;
  28361. };
  28362. /**
  28363. * Coerce `val`.
  28364. */
  28365. function coerce(val) {
  28366. if (val instanceof Error) return val.stack || val.message;
  28367. return val;
  28368. }
  28369. // persist
  28370. try {
  28371. if (window.localStorage) debug.enable(localStorage.debug);
  28372. } catch(e){}
  28373. },{}],119:[function(require,module,exports){
  28374. module.exports = require('./lib/');
  28375. },{"./lib/":120}],120:[function(require,module,exports){
  28376. module.exports = require('./socket');
  28377. /**
  28378. * Exports parser
  28379. *
  28380. * @api public
  28381. *
  28382. */
  28383. module.exports.parser = require('engine.io-parser');
  28384. },{"./socket":121,"engine.io-parser":133}],121:[function(require,module,exports){
  28385. (function (global){
  28386. /**
  28387. * Module dependencies.
  28388. */
  28389. var transports = require('./transports');
  28390. var Emitter = require('component-emitter');
  28391. var debug = require('debug')('engine.io-client:socket');
  28392. var index = require('indexof');
  28393. var parser = require('engine.io-parser');
  28394. var parseuri = require('parseuri');
  28395. var parsejson = require('parsejson');
  28396. var parseqs = require('parseqs');
  28397. /**
  28398. * Module exports.
  28399. */
  28400. module.exports = Socket;
  28401. /**
  28402. * Noop function.
  28403. *
  28404. * @api private
  28405. */
  28406. function noop(){}
  28407. /**
  28408. * Socket constructor.
  28409. *
  28410. * @param {String|Object} uri or options
  28411. * @param {Object} options
  28412. * @api public
  28413. */
  28414. function Socket(uri, opts){
  28415. if (!(this instanceof Socket)) return new Socket(uri, opts);
  28416. opts = opts || {};
  28417. if (uri && 'object' == typeof uri) {
  28418. opts = uri;
  28419. uri = null;
  28420. }
  28421. if (uri) {
  28422. uri = parseuri(uri);
  28423. opts.host = uri.host;
  28424. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  28425. opts.port = uri.port;
  28426. if (uri.query) opts.query = uri.query;
  28427. }
  28428. this.secure = null != opts.secure ? opts.secure :
  28429. (global.location && 'https:' == location.protocol);
  28430. if (opts.host) {
  28431. var pieces = opts.host.split(':');
  28432. opts.hostname = pieces.shift();
  28433. if (pieces.length) {
  28434. opts.port = pieces.pop();
  28435. } else if (!opts.port) {
  28436. // if no port is specified manually, use the protocol default
  28437. opts.port = this.secure ? '443' : '80';
  28438. }
  28439. }
  28440. this.agent = opts.agent || false;
  28441. this.hostname = opts.hostname ||
  28442. (global.location ? location.hostname : 'localhost');
  28443. this.port = opts.port || (global.location && location.port ?
  28444. location.port :
  28445. (this.secure ? 443 : 80));
  28446. this.query = opts.query || {};
  28447. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  28448. this.upgrade = false !== opts.upgrade;
  28449. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  28450. this.forceJSONP = !!opts.forceJSONP;
  28451. this.jsonp = false !== opts.jsonp;
  28452. this.forceBase64 = !!opts.forceBase64;
  28453. this.enablesXDR = !!opts.enablesXDR;
  28454. this.timestampParam = opts.timestampParam || 't';
  28455. this.timestampRequests = opts.timestampRequests;
  28456. this.transports = opts.transports || ['polling', 'websocket'];
  28457. this.readyState = '';
  28458. this.writeBuffer = [];
  28459. this.callbackBuffer = [];
  28460. this.policyPort = opts.policyPort || 843;
  28461. this.rememberUpgrade = opts.rememberUpgrade || false;
  28462. this.binaryType = null;
  28463. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  28464. // SSL options for Node.js client
  28465. this.pfx = opts.pfx || null;
  28466. this.key = opts.key || null;
  28467. this.passphrase = opts.passphrase || null;
  28468. this.cert = opts.cert || null;
  28469. this.ca = opts.ca || null;
  28470. this.ciphers = opts.ciphers || null;
  28471. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  28472. this.open();
  28473. }
  28474. Socket.priorWebsocketSuccess = false;
  28475. /**
  28476. * Mix in `Emitter`.
  28477. */
  28478. Emitter(Socket.prototype);
  28479. /**
  28480. * Protocol version.
  28481. *
  28482. * @api public
  28483. */
  28484. Socket.protocol = parser.protocol; // this is an int
  28485. /**
  28486. * Expose deps for legacy compatibility
  28487. * and standalone browser access.
  28488. */
  28489. Socket.Socket = Socket;
  28490. Socket.Transport = require('./transport');
  28491. Socket.transports = require('./transports');
  28492. Socket.parser = require('engine.io-parser');
  28493. /**
  28494. * Creates transport of the given type.
  28495. *
  28496. * @param {String} transport name
  28497. * @return {Transport}
  28498. * @api private
  28499. */
  28500. Socket.prototype.createTransport = function (name) {
  28501. debug('creating transport "%s"', name);
  28502. var query = clone(this.query);
  28503. // append engine.io protocol identifier
  28504. query.EIO = parser.protocol;
  28505. // transport name
  28506. query.transport = name;
  28507. // session id if we already have one
  28508. if (this.id) query.sid = this.id;
  28509. var transport = new transports[name]({
  28510. agent: this.agent,
  28511. hostname: this.hostname,
  28512. port: this.port,
  28513. secure: this.secure,
  28514. path: this.path,
  28515. query: query,
  28516. forceJSONP: this.forceJSONP,
  28517. jsonp: this.jsonp,
  28518. forceBase64: this.forceBase64,
  28519. enablesXDR: this.enablesXDR,
  28520. timestampRequests: this.timestampRequests,
  28521. timestampParam: this.timestampParam,
  28522. policyPort: this.policyPort,
  28523. socket: this,
  28524. pfx: this.pfx,
  28525. key: this.key,
  28526. passphrase: this.passphrase,
  28527. cert: this.cert,
  28528. ca: this.ca,
  28529. ciphers: this.ciphers,
  28530. rejectUnauthorized: this.rejectUnauthorized
  28531. });
  28532. return transport;
  28533. };
  28534. function clone (obj) {
  28535. var o = {};
  28536. for (var i in obj) {
  28537. if (obj.hasOwnProperty(i)) {
  28538. o[i] = obj[i];
  28539. }
  28540. }
  28541. return o;
  28542. }
  28543. /**
  28544. * Initializes transport to use and starts probe.
  28545. *
  28546. * @api private
  28547. */
  28548. Socket.prototype.open = function () {
  28549. var transport;
  28550. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  28551. transport = 'websocket';
  28552. } else if (0 == this.transports.length) {
  28553. // Emit error on next tick so it can be listened to
  28554. var self = this;
  28555. setTimeout(function() {
  28556. self.emit('error', 'No transports available');
  28557. }, 0);
  28558. return;
  28559. } else {
  28560. transport = this.transports[0];
  28561. }
  28562. this.readyState = 'opening';
  28563. // Retry with the next transport if the transport is disabled (jsonp: false)
  28564. var transport;
  28565. try {
  28566. transport = this.createTransport(transport);
  28567. } catch (e) {
  28568. this.transports.shift();
  28569. this.open();
  28570. return;
  28571. }
  28572. transport.open();
  28573. this.setTransport(transport);
  28574. };
  28575. /**
  28576. * Sets the current transport. Disables the existing one (if any).
  28577. *
  28578. * @api private
  28579. */
  28580. Socket.prototype.setTransport = function(transport){
  28581. debug('setting transport %s', transport.name);
  28582. var self = this;
  28583. if (this.transport) {
  28584. debug('clearing existing transport %s', this.transport.name);
  28585. this.transport.removeAllListeners();
  28586. }
  28587. // set up transport
  28588. this.transport = transport;
  28589. // set up transport listeners
  28590. transport
  28591. .on('drain', function(){
  28592. self.onDrain();
  28593. })
  28594. .on('packet', function(packet){
  28595. self.onPacket(packet);
  28596. })
  28597. .on('error', function(e){
  28598. self.onError(e);
  28599. })
  28600. .on('close', function(){
  28601. self.onClose('transport close');
  28602. });
  28603. };
  28604. /**
  28605. * Probes a transport.
  28606. *
  28607. * @param {String} transport name
  28608. * @api private
  28609. */
  28610. Socket.prototype.probe = function (name) {
  28611. debug('probing transport "%s"', name);
  28612. var transport = this.createTransport(name, { probe: 1 })
  28613. , failed = false
  28614. , self = this;
  28615. Socket.priorWebsocketSuccess = false;
  28616. function onTransportOpen(){
  28617. if (self.onlyBinaryUpgrades) {
  28618. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  28619. failed = failed || upgradeLosesBinary;
  28620. }
  28621. if (failed) return;
  28622. debug('probe transport "%s" opened', name);
  28623. transport.send([{ type: 'ping', data: 'probe' }]);
  28624. transport.once('packet', function (msg) {
  28625. if (failed) return;
  28626. if ('pong' == msg.type && 'probe' == msg.data) {
  28627. debug('probe transport "%s" pong', name);
  28628. self.upgrading = true;
  28629. self.emit('upgrading', transport);
  28630. if (!transport) return;
  28631. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  28632. debug('pausing current transport "%s"', self.transport.name);
  28633. self.transport.pause(function () {
  28634. if (failed) return;
  28635. if ('closed' == self.readyState) return;
  28636. debug('changing transport and sending upgrade packet');
  28637. cleanup();
  28638. self.setTransport(transport);
  28639. transport.send([{ type: 'upgrade' }]);
  28640. self.emit('upgrade', transport);
  28641. transport = null;
  28642. self.upgrading = false;
  28643. self.flush();
  28644. });
  28645. } else {
  28646. debug('probe transport "%s" failed', name);
  28647. var err = new Error('probe error');
  28648. err.transport = transport.name;
  28649. self.emit('upgradeError', err);
  28650. }
  28651. });
  28652. }
  28653. function freezeTransport() {
  28654. if (failed) return;
  28655. // Any callback called by transport should be ignored since now
  28656. failed = true;
  28657. cleanup();
  28658. transport.close();
  28659. transport = null;
  28660. }
  28661. //Handle any error that happens while probing
  28662. function onerror(err) {
  28663. var error = new Error('probe error: ' + err);
  28664. error.transport = transport.name;
  28665. freezeTransport();
  28666. debug('probe transport "%s" failed because of error: %s', name, err);
  28667. self.emit('upgradeError', error);
  28668. }
  28669. function onTransportClose(){
  28670. onerror("transport closed");
  28671. }
  28672. //When the socket is closed while we're probing
  28673. function onclose(){
  28674. onerror("socket closed");
  28675. }
  28676. //When the socket is upgraded while we're probing
  28677. function onupgrade(to){
  28678. if (transport && to.name != transport.name) {
  28679. debug('"%s" works - aborting "%s"', to.name, transport.name);
  28680. freezeTransport();
  28681. }
  28682. }
  28683. //Remove all listeners on the transport and on self
  28684. function cleanup(){
  28685. transport.removeListener('open', onTransportOpen);
  28686. transport.removeListener('error', onerror);
  28687. transport.removeListener('close', onTransportClose);
  28688. self.removeListener('close', onclose);
  28689. self.removeListener('upgrading', onupgrade);
  28690. }
  28691. transport.once('open', onTransportOpen);
  28692. transport.once('error', onerror);
  28693. transport.once('close', onTransportClose);
  28694. this.once('close', onclose);
  28695. this.once('upgrading', onupgrade);
  28696. transport.open();
  28697. };
  28698. /**
  28699. * Called when connection is deemed open.
  28700. *
  28701. * @api public
  28702. */
  28703. Socket.prototype.onOpen = function () {
  28704. debug('socket open');
  28705. this.readyState = 'open';
  28706. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  28707. this.emit('open');
  28708. this.flush();
  28709. // we check for `readyState` in case an `open`
  28710. // listener already closed the socket
  28711. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  28712. debug('starting upgrade probes');
  28713. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  28714. this.probe(this.upgrades[i]);
  28715. }
  28716. }
  28717. };
  28718. /**
  28719. * Handles a packet.
  28720. *
  28721. * @api private
  28722. */
  28723. Socket.prototype.onPacket = function (packet) {
  28724. if ('opening' == this.readyState || 'open' == this.readyState) {
  28725. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  28726. this.emit('packet', packet);
  28727. // Socket is live - any packet counts
  28728. this.emit('heartbeat');
  28729. switch (packet.type) {
  28730. case 'open':
  28731. this.onHandshake(parsejson(packet.data));
  28732. break;
  28733. case 'pong':
  28734. this.setPing();
  28735. break;
  28736. case 'error':
  28737. var err = new Error('server error');
  28738. err.code = packet.data;
  28739. this.emit('error', err);
  28740. break;
  28741. case 'message':
  28742. this.emit('data', packet.data);
  28743. this.emit('message', packet.data);
  28744. break;
  28745. }
  28746. } else {
  28747. debug('packet received with socket readyState "%s"', this.readyState);
  28748. }
  28749. };
  28750. /**
  28751. * Called upon handshake completion.
  28752. *
  28753. * @param {Object} handshake obj
  28754. * @api private
  28755. */
  28756. Socket.prototype.onHandshake = function (data) {
  28757. this.emit('handshake', data);
  28758. this.id = data.sid;
  28759. this.transport.query.sid = data.sid;
  28760. this.upgrades = this.filterUpgrades(data.upgrades);
  28761. this.pingInterval = data.pingInterval;
  28762. this.pingTimeout = data.pingTimeout;
  28763. this.onOpen();
  28764. // In case open handler closes socket
  28765. if ('closed' == this.readyState) return;
  28766. this.setPing();
  28767. // Prolong liveness of socket on heartbeat
  28768. this.removeListener('heartbeat', this.onHeartbeat);
  28769. this.on('heartbeat', this.onHeartbeat);
  28770. };
  28771. /**
  28772. * Resets ping timeout.
  28773. *
  28774. * @api private
  28775. */
  28776. Socket.prototype.onHeartbeat = function (timeout) {
  28777. clearTimeout(this.pingTimeoutTimer);
  28778. var self = this;
  28779. self.pingTimeoutTimer = setTimeout(function () {
  28780. if ('closed' == self.readyState) return;
  28781. self.onClose('ping timeout');
  28782. }, timeout || (self.pingInterval + self.pingTimeout));
  28783. };
  28784. /**
  28785. * Pings server every `this.pingInterval` and expects response
  28786. * within `this.pingTimeout` or closes connection.
  28787. *
  28788. * @api private
  28789. */
  28790. Socket.prototype.setPing = function () {
  28791. var self = this;
  28792. clearTimeout(self.pingIntervalTimer);
  28793. self.pingIntervalTimer = setTimeout(function () {
  28794. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  28795. self.ping();
  28796. self.onHeartbeat(self.pingTimeout);
  28797. }, self.pingInterval);
  28798. };
  28799. /**
  28800. * Sends a ping packet.
  28801. *
  28802. * @api public
  28803. */
  28804. Socket.prototype.ping = function () {
  28805. this.sendPacket('ping');
  28806. };
  28807. /**
  28808. * Called on `drain` event
  28809. *
  28810. * @api private
  28811. */
  28812. Socket.prototype.onDrain = function() {
  28813. for (var i = 0; i < this.prevBufferLen; i++) {
  28814. if (this.callbackBuffer[i]) {
  28815. this.callbackBuffer[i]();
  28816. }
  28817. }
  28818. this.writeBuffer.splice(0, this.prevBufferLen);
  28819. this.callbackBuffer.splice(0, this.prevBufferLen);
  28820. // setting prevBufferLen = 0 is very important
  28821. // for example, when upgrading, upgrade packet is sent over,
  28822. // and a nonzero prevBufferLen could cause problems on `drain`
  28823. this.prevBufferLen = 0;
  28824. if (this.writeBuffer.length == 0) {
  28825. this.emit('drain');
  28826. } else {
  28827. this.flush();
  28828. }
  28829. };
  28830. /**
  28831. * Flush write buffers.
  28832. *
  28833. * @api private
  28834. */
  28835. Socket.prototype.flush = function () {
  28836. if ('closed' != this.readyState && this.transport.writable &&
  28837. !this.upgrading && this.writeBuffer.length) {
  28838. debug('flushing %d packets in socket', this.writeBuffer.length);
  28839. this.transport.send(this.writeBuffer);
  28840. // keep track of current length of writeBuffer
  28841. // splice writeBuffer and callbackBuffer on `drain`
  28842. this.prevBufferLen = this.writeBuffer.length;
  28843. this.emit('flush');
  28844. }
  28845. };
  28846. /**
  28847. * Sends a message.
  28848. *
  28849. * @param {String} message.
  28850. * @param {Function} callback function.
  28851. * @return {Socket} for chaining.
  28852. * @api public
  28853. */
  28854. Socket.prototype.write =
  28855. Socket.prototype.send = function (msg, fn) {
  28856. this.sendPacket('message', msg, fn);
  28857. return this;
  28858. };
  28859. /**
  28860. * Sends a packet.
  28861. *
  28862. * @param {String} packet type.
  28863. * @param {String} data.
  28864. * @param {Function} callback function.
  28865. * @api private
  28866. */
  28867. Socket.prototype.sendPacket = function (type, data, fn) {
  28868. if ('closing' == this.readyState || 'closed' == this.readyState) {
  28869. return;
  28870. }
  28871. var packet = { type: type, data: data };
  28872. this.emit('packetCreate', packet);
  28873. this.writeBuffer.push(packet);
  28874. this.callbackBuffer.push(fn);
  28875. this.flush();
  28876. };
  28877. /**
  28878. * Closes the connection.
  28879. *
  28880. * @api private
  28881. */
  28882. Socket.prototype.close = function () {
  28883. if ('opening' == this.readyState || 'open' == this.readyState) {
  28884. this.readyState = 'closing';
  28885. var self = this;
  28886. function close() {
  28887. self.onClose('forced close');
  28888. debug('socket closing - telling transport to close');
  28889. self.transport.close();
  28890. }
  28891. function cleanupAndClose() {
  28892. self.removeListener('upgrade', cleanupAndClose);
  28893. self.removeListener('upgradeError', cleanupAndClose);
  28894. close();
  28895. }
  28896. function waitForUpgrade() {
  28897. // wait for upgrade to finish since we can't send packets while pausing a transport
  28898. self.once('upgrade', cleanupAndClose);
  28899. self.once('upgradeError', cleanupAndClose);
  28900. }
  28901. if (this.writeBuffer.length) {
  28902. this.once('drain', function() {
  28903. if (this.upgrading) {
  28904. waitForUpgrade();
  28905. } else {
  28906. close();
  28907. }
  28908. });
  28909. } else if (this.upgrading) {
  28910. waitForUpgrade();
  28911. } else {
  28912. close();
  28913. }
  28914. }
  28915. return this;
  28916. };
  28917. /**
  28918. * Called upon transport error
  28919. *
  28920. * @api private
  28921. */
  28922. Socket.prototype.onError = function (err) {
  28923. debug('socket error %j', err);
  28924. Socket.priorWebsocketSuccess = false;
  28925. this.emit('error', err);
  28926. this.onClose('transport error', err);
  28927. };
  28928. /**
  28929. * Called upon transport close.
  28930. *
  28931. * @api private
  28932. */
  28933. Socket.prototype.onClose = function (reason, desc) {
  28934. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  28935. debug('socket close with reason: "%s"', reason);
  28936. var self = this;
  28937. // clear timers
  28938. clearTimeout(this.pingIntervalTimer);
  28939. clearTimeout(this.pingTimeoutTimer);
  28940. // clean buffers in next tick, so developers can still
  28941. // grab the buffers on `close` event
  28942. setTimeout(function() {
  28943. self.writeBuffer = [];
  28944. self.callbackBuffer = [];
  28945. self.prevBufferLen = 0;
  28946. }, 0);
  28947. // stop event from firing again for transport
  28948. this.transport.removeAllListeners('close');
  28949. // ensure transport won't stay open
  28950. this.transport.close();
  28951. // ignore further transport communication
  28952. this.transport.removeAllListeners();
  28953. // set ready state
  28954. this.readyState = 'closed';
  28955. // clear session id
  28956. this.id = null;
  28957. // emit close event
  28958. this.emit('close', reason, desc);
  28959. }
  28960. };
  28961. /**
  28962. * Filters upgrades, returning only those matching client transports.
  28963. *
  28964. * @param {Array} server upgrades
  28965. * @api private
  28966. *
  28967. */
  28968. Socket.prototype.filterUpgrades = function (upgrades) {
  28969. var filteredUpgrades = [];
  28970. for (var i = 0, j = upgrades.length; i<j; i++) {
  28971. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  28972. }
  28973. return filteredUpgrades;
  28974. };
  28975. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  28976. },{"./transport":122,"./transports":123,"component-emitter":117,"debug":130,"engine.io-parser":133,"indexof":150,"parsejson":144,"parseqs":145,"parseuri":146}],122:[function(require,module,exports){
  28977. /**
  28978. * Module dependencies.
  28979. */
  28980. var parser = require('engine.io-parser');
  28981. var Emitter = require('component-emitter');
  28982. /**
  28983. * Module exports.
  28984. */
  28985. module.exports = Transport;
  28986. /**
  28987. * Transport abstract constructor.
  28988. *
  28989. * @param {Object} options.
  28990. * @api private
  28991. */
  28992. function Transport (opts) {
  28993. this.path = opts.path;
  28994. this.hostname = opts.hostname;
  28995. this.port = opts.port;
  28996. this.secure = opts.secure;
  28997. this.query = opts.query;
  28998. this.timestampParam = opts.timestampParam;
  28999. this.timestampRequests = opts.timestampRequests;
  29000. this.readyState = '';
  29001. this.agent = opts.agent || false;
  29002. this.socket = opts.socket;
  29003. this.enablesXDR = opts.enablesXDR;
  29004. // SSL options for Node.js client
  29005. this.pfx = opts.pfx;
  29006. this.key = opts.key;
  29007. this.passphrase = opts.passphrase;
  29008. this.cert = opts.cert;
  29009. this.ca = opts.ca;
  29010. this.ciphers = opts.ciphers;
  29011. this.rejectUnauthorized = opts.rejectUnauthorized;
  29012. }
  29013. /**
  29014. * Mix in `Emitter`.
  29015. */
  29016. Emitter(Transport.prototype);
  29017. /**
  29018. * A counter used to prevent collisions in the timestamps used
  29019. * for cache busting.
  29020. */
  29021. Transport.timestamps = 0;
  29022. /**
  29023. * Emits an error.
  29024. *
  29025. * @param {String} str
  29026. * @return {Transport} for chaining
  29027. * @api public
  29028. */
  29029. Transport.prototype.onError = function (msg, desc) {
  29030. var err = new Error(msg);
  29031. err.type = 'TransportError';
  29032. err.description = desc;
  29033. this.emit('error', err);
  29034. return this;
  29035. };
  29036. /**
  29037. * Opens the transport.
  29038. *
  29039. * @api public
  29040. */
  29041. Transport.prototype.open = function () {
  29042. if ('closed' == this.readyState || '' == this.readyState) {
  29043. this.readyState = 'opening';
  29044. this.doOpen();
  29045. }
  29046. return this;
  29047. };
  29048. /**
  29049. * Closes the transport.
  29050. *
  29051. * @api private
  29052. */
  29053. Transport.prototype.close = function () {
  29054. if ('opening' == this.readyState || 'open' == this.readyState) {
  29055. this.doClose();
  29056. this.onClose();
  29057. }
  29058. return this;
  29059. };
  29060. /**
  29061. * Sends multiple packets.
  29062. *
  29063. * @param {Array} packets
  29064. * @api private
  29065. */
  29066. Transport.prototype.send = function(packets){
  29067. if ('open' == this.readyState) {
  29068. this.write(packets);
  29069. } else {
  29070. throw new Error('Transport not open');
  29071. }
  29072. };
  29073. /**
  29074. * Called upon open
  29075. *
  29076. * @api private
  29077. */
  29078. Transport.prototype.onOpen = function () {
  29079. this.readyState = 'open';
  29080. this.writable = true;
  29081. this.emit('open');
  29082. };
  29083. /**
  29084. * Called with data.
  29085. *
  29086. * @param {String} data
  29087. * @api private
  29088. */
  29089. Transport.prototype.onData = function(data){
  29090. var packet = parser.decodePacket(data, this.socket.binaryType);
  29091. this.onPacket(packet);
  29092. };
  29093. /**
  29094. * Called with a decoded packet.
  29095. */
  29096. Transport.prototype.onPacket = function (packet) {
  29097. this.emit('packet', packet);
  29098. };
  29099. /**
  29100. * Called upon close.
  29101. *
  29102. * @api private
  29103. */
  29104. Transport.prototype.onClose = function () {
  29105. this.readyState = 'closed';
  29106. this.emit('close');
  29107. };
  29108. },{"component-emitter":117,"engine.io-parser":133}],123:[function(require,module,exports){
  29109. (function (global){
  29110. /**
  29111. * Module dependencies
  29112. */
  29113. var XMLHttpRequest = require('xmlhttprequest');
  29114. var XHR = require('./polling-xhr');
  29115. var JSONP = require('./polling-jsonp');
  29116. var websocket = require('./websocket');
  29117. /**
  29118. * Export transports.
  29119. */
  29120. exports.polling = polling;
  29121. exports.websocket = websocket;
  29122. /**
  29123. * Polling transport polymorphic constructor.
  29124. * Decides on xhr vs jsonp based on feature detection.
  29125. *
  29126. * @api private
  29127. */
  29128. function polling(opts){
  29129. var xhr;
  29130. var xd = false;
  29131. var xs = false;
  29132. var jsonp = false !== opts.jsonp;
  29133. if (global.location) {
  29134. var isSSL = 'https:' == location.protocol;
  29135. var port = location.port;
  29136. // some user agents have empty `location.port`
  29137. if (!port) {
  29138. port = isSSL ? 443 : 80;
  29139. }
  29140. xd = opts.hostname != location.hostname || port != opts.port;
  29141. xs = opts.secure != isSSL;
  29142. }
  29143. opts.xdomain = xd;
  29144. opts.xscheme = xs;
  29145. xhr = new XMLHttpRequest(opts);
  29146. if ('open' in xhr && !opts.forceJSONP) {
  29147. return new XHR(opts);
  29148. } else {
  29149. if (!jsonp) throw new Error('JSONP disabled');
  29150. return new JSONP(opts);
  29151. }
  29152. }
  29153. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29154. },{"./polling-jsonp":124,"./polling-xhr":125,"./websocket":127,"xmlhttprequest":128}],124:[function(require,module,exports){
  29155. (function (global){
  29156. /**
  29157. * Module requirements.
  29158. */
  29159. var Polling = require('./polling');
  29160. var inherit = require('component-inherit');
  29161. /**
  29162. * Module exports.
  29163. */
  29164. module.exports = JSONPPolling;
  29165. /**
  29166. * Cached regular expressions.
  29167. */
  29168. var rNewline = /\n/g;
  29169. var rEscapedNewline = /\\n/g;
  29170. /**
  29171. * Global JSONP callbacks.
  29172. */
  29173. var callbacks;
  29174. /**
  29175. * Callbacks count.
  29176. */
  29177. var index = 0;
  29178. /**
  29179. * Noop.
  29180. */
  29181. function empty () { }
  29182. /**
  29183. * JSONP Polling constructor.
  29184. *
  29185. * @param {Object} opts.
  29186. * @api public
  29187. */
  29188. function JSONPPolling (opts) {
  29189. Polling.call(this, opts);
  29190. this.query = this.query || {};
  29191. // define global callbacks array if not present
  29192. // we do this here (lazily) to avoid unneeded global pollution
  29193. if (!callbacks) {
  29194. // we need to consider multiple engines in the same page
  29195. if (!global.___eio) global.___eio = [];
  29196. callbacks = global.___eio;
  29197. }
  29198. // callback identifier
  29199. this.index = callbacks.length;
  29200. // add callback to jsonp global
  29201. var self = this;
  29202. callbacks.push(function (msg) {
  29203. self.onData(msg);
  29204. });
  29205. // append to query string
  29206. this.query.j = this.index;
  29207. // prevent spurious errors from being emitted when the window is unloaded
  29208. if (global.document && global.addEventListener) {
  29209. global.addEventListener('beforeunload', function () {
  29210. if (self.script) self.script.onerror = empty;
  29211. }, false);
  29212. }
  29213. }
  29214. /**
  29215. * Inherits from Polling.
  29216. */
  29217. inherit(JSONPPolling, Polling);
  29218. /*
  29219. * JSONP only supports binary as base64 encoded strings
  29220. */
  29221. JSONPPolling.prototype.supportsBinary = false;
  29222. /**
  29223. * Closes the socket.
  29224. *
  29225. * @api private
  29226. */
  29227. JSONPPolling.prototype.doClose = function () {
  29228. if (this.script) {
  29229. this.script.parentNode.removeChild(this.script);
  29230. this.script = null;
  29231. }
  29232. if (this.form) {
  29233. this.form.parentNode.removeChild(this.form);
  29234. this.form = null;
  29235. this.iframe = null;
  29236. }
  29237. Polling.prototype.doClose.call(this);
  29238. };
  29239. /**
  29240. * Starts a poll cycle.
  29241. *
  29242. * @api private
  29243. */
  29244. JSONPPolling.prototype.doPoll = function () {
  29245. var self = this;
  29246. var script = document.createElement('script');
  29247. if (this.script) {
  29248. this.script.parentNode.removeChild(this.script);
  29249. this.script = null;
  29250. }
  29251. script.async = true;
  29252. script.src = this.uri();
  29253. script.onerror = function(e){
  29254. self.onError('jsonp poll error',e);
  29255. };
  29256. var insertAt = document.getElementsByTagName('script')[0];
  29257. insertAt.parentNode.insertBefore(script, insertAt);
  29258. this.script = script;
  29259. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  29260. if (isUAgecko) {
  29261. setTimeout(function () {
  29262. var iframe = document.createElement('iframe');
  29263. document.body.appendChild(iframe);
  29264. document.body.removeChild(iframe);
  29265. }, 100);
  29266. }
  29267. };
  29268. /**
  29269. * Writes with a hidden iframe.
  29270. *
  29271. * @param {String} data to send
  29272. * @param {Function} called upon flush.
  29273. * @api private
  29274. */
  29275. JSONPPolling.prototype.doWrite = function (data, fn) {
  29276. var self = this;
  29277. if (!this.form) {
  29278. var form = document.createElement('form');
  29279. var area = document.createElement('textarea');
  29280. var id = this.iframeId = 'eio_iframe_' + this.index;
  29281. var iframe;
  29282. form.className = 'socketio';
  29283. form.style.position = 'absolute';
  29284. form.style.top = '-1000px';
  29285. form.style.left = '-1000px';
  29286. form.target = id;
  29287. form.method = 'POST';
  29288. form.setAttribute('accept-charset', 'utf-8');
  29289. area.name = 'd';
  29290. form.appendChild(area);
  29291. document.body.appendChild(form);
  29292. this.form = form;
  29293. this.area = area;
  29294. }
  29295. this.form.action = this.uri();
  29296. function complete () {
  29297. initIframe();
  29298. fn();
  29299. }
  29300. function initIframe () {
  29301. if (self.iframe) {
  29302. try {
  29303. self.form.removeChild(self.iframe);
  29304. } catch (e) {
  29305. self.onError('jsonp polling iframe removal error', e);
  29306. }
  29307. }
  29308. try {
  29309. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  29310. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  29311. iframe = document.createElement(html);
  29312. } catch (e) {
  29313. iframe = document.createElement('iframe');
  29314. iframe.name = self.iframeId;
  29315. iframe.src = 'javascript:0';
  29316. }
  29317. iframe.id = self.iframeId;
  29318. self.form.appendChild(iframe);
  29319. self.iframe = iframe;
  29320. }
  29321. initIframe();
  29322. // escape \n to prevent it from being converted into \r\n by some UAs
  29323. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  29324. data = data.replace(rEscapedNewline, '\\\n');
  29325. this.area.value = data.replace(rNewline, '\\n');
  29326. try {
  29327. this.form.submit();
  29328. } catch(e) {}
  29329. if (this.iframe.attachEvent) {
  29330. this.iframe.onreadystatechange = function(){
  29331. if (self.iframe.readyState == 'complete') {
  29332. complete();
  29333. }
  29334. };
  29335. } else {
  29336. this.iframe.onload = complete;
  29337. }
  29338. };
  29339. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29340. },{"./polling":126,"component-inherit":129}],125:[function(require,module,exports){
  29341. (function (global){
  29342. /**
  29343. * Module requirements.
  29344. */
  29345. var XMLHttpRequest = require('xmlhttprequest');
  29346. var Polling = require('./polling');
  29347. var Emitter = require('component-emitter');
  29348. var inherit = require('component-inherit');
  29349. var debug = require('debug')('engine.io-client:polling-xhr');
  29350. /**
  29351. * Module exports.
  29352. */
  29353. module.exports = XHR;
  29354. module.exports.Request = Request;
  29355. /**
  29356. * Empty function
  29357. */
  29358. function empty(){}
  29359. /**
  29360. * XHR Polling constructor.
  29361. *
  29362. * @param {Object} opts
  29363. * @api public
  29364. */
  29365. function XHR(opts){
  29366. Polling.call(this, opts);
  29367. if (global.location) {
  29368. var isSSL = 'https:' == location.protocol;
  29369. var port = location.port;
  29370. // some user agents have empty `location.port`
  29371. if (!port) {
  29372. port = isSSL ? 443 : 80;
  29373. }
  29374. this.xd = opts.hostname != global.location.hostname ||
  29375. port != opts.port;
  29376. this.xs = opts.secure != isSSL;
  29377. }
  29378. }
  29379. /**
  29380. * Inherits from Polling.
  29381. */
  29382. inherit(XHR, Polling);
  29383. /**
  29384. * XHR supports binary
  29385. */
  29386. XHR.prototype.supportsBinary = true;
  29387. /**
  29388. * Creates a request.
  29389. *
  29390. * @param {String} method
  29391. * @api private
  29392. */
  29393. XHR.prototype.request = function(opts){
  29394. opts = opts || {};
  29395. opts.uri = this.uri();
  29396. opts.xd = this.xd;
  29397. opts.xs = this.xs;
  29398. opts.agent = this.agent || false;
  29399. opts.supportsBinary = this.supportsBinary;
  29400. opts.enablesXDR = this.enablesXDR;
  29401. // SSL options for Node.js client
  29402. opts.pfx = this.pfx;
  29403. opts.key = this.key;
  29404. opts.passphrase = this.passphrase;
  29405. opts.cert = this.cert;
  29406. opts.ca = this.ca;
  29407. opts.ciphers = this.ciphers;
  29408. opts.rejectUnauthorized = this.rejectUnauthorized;
  29409. return new Request(opts);
  29410. };
  29411. /**
  29412. * Sends data.
  29413. *
  29414. * @param {String} data to send.
  29415. * @param {Function} called upon flush.
  29416. * @api private
  29417. */
  29418. XHR.prototype.doWrite = function(data, fn){
  29419. var isBinary = typeof data !== 'string' && data !== undefined;
  29420. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  29421. var self = this;
  29422. req.on('success', fn);
  29423. req.on('error', function(err){
  29424. self.onError('xhr post error', err);
  29425. });
  29426. this.sendXhr = req;
  29427. };
  29428. /**
  29429. * Starts a poll cycle.
  29430. *
  29431. * @api private
  29432. */
  29433. XHR.prototype.doPoll = function(){
  29434. debug('xhr poll');
  29435. var req = this.request();
  29436. var self = this;
  29437. req.on('data', function(data){
  29438. self.onData(data);
  29439. });
  29440. req.on('error', function(err){
  29441. self.onError('xhr poll error', err);
  29442. });
  29443. this.pollXhr = req;
  29444. };
  29445. /**
  29446. * Request constructor
  29447. *
  29448. * @param {Object} options
  29449. * @api public
  29450. */
  29451. function Request(opts){
  29452. this.method = opts.method || 'GET';
  29453. this.uri = opts.uri;
  29454. this.xd = !!opts.xd;
  29455. this.xs = !!opts.xs;
  29456. this.async = false !== opts.async;
  29457. this.data = undefined != opts.data ? opts.data : null;
  29458. this.agent = opts.agent;
  29459. this.isBinary = opts.isBinary;
  29460. this.supportsBinary = opts.supportsBinary;
  29461. this.enablesXDR = opts.enablesXDR;
  29462. // SSL options for Node.js client
  29463. this.pfx = opts.pfx;
  29464. this.key = opts.key;
  29465. this.passphrase = opts.passphrase;
  29466. this.cert = opts.cert;
  29467. this.ca = opts.ca;
  29468. this.ciphers = opts.ciphers;
  29469. this.rejectUnauthorized = opts.rejectUnauthorized;
  29470. this.create();
  29471. }
  29472. /**
  29473. * Mix in `Emitter`.
  29474. */
  29475. Emitter(Request.prototype);
  29476. /**
  29477. * Creates the XHR object and sends the request.
  29478. *
  29479. * @api private
  29480. */
  29481. Request.prototype.create = function(){
  29482. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  29483. // SSL options for Node.js client
  29484. opts.pfx = this.pfx;
  29485. opts.key = this.key;
  29486. opts.passphrase = this.passphrase;
  29487. opts.cert = this.cert;
  29488. opts.ca = this.ca;
  29489. opts.ciphers = this.ciphers;
  29490. opts.rejectUnauthorized = this.rejectUnauthorized;
  29491. var xhr = this.xhr = new XMLHttpRequest(opts);
  29492. var self = this;
  29493. try {
  29494. debug('xhr open %s: %s', this.method, this.uri);
  29495. xhr.open(this.method, this.uri, this.async);
  29496. if (this.supportsBinary) {
  29497. // This has to be done after open because Firefox is stupid
  29498. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  29499. xhr.responseType = 'arraybuffer';
  29500. }
  29501. if ('POST' == this.method) {
  29502. try {
  29503. if (this.isBinary) {
  29504. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  29505. } else {
  29506. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  29507. }
  29508. } catch (e) {}
  29509. }
  29510. // ie6 check
  29511. if ('withCredentials' in xhr) {
  29512. xhr.withCredentials = true;
  29513. }
  29514. if (this.hasXDR()) {
  29515. xhr.onload = function(){
  29516. self.onLoad();
  29517. };
  29518. xhr.onerror = function(){
  29519. self.onError(xhr.responseText);
  29520. };
  29521. } else {
  29522. xhr.onreadystatechange = function(){
  29523. if (4 != xhr.readyState) return;
  29524. if (200 == xhr.status || 1223 == xhr.status) {
  29525. self.onLoad();
  29526. } else {
  29527. // make sure the `error` event handler that's user-set
  29528. // does not throw in the same tick and gets caught here
  29529. setTimeout(function(){
  29530. self.onError(xhr.status);
  29531. }, 0);
  29532. }
  29533. };
  29534. }
  29535. debug('xhr data %s', this.data);
  29536. xhr.send(this.data);
  29537. } catch (e) {
  29538. // Need to defer since .create() is called directly fhrom the constructor
  29539. // and thus the 'error' event can only be only bound *after* this exception
  29540. // occurs. Therefore, also, we cannot throw here at all.
  29541. setTimeout(function() {
  29542. self.onError(e);
  29543. }, 0);
  29544. return;
  29545. }
  29546. if (global.document) {
  29547. this.index = Request.requestsCount++;
  29548. Request.requests[this.index] = this;
  29549. }
  29550. };
  29551. /**
  29552. * Called upon successful response.
  29553. *
  29554. * @api private
  29555. */
  29556. Request.prototype.onSuccess = function(){
  29557. this.emit('success');
  29558. this.cleanup();
  29559. };
  29560. /**
  29561. * Called if we have data.
  29562. *
  29563. * @api private
  29564. */
  29565. Request.prototype.onData = function(data){
  29566. this.emit('data', data);
  29567. this.onSuccess();
  29568. };
  29569. /**
  29570. * Called upon error.
  29571. *
  29572. * @api private
  29573. */
  29574. Request.prototype.onError = function(err){
  29575. this.emit('error', err);
  29576. this.cleanup(true);
  29577. };
  29578. /**
  29579. * Cleans up house.
  29580. *
  29581. * @api private
  29582. */
  29583. Request.prototype.cleanup = function(fromError){
  29584. if ('undefined' == typeof this.xhr || null === this.xhr) {
  29585. return;
  29586. }
  29587. // xmlhttprequest
  29588. if (this.hasXDR()) {
  29589. this.xhr.onload = this.xhr.onerror = empty;
  29590. } else {
  29591. this.xhr.onreadystatechange = empty;
  29592. }
  29593. if (fromError) {
  29594. try {
  29595. this.xhr.abort();
  29596. } catch(e) {}
  29597. }
  29598. if (global.document) {
  29599. delete Request.requests[this.index];
  29600. }
  29601. this.xhr = null;
  29602. };
  29603. /**
  29604. * Called upon load.
  29605. *
  29606. * @api private
  29607. */
  29608. Request.prototype.onLoad = function(){
  29609. var data;
  29610. try {
  29611. var contentType;
  29612. try {
  29613. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  29614. } catch (e) {}
  29615. if (contentType === 'application/octet-stream') {
  29616. data = this.xhr.response;
  29617. } else {
  29618. if (!this.supportsBinary) {
  29619. data = this.xhr.responseText;
  29620. } else {
  29621. data = 'ok';
  29622. }
  29623. }
  29624. } catch (e) {
  29625. this.onError(e);
  29626. }
  29627. if (null != data) {
  29628. this.onData(data);
  29629. }
  29630. };
  29631. /**
  29632. * Check if it has XDomainRequest.
  29633. *
  29634. * @api private
  29635. */
  29636. Request.prototype.hasXDR = function(){
  29637. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  29638. };
  29639. /**
  29640. * Aborts the request.
  29641. *
  29642. * @api public
  29643. */
  29644. Request.prototype.abort = function(){
  29645. this.cleanup();
  29646. };
  29647. /**
  29648. * Aborts pending requests when unloading the window. This is needed to prevent
  29649. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  29650. * emitted.
  29651. */
  29652. if (global.document) {
  29653. Request.requestsCount = 0;
  29654. Request.requests = {};
  29655. if (global.attachEvent) {
  29656. global.attachEvent('onunload', unloadHandler);
  29657. } else if (global.addEventListener) {
  29658. global.addEventListener('beforeunload', unloadHandler, false);
  29659. }
  29660. }
  29661. function unloadHandler() {
  29662. for (var i in Request.requests) {
  29663. if (Request.requests.hasOwnProperty(i)) {
  29664. Request.requests[i].abort();
  29665. }
  29666. }
  29667. }
  29668. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29669. },{"./polling":126,"component-emitter":117,"component-inherit":129,"debug":130,"xmlhttprequest":128}],126:[function(require,module,exports){
  29670. /**
  29671. * Module dependencies.
  29672. */
  29673. var Transport = require('../transport');
  29674. var parseqs = require('parseqs');
  29675. var parser = require('engine.io-parser');
  29676. var inherit = require('component-inherit');
  29677. var debug = require('debug')('engine.io-client:polling');
  29678. /**
  29679. * Module exports.
  29680. */
  29681. module.exports = Polling;
  29682. /**
  29683. * Is XHR2 supported?
  29684. */
  29685. var hasXHR2 = (function() {
  29686. var XMLHttpRequest = require('xmlhttprequest');
  29687. var xhr = new XMLHttpRequest({ xdomain: false });
  29688. return null != xhr.responseType;
  29689. })();
  29690. /**
  29691. * Polling interface.
  29692. *
  29693. * @param {Object} opts
  29694. * @api private
  29695. */
  29696. function Polling(opts){
  29697. var forceBase64 = (opts && opts.forceBase64);
  29698. if (!hasXHR2 || forceBase64) {
  29699. this.supportsBinary = false;
  29700. }
  29701. Transport.call(this, opts);
  29702. }
  29703. /**
  29704. * Inherits from Transport.
  29705. */
  29706. inherit(Polling, Transport);
  29707. /**
  29708. * Transport name.
  29709. */
  29710. Polling.prototype.name = 'polling';
  29711. /**
  29712. * Opens the socket (triggers polling). We write a PING message to determine
  29713. * when the transport is open.
  29714. *
  29715. * @api private
  29716. */
  29717. Polling.prototype.doOpen = function(){
  29718. this.poll();
  29719. };
  29720. /**
  29721. * Pauses polling.
  29722. *
  29723. * @param {Function} callback upon buffers are flushed and transport is paused
  29724. * @api private
  29725. */
  29726. Polling.prototype.pause = function(onPause){
  29727. var pending = 0;
  29728. var self = this;
  29729. this.readyState = 'pausing';
  29730. function pause(){
  29731. debug('paused');
  29732. self.readyState = 'paused';
  29733. onPause();
  29734. }
  29735. if (this.polling || !this.writable) {
  29736. var total = 0;
  29737. if (this.polling) {
  29738. debug('we are currently polling - waiting to pause');
  29739. total++;
  29740. this.once('pollComplete', function(){
  29741. debug('pre-pause polling complete');
  29742. --total || pause();
  29743. });
  29744. }
  29745. if (!this.writable) {
  29746. debug('we are currently writing - waiting to pause');
  29747. total++;
  29748. this.once('drain', function(){
  29749. debug('pre-pause writing complete');
  29750. --total || pause();
  29751. });
  29752. }
  29753. } else {
  29754. pause();
  29755. }
  29756. };
  29757. /**
  29758. * Starts polling cycle.
  29759. *
  29760. * @api public
  29761. */
  29762. Polling.prototype.poll = function(){
  29763. debug('polling');
  29764. this.polling = true;
  29765. this.doPoll();
  29766. this.emit('poll');
  29767. };
  29768. /**
  29769. * Overloads onData to detect payloads.
  29770. *
  29771. * @api private
  29772. */
  29773. Polling.prototype.onData = function(data){
  29774. var self = this;
  29775. debug('polling got data %s', data);
  29776. var callback = function(packet, index, total) {
  29777. // if its the first message we consider the transport open
  29778. if ('opening' == self.readyState) {
  29779. self.onOpen();
  29780. }
  29781. // if its a close packet, we close the ongoing requests
  29782. if ('close' == packet.type) {
  29783. self.onClose();
  29784. return false;
  29785. }
  29786. // otherwise bypass onData and handle the message
  29787. self.onPacket(packet);
  29788. };
  29789. // decode payload
  29790. parser.decodePayload(data, this.socket.binaryType, callback);
  29791. // if an event did not trigger closing
  29792. if ('closed' != this.readyState) {
  29793. // if we got data we're not polling
  29794. this.polling = false;
  29795. this.emit('pollComplete');
  29796. if ('open' == this.readyState) {
  29797. this.poll();
  29798. } else {
  29799. debug('ignoring poll - transport state "%s"', this.readyState);
  29800. }
  29801. }
  29802. };
  29803. /**
  29804. * For polling, send a close packet.
  29805. *
  29806. * @api private
  29807. */
  29808. Polling.prototype.doClose = function(){
  29809. var self = this;
  29810. function close(){
  29811. debug('writing close packet');
  29812. self.write([{ type: 'close' }]);
  29813. }
  29814. if ('open' == this.readyState) {
  29815. debug('transport open - closing');
  29816. close();
  29817. } else {
  29818. // in case we're trying to close while
  29819. // handshaking is in progress (GH-164)
  29820. debug('transport not open - deferring close');
  29821. this.once('open', close);
  29822. }
  29823. };
  29824. /**
  29825. * Writes a packets payload.
  29826. *
  29827. * @param {Array} data packets
  29828. * @param {Function} drain callback
  29829. * @api private
  29830. */
  29831. Polling.prototype.write = function(packets){
  29832. var self = this;
  29833. this.writable = false;
  29834. var callbackfn = function() {
  29835. self.writable = true;
  29836. self.emit('drain');
  29837. };
  29838. var self = this;
  29839. parser.encodePayload(packets, this.supportsBinary, function(data) {
  29840. self.doWrite(data, callbackfn);
  29841. });
  29842. };
  29843. /**
  29844. * Generates uri for connection.
  29845. *
  29846. * @api private
  29847. */
  29848. Polling.prototype.uri = function(){
  29849. var query = this.query || {};
  29850. var schema = this.secure ? 'https' : 'http';
  29851. var port = '';
  29852. // cache busting is forced
  29853. if (false !== this.timestampRequests) {
  29854. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  29855. }
  29856. if (!this.supportsBinary && !query.sid) {
  29857. query.b64 = 1;
  29858. }
  29859. query = parseqs.encode(query);
  29860. // avoid port if default for schema
  29861. if (this.port && (('https' == schema && this.port != 443) ||
  29862. ('http' == schema && this.port != 80))) {
  29863. port = ':' + this.port;
  29864. }
  29865. // prepend ? to query
  29866. if (query.length) {
  29867. query = '?' + query;
  29868. }
  29869. return schema + '://' + this.hostname + port + this.path + query;
  29870. };
  29871. },{"../transport":122,"component-inherit":129,"debug":130,"engine.io-parser":133,"parseqs":145,"xmlhttprequest":128}],127:[function(require,module,exports){
  29872. /**
  29873. * Module dependencies.
  29874. */
  29875. var Transport = require('../transport');
  29876. var parser = require('engine.io-parser');
  29877. var parseqs = require('parseqs');
  29878. var inherit = require('component-inherit');
  29879. var debug = require('debug')('engine.io-client:websocket');
  29880. /**
  29881. * `ws` exposes a WebSocket-compatible interface in
  29882. * Node, or the `WebSocket` or `MozWebSocket` globals
  29883. * in the browser.
  29884. */
  29885. var WebSocket = require('ws');
  29886. /**
  29887. * Module exports.
  29888. */
  29889. module.exports = WS;
  29890. /**
  29891. * WebSocket transport constructor.
  29892. *
  29893. * @api {Object} connection options
  29894. * @api public
  29895. */
  29896. function WS(opts){
  29897. var forceBase64 = (opts && opts.forceBase64);
  29898. if (forceBase64) {
  29899. this.supportsBinary = false;
  29900. }
  29901. Transport.call(this, opts);
  29902. }
  29903. /**
  29904. * Inherits from Transport.
  29905. */
  29906. inherit(WS, Transport);
  29907. /**
  29908. * Transport name.
  29909. *
  29910. * @api public
  29911. */
  29912. WS.prototype.name = 'websocket';
  29913. /*
  29914. * WebSockets support binary
  29915. */
  29916. WS.prototype.supportsBinary = true;
  29917. /**
  29918. * Opens socket.
  29919. *
  29920. * @api private
  29921. */
  29922. WS.prototype.doOpen = function(){
  29923. if (!this.check()) {
  29924. // let probe timeout
  29925. return;
  29926. }
  29927. var self = this;
  29928. var uri = this.uri();
  29929. var protocols = void(0);
  29930. var opts = { agent: this.agent };
  29931. // SSL options for Node.js client
  29932. opts.pfx = this.pfx;
  29933. opts.key = this.key;
  29934. opts.passphrase = this.passphrase;
  29935. opts.cert = this.cert;
  29936. opts.ca = this.ca;
  29937. opts.ciphers = this.ciphers;
  29938. opts.rejectUnauthorized = this.rejectUnauthorized;
  29939. this.ws = new WebSocket(uri, protocols, opts);
  29940. if (this.ws.binaryType === undefined) {
  29941. this.supportsBinary = false;
  29942. }
  29943. this.ws.binaryType = 'arraybuffer';
  29944. this.addEventListeners();
  29945. };
  29946. /**
  29947. * Adds event listeners to the socket
  29948. *
  29949. * @api private
  29950. */
  29951. WS.prototype.addEventListeners = function(){
  29952. var self = this;
  29953. this.ws.onopen = function(){
  29954. self.onOpen();
  29955. };
  29956. this.ws.onclose = function(){
  29957. self.onClose();
  29958. };
  29959. this.ws.onmessage = function(ev){
  29960. self.onData(ev.data);
  29961. };
  29962. this.ws.onerror = function(e){
  29963. self.onError('websocket error', e);
  29964. };
  29965. };
  29966. /**
  29967. * Override `onData` to use a timer on iOS.
  29968. * See: https://gist.github.com/mloughran/2052006
  29969. *
  29970. * @api private
  29971. */
  29972. if ('undefined' != typeof navigator
  29973. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  29974. WS.prototype.onData = function(data){
  29975. var self = this;
  29976. setTimeout(function(){
  29977. Transport.prototype.onData.call(self, data);
  29978. }, 0);
  29979. };
  29980. }
  29981. /**
  29982. * Writes data to socket.
  29983. *
  29984. * @param {Array} array of packets.
  29985. * @api private
  29986. */
  29987. WS.prototype.write = function(packets){
  29988. var self = this;
  29989. this.writable = false;
  29990. // encodePacket efficient as it uses WS framing
  29991. // no need for encodePayload
  29992. for (var i = 0, l = packets.length; i < l; i++) {
  29993. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  29994. //Sometimes the websocket has already been closed but the browser didn't
  29995. //have a chance of informing us about it yet, in that case send will
  29996. //throw an error
  29997. try {
  29998. self.ws.send(data);
  29999. } catch (e){
  30000. debug('websocket closed before onclose event');
  30001. }
  30002. });
  30003. }
  30004. function ondrain() {
  30005. self.writable = true;
  30006. self.emit('drain');
  30007. }
  30008. // fake drain
  30009. // defer to next tick to allow Socket to clear writeBuffer
  30010. setTimeout(ondrain, 0);
  30011. };
  30012. /**
  30013. * Called upon close
  30014. *
  30015. * @api private
  30016. */
  30017. WS.prototype.onClose = function(){
  30018. Transport.prototype.onClose.call(this);
  30019. };
  30020. /**
  30021. * Closes socket.
  30022. *
  30023. * @api private
  30024. */
  30025. WS.prototype.doClose = function(){
  30026. if (typeof this.ws !== 'undefined') {
  30027. this.ws.close();
  30028. }
  30029. };
  30030. /**
  30031. * Generates uri for connection.
  30032. *
  30033. * @api private
  30034. */
  30035. WS.prototype.uri = function(){
  30036. var query = this.query || {};
  30037. var schema = this.secure ? 'wss' : 'ws';
  30038. var port = '';
  30039. // avoid port if default for schema
  30040. if (this.port && (('wss' == schema && this.port != 443)
  30041. || ('ws' == schema && this.port != 80))) {
  30042. port = ':' + this.port;
  30043. }
  30044. // append timestamp to URI
  30045. if (this.timestampRequests) {
  30046. query[this.timestampParam] = +new Date;
  30047. }
  30048. // communicate binary support capabilities
  30049. if (!this.supportsBinary) {
  30050. query.b64 = 1;
  30051. }
  30052. query = parseqs.encode(query);
  30053. // prepend ? to query
  30054. if (query.length) {
  30055. query = '?' + query;
  30056. }
  30057. return schema + '://' + this.hostname + port + this.path + query;
  30058. };
  30059. /**
  30060. * Feature detection for WebSocket.
  30061. *
  30062. * @return {Boolean} whether this transport is available.
  30063. * @api public
  30064. */
  30065. WS.prototype.check = function(){
  30066. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  30067. };
  30068. },{"../transport":122,"component-inherit":129,"debug":130,"engine.io-parser":133,"parseqs":145,"ws":147}],128:[function(require,module,exports){
  30069. // browser shim for xmlhttprequest module
  30070. var hasCORS = require('has-cors');
  30071. module.exports = function(opts) {
  30072. var xdomain = opts.xdomain;
  30073. // scheme must be same when usign XDomainRequest
  30074. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  30075. var xscheme = opts.xscheme;
  30076. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  30077. // https://github.com/Automattic/engine.io-client/pull/217
  30078. var enablesXDR = opts.enablesXDR;
  30079. // XMLHttpRequest can be disabled on IE
  30080. try {
  30081. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  30082. return new XMLHttpRequest();
  30083. }
  30084. } catch (e) { }
  30085. // Use XDomainRequest for IE8 if enablesXDR is true
  30086. // because loading bar keeps flashing when using jsonp-polling
  30087. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  30088. try {
  30089. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  30090. return new XDomainRequest();
  30091. }
  30092. } catch (e) { }
  30093. if (!xdomain) {
  30094. try {
  30095. return new ActiveXObject('Microsoft.XMLHTTP');
  30096. } catch(e) { }
  30097. }
  30098. }
  30099. },{"has-cors":142}],129:[function(require,module,exports){
  30100. module.exports = function(a, b){
  30101. var fn = function(){};
  30102. fn.prototype = b.prototype;
  30103. a.prototype = new fn;
  30104. a.prototype.constructor = a;
  30105. };
  30106. },{}],130:[function(require,module,exports){
  30107. /**
  30108. * This is the web browser implementation of `debug()`.
  30109. *
  30110. * Expose `debug()` as the module.
  30111. */
  30112. exports = module.exports = require('./debug');
  30113. exports.log = log;
  30114. exports.formatArgs = formatArgs;
  30115. exports.save = save;
  30116. exports.load = load;
  30117. exports.useColors = useColors;
  30118. /**
  30119. * Colors.
  30120. */
  30121. exports.colors = [
  30122. 'lightseagreen',
  30123. 'forestgreen',
  30124. 'goldenrod',
  30125. 'dodgerblue',
  30126. 'darkorchid',
  30127. 'crimson'
  30128. ];
  30129. /**
  30130. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  30131. * and the Firebug extension (any Firefox version) are known
  30132. * to support "%c" CSS customizations.
  30133. *
  30134. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  30135. */
  30136. function useColors() {
  30137. // is webkit? http://stackoverflow.com/a/16459606/376773
  30138. return ('WebkitAppearance' in document.documentElement.style) ||
  30139. // is firebug? http://stackoverflow.com/a/398120/376773
  30140. (window.console && (console.firebug || (console.exception && console.table))) ||
  30141. // is firefox >= v31?
  30142. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  30143. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  30144. }
  30145. /**
  30146. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  30147. */
  30148. exports.formatters.j = function(v) {
  30149. return JSON.stringify(v);
  30150. };
  30151. /**
  30152. * Colorize log arguments if enabled.
  30153. *
  30154. * @api public
  30155. */
  30156. function formatArgs() {
  30157. var args = arguments;
  30158. var useColors = this.useColors;
  30159. args[0] = (useColors ? '%c' : '')
  30160. + this.namespace
  30161. + (useColors ? ' %c' : ' ')
  30162. + args[0]
  30163. + (useColors ? '%c ' : ' ')
  30164. + '+' + exports.humanize(this.diff);
  30165. if (!useColors) return args;
  30166. var c = 'color: ' + this.color;
  30167. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  30168. // the final "%c" is somewhat tricky, because there could be other
  30169. // arguments passed either before or after the %c, so we need to
  30170. // figure out the correct index to insert the CSS into
  30171. var index = 0;
  30172. var lastC = 0;
  30173. args[0].replace(/%[a-z%]/g, function(match) {
  30174. if ('%%' === match) return;
  30175. index++;
  30176. if ('%c' === match) {
  30177. // we only are interested in the *last* %c
  30178. // (the user may have provided their own)
  30179. lastC = index;
  30180. }
  30181. });
  30182. args.splice(lastC, 0, c);
  30183. return args;
  30184. }
  30185. /**
  30186. * Invokes `console.log()` when available.
  30187. * No-op when `console.log` is not a "function".
  30188. *
  30189. * @api public
  30190. */
  30191. function log() {
  30192. // This hackery is required for IE8,
  30193. // where the `console.log` function doesn't have 'apply'
  30194. return 'object' == typeof console
  30195. && 'function' == typeof console.log
  30196. && Function.prototype.apply.call(console.log, console, arguments);
  30197. }
  30198. /**
  30199. * Save `namespaces`.
  30200. *
  30201. * @param {String} namespaces
  30202. * @api private
  30203. */
  30204. function save(namespaces) {
  30205. try {
  30206. if (null == namespaces) {
  30207. localStorage.removeItem('debug');
  30208. } else {
  30209. localStorage.debug = namespaces;
  30210. }
  30211. } catch(e) {}
  30212. }
  30213. /**
  30214. * Load `namespaces`.
  30215. *
  30216. * @return {String} returns the previously persisted debug modes
  30217. * @api private
  30218. */
  30219. function load() {
  30220. var r;
  30221. try {
  30222. r = localStorage.debug;
  30223. } catch(e) {}
  30224. return r;
  30225. }
  30226. /**
  30227. * Enable namespaces listed in `localStorage.debug` initially.
  30228. */
  30229. exports.enable(load());
  30230. },{"./debug":131}],131:[function(require,module,exports){
  30231. /**
  30232. * This is the common logic for both the Node.js and web browser
  30233. * implementations of `debug()`.
  30234. *
  30235. * Expose `debug()` as the module.
  30236. */
  30237. exports = module.exports = debug;
  30238. exports.coerce = coerce;
  30239. exports.disable = disable;
  30240. exports.enable = enable;
  30241. exports.enabled = enabled;
  30242. exports.humanize = require('ms');
  30243. /**
  30244. * The currently active debug mode names, and names to skip.
  30245. */
  30246. exports.names = [];
  30247. exports.skips = [];
  30248. /**
  30249. * Map of special "%n" handling functions, for the debug "format" argument.
  30250. *
  30251. * Valid key names are a single, lowercased letter, i.e. "n".
  30252. */
  30253. exports.formatters = {};
  30254. /**
  30255. * Previously assigned color.
  30256. */
  30257. var prevColor = 0;
  30258. /**
  30259. * Previous log timestamp.
  30260. */
  30261. var prevTime;
  30262. /**
  30263. * Select a color.
  30264. *
  30265. * @return {Number}
  30266. * @api private
  30267. */
  30268. function selectColor() {
  30269. return exports.colors[prevColor++ % exports.colors.length];
  30270. }
  30271. /**
  30272. * Create a debugger with the given `namespace`.
  30273. *
  30274. * @param {String} namespace
  30275. * @return {Function}
  30276. * @api public
  30277. */
  30278. function debug(namespace) {
  30279. // define the `disabled` version
  30280. function disabled() {
  30281. }
  30282. disabled.enabled = false;
  30283. // define the `enabled` version
  30284. function enabled() {
  30285. var self = enabled;
  30286. // set `diff` timestamp
  30287. var curr = +new Date();
  30288. var ms = curr - (prevTime || curr);
  30289. self.diff = ms;
  30290. self.prev = prevTime;
  30291. self.curr = curr;
  30292. prevTime = curr;
  30293. // add the `color` if not set
  30294. if (null == self.useColors) self.useColors = exports.useColors();
  30295. if (null == self.color && self.useColors) self.color = selectColor();
  30296. var args = Array.prototype.slice.call(arguments);
  30297. args[0] = exports.coerce(args[0]);
  30298. if ('string' !== typeof args[0]) {
  30299. // anything else let's inspect with %o
  30300. args = ['%o'].concat(args);
  30301. }
  30302. // apply any `formatters` transformations
  30303. var index = 0;
  30304. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  30305. // if we encounter an escaped % then don't increase the array index
  30306. if (match === '%%') return match;
  30307. index++;
  30308. var formatter = exports.formatters[format];
  30309. if ('function' === typeof formatter) {
  30310. var val = args[index];
  30311. match = formatter.call(self, val);
  30312. // now we need to remove `args[index]` since it's inlined in the `format`
  30313. args.splice(index, 1);
  30314. index--;
  30315. }
  30316. return match;
  30317. });
  30318. if ('function' === typeof exports.formatArgs) {
  30319. args = exports.formatArgs.apply(self, args);
  30320. }
  30321. var logFn = enabled.log || exports.log || console.log.bind(console);
  30322. logFn.apply(self, args);
  30323. }
  30324. enabled.enabled = true;
  30325. var fn = exports.enabled(namespace) ? enabled : disabled;
  30326. fn.namespace = namespace;
  30327. return fn;
  30328. }
  30329. /**
  30330. * Enables a debug mode by namespaces. This can include modes
  30331. * separated by a colon and wildcards.
  30332. *
  30333. * @param {String} namespaces
  30334. * @api public
  30335. */
  30336. function enable(namespaces) {
  30337. exports.save(namespaces);
  30338. var split = (namespaces || '').split(/[\s,]+/);
  30339. var len = split.length;
  30340. for (var i = 0; i < len; i++) {
  30341. if (!split[i]) continue; // ignore empty strings
  30342. namespaces = split[i].replace(/\*/g, '.*?');
  30343. if (namespaces[0] === '-') {
  30344. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  30345. } else {
  30346. exports.names.push(new RegExp('^' + namespaces + '$'));
  30347. }
  30348. }
  30349. }
  30350. /**
  30351. * Disable debug output.
  30352. *
  30353. * @api public
  30354. */
  30355. function disable() {
  30356. exports.enable('');
  30357. }
  30358. /**
  30359. * Returns true if the given mode name is enabled, false otherwise.
  30360. *
  30361. * @param {String} name
  30362. * @return {Boolean}
  30363. * @api public
  30364. */
  30365. function enabled(name) {
  30366. var i, len;
  30367. for (i = 0, len = exports.skips.length; i < len; i++) {
  30368. if (exports.skips[i].test(name)) {
  30369. return false;
  30370. }
  30371. }
  30372. for (i = 0, len = exports.names.length; i < len; i++) {
  30373. if (exports.names[i].test(name)) {
  30374. return true;
  30375. }
  30376. }
  30377. return false;
  30378. }
  30379. /**
  30380. * Coerce `val`.
  30381. *
  30382. * @param {Mixed} val
  30383. * @return {Mixed}
  30384. * @api private
  30385. */
  30386. function coerce(val) {
  30387. if (val instanceof Error) return val.stack || val.message;
  30388. return val;
  30389. }
  30390. },{"ms":132}],132:[function(require,module,exports){
  30391. /**
  30392. * Helpers.
  30393. */
  30394. var s = 1000;
  30395. var m = s * 60;
  30396. var h = m * 60;
  30397. var d = h * 24;
  30398. var y = d * 365.25;
  30399. /**
  30400. * Parse or format the given `val`.
  30401. *
  30402. * Options:
  30403. *
  30404. * - `long` verbose formatting [false]
  30405. *
  30406. * @param {String|Number} val
  30407. * @param {Object} options
  30408. * @return {String|Number}
  30409. * @api public
  30410. */
  30411. module.exports = function(val, options){
  30412. options = options || {};
  30413. if ('string' == typeof val) return parse(val);
  30414. return options.long
  30415. ? long(val)
  30416. : short(val);
  30417. };
  30418. /**
  30419. * Parse the given `str` and return milliseconds.
  30420. *
  30421. * @param {String} str
  30422. * @return {Number}
  30423. * @api private
  30424. */
  30425. function parse(str) {
  30426. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  30427. if (!match) return;
  30428. var n = parseFloat(match[1]);
  30429. var type = (match[2] || 'ms').toLowerCase();
  30430. switch (type) {
  30431. case 'years':
  30432. case 'year':
  30433. case 'y':
  30434. return n * y;
  30435. case 'days':
  30436. case 'day':
  30437. case 'd':
  30438. return n * d;
  30439. case 'hours':
  30440. case 'hour':
  30441. case 'h':
  30442. return n * h;
  30443. case 'minutes':
  30444. case 'minute':
  30445. case 'm':
  30446. return n * m;
  30447. case 'seconds':
  30448. case 'second':
  30449. case 's':
  30450. return n * s;
  30451. case 'ms':
  30452. return n;
  30453. }
  30454. }
  30455. /**
  30456. * Short format for `ms`.
  30457. *
  30458. * @param {Number} ms
  30459. * @return {String}
  30460. * @api private
  30461. */
  30462. function short(ms) {
  30463. if (ms >= d) return Math.round(ms / d) + 'd';
  30464. if (ms >= h) return Math.round(ms / h) + 'h';
  30465. if (ms >= m) return Math.round(ms / m) + 'm';
  30466. if (ms >= s) return Math.round(ms / s) + 's';
  30467. return ms + 'ms';
  30468. }
  30469. /**
  30470. * Long format for `ms`.
  30471. *
  30472. * @param {Number} ms
  30473. * @return {String}
  30474. * @api private
  30475. */
  30476. function long(ms) {
  30477. return plural(ms, d, 'day')
  30478. || plural(ms, h, 'hour')
  30479. || plural(ms, m, 'minute')
  30480. || plural(ms, s, 'second')
  30481. || ms + ' ms';
  30482. }
  30483. /**
  30484. * Pluralization helper.
  30485. */
  30486. function plural(ms, n, name) {
  30487. if (ms < n) return;
  30488. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  30489. return Math.ceil(ms / n) + ' ' + name + 's';
  30490. }
  30491. },{}],133:[function(require,module,exports){
  30492. (function (global){
  30493. /**
  30494. * Module dependencies.
  30495. */
  30496. var keys = require('./keys');
  30497. var hasBinary = require('has-binary');
  30498. var sliceBuffer = require('arraybuffer.slice');
  30499. var base64encoder = require('base64-arraybuffer');
  30500. var after = require('after');
  30501. var utf8 = require('utf8');
  30502. /**
  30503. * Check if we are running an android browser. That requires us to use
  30504. * ArrayBuffer with polling transports...
  30505. *
  30506. * http://ghinda.net/jpeg-blob-ajax-android/
  30507. */
  30508. var isAndroid = navigator.userAgent.match(/Android/i);
  30509. /**
  30510. * Check if we are running in PhantomJS.
  30511. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  30512. * https://github.com/ariya/phantomjs/issues/11395
  30513. * @type boolean
  30514. */
  30515. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  30516. /**
  30517. * When true, avoids using Blobs to encode payloads.
  30518. * @type boolean
  30519. */
  30520. var dontSendBlobs = isAndroid || isPhantomJS;
  30521. /**
  30522. * Current protocol version.
  30523. */
  30524. exports.protocol = 3;
  30525. /**
  30526. * Packet types.
  30527. */
  30528. var packets = exports.packets = {
  30529. open: 0 // non-ws
  30530. , close: 1 // non-ws
  30531. , ping: 2
  30532. , pong: 3
  30533. , message: 4
  30534. , upgrade: 5
  30535. , noop: 6
  30536. };
  30537. var packetslist = keys(packets);
  30538. /**
  30539. * Premade error packet.
  30540. */
  30541. var err = { type: 'error', data: 'parser error' };
  30542. /**
  30543. * Create a blob api even for blob builder when vendor prefixes exist
  30544. */
  30545. var Blob = require('blob');
  30546. /**
  30547. * Encodes a packet.
  30548. *
  30549. * <packet type id> [ <data> ]
  30550. *
  30551. * Example:
  30552. *
  30553. * 5hello world
  30554. * 3
  30555. * 4
  30556. *
  30557. * Binary is encoded in an identical principle
  30558. *
  30559. * @api private
  30560. */
  30561. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  30562. if ('function' == typeof supportsBinary) {
  30563. callback = supportsBinary;
  30564. supportsBinary = false;
  30565. }
  30566. if ('function' == typeof utf8encode) {
  30567. callback = utf8encode;
  30568. utf8encode = null;
  30569. }
  30570. var data = (packet.data === undefined)
  30571. ? undefined
  30572. : packet.data.buffer || packet.data;
  30573. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  30574. return encodeArrayBuffer(packet, supportsBinary, callback);
  30575. } else if (Blob && data instanceof global.Blob) {
  30576. return encodeBlob(packet, supportsBinary, callback);
  30577. }
  30578. // might be an object with { base64: true, data: dataAsBase64String }
  30579. if (data && data.base64) {
  30580. return encodeBase64Object(packet, callback);
  30581. }
  30582. // Sending data as a utf-8 string
  30583. var encoded = packets[packet.type];
  30584. // data fragment is optional
  30585. if (undefined !== packet.data) {
  30586. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  30587. }
  30588. return callback('' + encoded);
  30589. };
  30590. function encodeBase64Object(packet, callback) {
  30591. // packet data is an object { base64: true, data: dataAsBase64String }
  30592. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  30593. return callback(message);
  30594. }
  30595. /**
  30596. * Encode packet helpers for binary types
  30597. */
  30598. function encodeArrayBuffer(packet, supportsBinary, callback) {
  30599. if (!supportsBinary) {
  30600. return exports.encodeBase64Packet(packet, callback);
  30601. }
  30602. var data = packet.data;
  30603. var contentArray = new Uint8Array(data);
  30604. var resultBuffer = new Uint8Array(1 + data.byteLength);
  30605. resultBuffer[0] = packets[packet.type];
  30606. for (var i = 0; i < contentArray.length; i++) {
  30607. resultBuffer[i+1] = contentArray[i];
  30608. }
  30609. return callback(resultBuffer.buffer);
  30610. }
  30611. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  30612. if (!supportsBinary) {
  30613. return exports.encodeBase64Packet(packet, callback);
  30614. }
  30615. var fr = new FileReader();
  30616. fr.onload = function() {
  30617. packet.data = fr.result;
  30618. exports.encodePacket(packet, supportsBinary, true, callback);
  30619. };
  30620. return fr.readAsArrayBuffer(packet.data);
  30621. }
  30622. function encodeBlob(packet, supportsBinary, callback) {
  30623. if (!supportsBinary) {
  30624. return exports.encodeBase64Packet(packet, callback);
  30625. }
  30626. if (dontSendBlobs) {
  30627. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  30628. }
  30629. var length = new Uint8Array(1);
  30630. length[0] = packets[packet.type];
  30631. var blob = new Blob([length.buffer, packet.data]);
  30632. return callback(blob);
  30633. }
  30634. /**
  30635. * Encodes a packet with binary data in a base64 string
  30636. *
  30637. * @param {Object} packet, has `type` and `data`
  30638. * @return {String} base64 encoded message
  30639. */
  30640. exports.encodeBase64Packet = function(packet, callback) {
  30641. var message = 'b' + exports.packets[packet.type];
  30642. if (Blob && packet.data instanceof Blob) {
  30643. var fr = new FileReader();
  30644. fr.onload = function() {
  30645. var b64 = fr.result.split(',')[1];
  30646. callback(message + b64);
  30647. };
  30648. return fr.readAsDataURL(packet.data);
  30649. }
  30650. var b64data;
  30651. try {
  30652. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  30653. } catch (e) {
  30654. // iPhone Safari doesn't let you apply with typed arrays
  30655. var typed = new Uint8Array(packet.data);
  30656. var basic = new Array(typed.length);
  30657. for (var i = 0; i < typed.length; i++) {
  30658. basic[i] = typed[i];
  30659. }
  30660. b64data = String.fromCharCode.apply(null, basic);
  30661. }
  30662. message += global.btoa(b64data);
  30663. return callback(message);
  30664. };
  30665. /**
  30666. * Decodes a packet. Changes format to Blob if requested.
  30667. *
  30668. * @return {Object} with `type` and `data` (if any)
  30669. * @api private
  30670. */
  30671. exports.decodePacket = function (data, binaryType, utf8decode) {
  30672. // String data
  30673. if (typeof data == 'string' || data === undefined) {
  30674. if (data.charAt(0) == 'b') {
  30675. return exports.decodeBase64Packet(data.substr(1), binaryType);
  30676. }
  30677. if (utf8decode) {
  30678. try {
  30679. data = utf8.decode(data);
  30680. } catch (e) {
  30681. return err;
  30682. }
  30683. }
  30684. var type = data.charAt(0);
  30685. if (Number(type) != type || !packetslist[type]) {
  30686. return err;
  30687. }
  30688. if (data.length > 1) {
  30689. return { type: packetslist[type], data: data.substring(1) };
  30690. } else {
  30691. return { type: packetslist[type] };
  30692. }
  30693. }
  30694. var asArray = new Uint8Array(data);
  30695. var type = asArray[0];
  30696. var rest = sliceBuffer(data, 1);
  30697. if (Blob && binaryType === 'blob') {
  30698. rest = new Blob([rest]);
  30699. }
  30700. return { type: packetslist[type], data: rest };
  30701. };
  30702. /**
  30703. * Decodes a packet encoded in a base64 string
  30704. *
  30705. * @param {String} base64 encoded message
  30706. * @return {Object} with `type` and `data` (if any)
  30707. */
  30708. exports.decodeBase64Packet = function(msg, binaryType) {
  30709. var type = packetslist[msg.charAt(0)];
  30710. if (!global.ArrayBuffer) {
  30711. return { type: type, data: { base64: true, data: msg.substr(1) } };
  30712. }
  30713. var data = base64encoder.decode(msg.substr(1));
  30714. if (binaryType === 'blob' && Blob) {
  30715. data = new Blob([data]);
  30716. }
  30717. return { type: type, data: data };
  30718. };
  30719. /**
  30720. * Encodes multiple messages (payload).
  30721. *
  30722. * <length>:data
  30723. *
  30724. * Example:
  30725. *
  30726. * 11:hello world2:hi
  30727. *
  30728. * If any contents are binary, they will be encoded as base64 strings. Base64
  30729. * encoded strings are marked with a b before the length specifier
  30730. *
  30731. * @param {Array} packets
  30732. * @api private
  30733. */
  30734. exports.encodePayload = function (packets, supportsBinary, callback) {
  30735. if (typeof supportsBinary == 'function') {
  30736. callback = supportsBinary;
  30737. supportsBinary = null;
  30738. }
  30739. var isBinary = hasBinary(packets);
  30740. if (supportsBinary && isBinary) {
  30741. if (Blob && !dontSendBlobs) {
  30742. return exports.encodePayloadAsBlob(packets, callback);
  30743. }
  30744. return exports.encodePayloadAsArrayBuffer(packets, callback);
  30745. }
  30746. if (!packets.length) {
  30747. return callback('0:');
  30748. }
  30749. function setLengthHeader(message) {
  30750. return message.length + ':' + message;
  30751. }
  30752. function encodeOne(packet, doneCallback) {
  30753. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  30754. doneCallback(null, setLengthHeader(message));
  30755. });
  30756. }
  30757. map(packets, encodeOne, function(err, results) {
  30758. return callback(results.join(''));
  30759. });
  30760. };
  30761. /**
  30762. * Async array map using after
  30763. */
  30764. function map(ary, each, done) {
  30765. var result = new Array(ary.length);
  30766. var next = after(ary.length, done);
  30767. var eachWithIndex = function(i, el, cb) {
  30768. each(el, function(error, msg) {
  30769. result[i] = msg;
  30770. cb(error, result);
  30771. });
  30772. };
  30773. for (var i = 0; i < ary.length; i++) {
  30774. eachWithIndex(i, ary[i], next);
  30775. }
  30776. }
  30777. /*
  30778. * Decodes data when a payload is maybe expected. Possible binary contents are
  30779. * decoded from their base64 representation
  30780. *
  30781. * @param {String} data, callback method
  30782. * @api public
  30783. */
  30784. exports.decodePayload = function (data, binaryType, callback) {
  30785. if (typeof data != 'string') {
  30786. return exports.decodePayloadAsBinary(data, binaryType, callback);
  30787. }
  30788. if (typeof binaryType === 'function') {
  30789. callback = binaryType;
  30790. binaryType = null;
  30791. }
  30792. var packet;
  30793. if (data == '') {
  30794. // parser error - ignoring payload
  30795. return callback(err, 0, 1);
  30796. }
  30797. var length = ''
  30798. , n, msg;
  30799. for (var i = 0, l = data.length; i < l; i++) {
  30800. var chr = data.charAt(i);
  30801. if (':' != chr) {
  30802. length += chr;
  30803. } else {
  30804. if ('' == length || (length != (n = Number(length)))) {
  30805. // parser error - ignoring payload
  30806. return callback(err, 0, 1);
  30807. }
  30808. msg = data.substr(i + 1, n);
  30809. if (length != msg.length) {
  30810. // parser error - ignoring payload
  30811. return callback(err, 0, 1);
  30812. }
  30813. if (msg.length) {
  30814. packet = exports.decodePacket(msg, binaryType, true);
  30815. if (err.type == packet.type && err.data == packet.data) {
  30816. // parser error in individual packet - ignoring payload
  30817. return callback(err, 0, 1);
  30818. }
  30819. var ret = callback(packet, i + n, l);
  30820. if (false === ret) return;
  30821. }
  30822. // advance cursor
  30823. i += n;
  30824. length = '';
  30825. }
  30826. }
  30827. if (length != '') {
  30828. // parser error - ignoring payload
  30829. return callback(err, 0, 1);
  30830. }
  30831. };
  30832. /**
  30833. * Encodes multiple messages (payload) as binary.
  30834. *
  30835. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  30836. * 255><data>
  30837. *
  30838. * Example:
  30839. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  30840. *
  30841. * @param {Array} packets
  30842. * @return {ArrayBuffer} encoded payload
  30843. * @api private
  30844. */
  30845. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  30846. if (!packets.length) {
  30847. return callback(new ArrayBuffer(0));
  30848. }
  30849. function encodeOne(packet, doneCallback) {
  30850. exports.encodePacket(packet, true, true, function(data) {
  30851. return doneCallback(null, data);
  30852. });
  30853. }
  30854. map(packets, encodeOne, function(err, encodedPackets) {
  30855. var totalLength = encodedPackets.reduce(function(acc, p) {
  30856. var len;
  30857. if (typeof p === 'string'){
  30858. len = p.length;
  30859. } else {
  30860. len = p.byteLength;
  30861. }
  30862. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  30863. }, 0);
  30864. var resultArray = new Uint8Array(totalLength);
  30865. var bufferIndex = 0;
  30866. encodedPackets.forEach(function(p) {
  30867. var isString = typeof p === 'string';
  30868. var ab = p;
  30869. if (isString) {
  30870. var view = new Uint8Array(p.length);
  30871. for (var i = 0; i < p.length; i++) {
  30872. view[i] = p.charCodeAt(i);
  30873. }
  30874. ab = view.buffer;
  30875. }
  30876. if (isString) { // not true binary
  30877. resultArray[bufferIndex++] = 0;
  30878. } else { // true binary
  30879. resultArray[bufferIndex++] = 1;
  30880. }
  30881. var lenStr = ab.byteLength.toString();
  30882. for (var i = 0; i < lenStr.length; i++) {
  30883. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  30884. }
  30885. resultArray[bufferIndex++] = 255;
  30886. var view = new Uint8Array(ab);
  30887. for (var i = 0; i < view.length; i++) {
  30888. resultArray[bufferIndex++] = view[i];
  30889. }
  30890. });
  30891. return callback(resultArray.buffer);
  30892. });
  30893. };
  30894. /**
  30895. * Encode as Blob
  30896. */
  30897. exports.encodePayloadAsBlob = function(packets, callback) {
  30898. function encodeOne(packet, doneCallback) {
  30899. exports.encodePacket(packet, true, true, function(encoded) {
  30900. var binaryIdentifier = new Uint8Array(1);
  30901. binaryIdentifier[0] = 1;
  30902. if (typeof encoded === 'string') {
  30903. var view = new Uint8Array(encoded.length);
  30904. for (var i = 0; i < encoded.length; i++) {
  30905. view[i] = encoded.charCodeAt(i);
  30906. }
  30907. encoded = view.buffer;
  30908. binaryIdentifier[0] = 0;
  30909. }
  30910. var len = (encoded instanceof ArrayBuffer)
  30911. ? encoded.byteLength
  30912. : encoded.size;
  30913. var lenStr = len.toString();
  30914. var lengthAry = new Uint8Array(lenStr.length + 1);
  30915. for (var i = 0; i < lenStr.length; i++) {
  30916. lengthAry[i] = parseInt(lenStr[i]);
  30917. }
  30918. lengthAry[lenStr.length] = 255;
  30919. if (Blob) {
  30920. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  30921. doneCallback(null, blob);
  30922. }
  30923. });
  30924. }
  30925. map(packets, encodeOne, function(err, results) {
  30926. return callback(new Blob(results));
  30927. });
  30928. };
  30929. /*
  30930. * Decodes data when a payload is maybe expected. Strings are decoded by
  30931. * interpreting each byte as a key code for entries marked to start with 0. See
  30932. * description of encodePayloadAsBinary
  30933. *
  30934. * @param {ArrayBuffer} data, callback method
  30935. * @api public
  30936. */
  30937. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  30938. if (typeof binaryType === 'function') {
  30939. callback = binaryType;
  30940. binaryType = null;
  30941. }
  30942. var bufferTail = data;
  30943. var buffers = [];
  30944. var numberTooLong = false;
  30945. while (bufferTail.byteLength > 0) {
  30946. var tailArray = new Uint8Array(bufferTail);
  30947. var isString = tailArray[0] === 0;
  30948. var msgLength = '';
  30949. for (var i = 1; ; i++) {
  30950. if (tailArray[i] == 255) break;
  30951. if (msgLength.length > 310) {
  30952. numberTooLong = true;
  30953. break;
  30954. }
  30955. msgLength += tailArray[i];
  30956. }
  30957. if(numberTooLong) return callback(err, 0, 1);
  30958. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  30959. msgLength = parseInt(msgLength);
  30960. var msg = sliceBuffer(bufferTail, 0, msgLength);
  30961. if (isString) {
  30962. try {
  30963. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  30964. } catch (e) {
  30965. // iPhone Safari doesn't let you apply to typed arrays
  30966. var typed = new Uint8Array(msg);
  30967. msg = '';
  30968. for (var i = 0; i < typed.length; i++) {
  30969. msg += String.fromCharCode(typed[i]);
  30970. }
  30971. }
  30972. }
  30973. buffers.push(msg);
  30974. bufferTail = sliceBuffer(bufferTail, msgLength);
  30975. }
  30976. var total = buffers.length;
  30977. buffers.forEach(function(buffer, i) {
  30978. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  30979. });
  30980. };
  30981. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  30982. },{"./keys":134,"after":135,"arraybuffer.slice":136,"base64-arraybuffer":137,"blob":138,"has-binary":139,"utf8":141}],134:[function(require,module,exports){
  30983. /**
  30984. * Gets the keys for an object.
  30985. *
  30986. * @return {Array} keys
  30987. * @api private
  30988. */
  30989. module.exports = Object.keys || function keys (obj){
  30990. var arr = [];
  30991. var has = Object.prototype.hasOwnProperty;
  30992. for (var i in obj) {
  30993. if (has.call(obj, i)) {
  30994. arr.push(i);
  30995. }
  30996. }
  30997. return arr;
  30998. };
  30999. },{}],135:[function(require,module,exports){
  31000. module.exports = after
  31001. function after(count, callback, err_cb) {
  31002. var bail = false
  31003. err_cb = err_cb || noop
  31004. proxy.count = count
  31005. return (count === 0) ? callback() : proxy
  31006. function proxy(err, result) {
  31007. if (proxy.count <= 0) {
  31008. throw new Error('after called too many times')
  31009. }
  31010. --proxy.count
  31011. // after first error, rest are passed to err_cb
  31012. if (err) {
  31013. bail = true
  31014. callback(err)
  31015. // future error callbacks will go to error handler
  31016. callback = err_cb
  31017. } else if (proxy.count === 0 && !bail) {
  31018. callback(null, result)
  31019. }
  31020. }
  31021. }
  31022. function noop() {}
  31023. },{}],136:[function(require,module,exports){
  31024. /**
  31025. * An abstraction for slicing an arraybuffer even when
  31026. * ArrayBuffer.prototype.slice is not supported
  31027. *
  31028. * @api public
  31029. */
  31030. module.exports = function(arraybuffer, start, end) {
  31031. var bytes = arraybuffer.byteLength;
  31032. start = start || 0;
  31033. end = end || bytes;
  31034. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  31035. if (start < 0) { start += bytes; }
  31036. if (end < 0) { end += bytes; }
  31037. if (end > bytes) { end = bytes; }
  31038. if (start >= bytes || start >= end || bytes === 0) {
  31039. return new ArrayBuffer(0);
  31040. }
  31041. var abv = new Uint8Array(arraybuffer);
  31042. var result = new Uint8Array(end - start);
  31043. for (var i = start, ii = 0; i < end; i++, ii++) {
  31044. result[ii] = abv[i];
  31045. }
  31046. return result.buffer;
  31047. };
  31048. },{}],137:[function(require,module,exports){
  31049. /*
  31050. * base64-arraybuffer
  31051. * https://github.com/niklasvh/base64-arraybuffer
  31052. *
  31053. * Copyright (c) 2012 Niklas von Hertzen
  31054. * Licensed under the MIT license.
  31055. */
  31056. (function(chars){
  31057. "use strict";
  31058. exports.encode = function(arraybuffer) {
  31059. var bytes = new Uint8Array(arraybuffer),
  31060. i, len = bytes.length, base64 = "";
  31061. for (i = 0; i < len; i+=3) {
  31062. base64 += chars[bytes[i] >> 2];
  31063. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  31064. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  31065. base64 += chars[bytes[i + 2] & 63];
  31066. }
  31067. if ((len % 3) === 2) {
  31068. base64 = base64.substring(0, base64.length - 1) + "=";
  31069. } else if (len % 3 === 1) {
  31070. base64 = base64.substring(0, base64.length - 2) + "==";
  31071. }
  31072. return base64;
  31073. };
  31074. exports.decode = function(base64) {
  31075. var bufferLength = base64.length * 0.75,
  31076. len = base64.length, i, p = 0,
  31077. encoded1, encoded2, encoded3, encoded4;
  31078. if (base64[base64.length - 1] === "=") {
  31079. bufferLength--;
  31080. if (base64[base64.length - 2] === "=") {
  31081. bufferLength--;
  31082. }
  31083. }
  31084. var arraybuffer = new ArrayBuffer(bufferLength),
  31085. bytes = new Uint8Array(arraybuffer);
  31086. for (i = 0; i < len; i+=4) {
  31087. encoded1 = chars.indexOf(base64[i]);
  31088. encoded2 = chars.indexOf(base64[i+1]);
  31089. encoded3 = chars.indexOf(base64[i+2]);
  31090. encoded4 = chars.indexOf(base64[i+3]);
  31091. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  31092. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  31093. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  31094. }
  31095. return arraybuffer;
  31096. };
  31097. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  31098. },{}],138:[function(require,module,exports){
  31099. (function (global){
  31100. /**
  31101. * Create a blob builder even when vendor prefixes exist
  31102. */
  31103. var BlobBuilder = global.BlobBuilder
  31104. || global.WebKitBlobBuilder
  31105. || global.MSBlobBuilder
  31106. || global.MozBlobBuilder;
  31107. /**
  31108. * Check if Blob constructor is supported
  31109. */
  31110. var blobSupported = (function() {
  31111. try {
  31112. var b = new Blob(['hi']);
  31113. return b.size == 2;
  31114. } catch(e) {
  31115. return false;
  31116. }
  31117. })();
  31118. /**
  31119. * Check if BlobBuilder is supported
  31120. */
  31121. var blobBuilderSupported = BlobBuilder
  31122. && BlobBuilder.prototype.append
  31123. && BlobBuilder.prototype.getBlob;
  31124. function BlobBuilderConstructor(ary, options) {
  31125. options = options || {};
  31126. var bb = new BlobBuilder();
  31127. for (var i = 0; i < ary.length; i++) {
  31128. bb.append(ary[i]);
  31129. }
  31130. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  31131. };
  31132. module.exports = (function() {
  31133. if (blobSupported) {
  31134. return global.Blob;
  31135. } else if (blobBuilderSupported) {
  31136. return BlobBuilderConstructor;
  31137. } else {
  31138. return undefined;
  31139. }
  31140. })();
  31141. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31142. },{}],139:[function(require,module,exports){
  31143. (function (global){
  31144. /*
  31145. * Module requirements.
  31146. */
  31147. var isArray = require('isarray');
  31148. /**
  31149. * Module exports.
  31150. */
  31151. module.exports = hasBinary;
  31152. /**
  31153. * Checks for binary data.
  31154. *
  31155. * Right now only Buffer and ArrayBuffer are supported..
  31156. *
  31157. * @param {Object} anything
  31158. * @api public
  31159. */
  31160. function hasBinary(data) {
  31161. function _hasBinary(obj) {
  31162. if (!obj) return false;
  31163. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  31164. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  31165. (global.Blob && obj instanceof Blob) ||
  31166. (global.File && obj instanceof File)
  31167. ) {
  31168. return true;
  31169. }
  31170. if (isArray(obj)) {
  31171. for (var i = 0; i < obj.length; i++) {
  31172. if (_hasBinary(obj[i])) {
  31173. return true;
  31174. }
  31175. }
  31176. } else if (obj && 'object' == typeof obj) {
  31177. if (obj.toJSON) {
  31178. obj = obj.toJSON();
  31179. }
  31180. for (var key in obj) {
  31181. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  31182. return true;
  31183. }
  31184. }
  31185. }
  31186. return false;
  31187. }
  31188. return _hasBinary(data);
  31189. }
  31190. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31191. },{"isarray":140}],140:[function(require,module,exports){
  31192. module.exports = Array.isArray || function (arr) {
  31193. return Object.prototype.toString.call(arr) == '[object Array]';
  31194. };
  31195. },{}],141:[function(require,module,exports){
  31196. (function (global){
  31197. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  31198. ;(function(root) {
  31199. // Detect free variables `exports`
  31200. var freeExports = typeof exports == 'object' && exports;
  31201. // Detect free variable `module`
  31202. var freeModule = typeof module == 'object' && module &&
  31203. module.exports == freeExports && module;
  31204. // Detect free variable `global`, from Node.js or Browserified code,
  31205. // and use it as `root`
  31206. var freeGlobal = typeof global == 'object' && global;
  31207. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  31208. root = freeGlobal;
  31209. }
  31210. /*--------------------------------------------------------------------------*/
  31211. var stringFromCharCode = String.fromCharCode;
  31212. // Taken from http://mths.be/punycode
  31213. function ucs2decode(string) {
  31214. var output = [];
  31215. var counter = 0;
  31216. var length = string.length;
  31217. var value;
  31218. var extra;
  31219. while (counter < length) {
  31220. value = string.charCodeAt(counter++);
  31221. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  31222. // high surrogate, and there is a next character
  31223. extra = string.charCodeAt(counter++);
  31224. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  31225. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  31226. } else {
  31227. // unmatched surrogate; only append this code unit, in case the next
  31228. // code unit is the high surrogate of a surrogate pair
  31229. output.push(value);
  31230. counter--;
  31231. }
  31232. } else {
  31233. output.push(value);
  31234. }
  31235. }
  31236. return output;
  31237. }
  31238. // Taken from http://mths.be/punycode
  31239. function ucs2encode(array) {
  31240. var length = array.length;
  31241. var index = -1;
  31242. var value;
  31243. var output = '';
  31244. while (++index < length) {
  31245. value = array[index];
  31246. if (value > 0xFFFF) {
  31247. value -= 0x10000;
  31248. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  31249. value = 0xDC00 | value & 0x3FF;
  31250. }
  31251. output += stringFromCharCode(value);
  31252. }
  31253. return output;
  31254. }
  31255. /*--------------------------------------------------------------------------*/
  31256. function createByte(codePoint, shift) {
  31257. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  31258. }
  31259. function encodeCodePoint(codePoint) {
  31260. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  31261. return stringFromCharCode(codePoint);
  31262. }
  31263. var symbol = '';
  31264. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  31265. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  31266. }
  31267. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  31268. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  31269. symbol += createByte(codePoint, 6);
  31270. }
  31271. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  31272. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  31273. symbol += createByte(codePoint, 12);
  31274. symbol += createByte(codePoint, 6);
  31275. }
  31276. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  31277. return symbol;
  31278. }
  31279. function utf8encode(string) {
  31280. var codePoints = ucs2decode(string);
  31281. // console.log(JSON.stringify(codePoints.map(function(x) {
  31282. // return 'U+' + x.toString(16).toUpperCase();
  31283. // })));
  31284. var length = codePoints.length;
  31285. var index = -1;
  31286. var codePoint;
  31287. var byteString = '';
  31288. while (++index < length) {
  31289. codePoint = codePoints[index];
  31290. byteString += encodeCodePoint(codePoint);
  31291. }
  31292. return byteString;
  31293. }
  31294. /*--------------------------------------------------------------------------*/
  31295. function readContinuationByte() {
  31296. if (byteIndex >= byteCount) {
  31297. throw Error('Invalid byte index');
  31298. }
  31299. var continuationByte = byteArray[byteIndex] & 0xFF;
  31300. byteIndex++;
  31301. if ((continuationByte & 0xC0) == 0x80) {
  31302. return continuationByte & 0x3F;
  31303. }
  31304. // If we end up here, it’s not a continuation byte
  31305. throw Error('Invalid continuation byte');
  31306. }
  31307. function decodeSymbol() {
  31308. var byte1;
  31309. var byte2;
  31310. var byte3;
  31311. var byte4;
  31312. var codePoint;
  31313. if (byteIndex > byteCount) {
  31314. throw Error('Invalid byte index');
  31315. }
  31316. if (byteIndex == byteCount) {
  31317. return false;
  31318. }
  31319. // Read first byte
  31320. byte1 = byteArray[byteIndex] & 0xFF;
  31321. byteIndex++;
  31322. // 1-byte sequence (no continuation bytes)
  31323. if ((byte1 & 0x80) == 0) {
  31324. return byte1;
  31325. }
  31326. // 2-byte sequence
  31327. if ((byte1 & 0xE0) == 0xC0) {
  31328. var byte2 = readContinuationByte();
  31329. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  31330. if (codePoint >= 0x80) {
  31331. return codePoint;
  31332. } else {
  31333. throw Error('Invalid continuation byte');
  31334. }
  31335. }
  31336. // 3-byte sequence (may include unpaired surrogates)
  31337. if ((byte1 & 0xF0) == 0xE0) {
  31338. byte2 = readContinuationByte();
  31339. byte3 = readContinuationByte();
  31340. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  31341. if (codePoint >= 0x0800) {
  31342. return codePoint;
  31343. } else {
  31344. throw Error('Invalid continuation byte');
  31345. }
  31346. }
  31347. // 4-byte sequence
  31348. if ((byte1 & 0xF8) == 0xF0) {
  31349. byte2 = readContinuationByte();
  31350. byte3 = readContinuationByte();
  31351. byte4 = readContinuationByte();
  31352. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  31353. (byte3 << 0x06) | byte4;
  31354. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  31355. return codePoint;
  31356. }
  31357. }
  31358. throw Error('Invalid UTF-8 detected');
  31359. }
  31360. var byteArray;
  31361. var byteCount;
  31362. var byteIndex;
  31363. function utf8decode(byteString) {
  31364. byteArray = ucs2decode(byteString);
  31365. byteCount = byteArray.length;
  31366. byteIndex = 0;
  31367. var codePoints = [];
  31368. var tmp;
  31369. while ((tmp = decodeSymbol()) !== false) {
  31370. codePoints.push(tmp);
  31371. }
  31372. return ucs2encode(codePoints);
  31373. }
  31374. /*--------------------------------------------------------------------------*/
  31375. var utf8 = {
  31376. 'version': '2.0.0',
  31377. 'encode': utf8encode,
  31378. 'decode': utf8decode
  31379. };
  31380. // Some AMD build optimizers, like r.js, check for specific condition patterns
  31381. // like the following:
  31382. if (
  31383. typeof define == 'function' &&
  31384. typeof define.amd == 'object' &&
  31385. define.amd
  31386. ) {
  31387. define(function() {
  31388. return utf8;
  31389. });
  31390. } else if (freeExports && !freeExports.nodeType) {
  31391. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  31392. freeModule.exports = utf8;
  31393. } else { // in Narwhal or RingoJS v0.7.0-
  31394. var object = {};
  31395. var hasOwnProperty = object.hasOwnProperty;
  31396. for (var key in utf8) {
  31397. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  31398. }
  31399. }
  31400. } else { // in Rhino or a web browser
  31401. root.utf8 = utf8;
  31402. }
  31403. }(this));
  31404. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31405. },{}],142:[function(require,module,exports){
  31406. /**
  31407. * Module dependencies.
  31408. */
  31409. var global = require('global');
  31410. /**
  31411. * Module exports.
  31412. *
  31413. * Logic borrowed from Modernizr:
  31414. *
  31415. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  31416. */
  31417. try {
  31418. module.exports = 'XMLHttpRequest' in global &&
  31419. 'withCredentials' in new global.XMLHttpRequest();
  31420. } catch (err) {
  31421. // if XMLHttp support is disabled in IE then it will throw
  31422. // when trying to create
  31423. module.exports = false;
  31424. }
  31425. },{"global":143}],143:[function(require,module,exports){
  31426. /**
  31427. * Returns `this`. Execute this without a "context" (i.e. without it being
  31428. * attached to an object of the left-hand side), and `this` points to the
  31429. * "global" scope of the current JS execution.
  31430. */
  31431. module.exports = (function () { return this; })();
  31432. },{}],144:[function(require,module,exports){
  31433. (function (global){
  31434. /**
  31435. * JSON parse.
  31436. *
  31437. * @see Based on jQuery#parseJSON (MIT) and JSON2
  31438. * @api private
  31439. */
  31440. var rvalidchars = /^[\],:{}\s]*$/;
  31441. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  31442. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  31443. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  31444. var rtrimLeft = /^\s+/;
  31445. var rtrimRight = /\s+$/;
  31446. module.exports = function parsejson(data) {
  31447. if ('string' != typeof data || !data) {
  31448. return null;
  31449. }
  31450. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  31451. // Attempt to parse using the native JSON parser first
  31452. if (global.JSON && JSON.parse) {
  31453. return JSON.parse(data);
  31454. }
  31455. if (rvalidchars.test(data.replace(rvalidescape, '@')
  31456. .replace(rvalidtokens, ']')
  31457. .replace(rvalidbraces, ''))) {
  31458. return (new Function('return ' + data))();
  31459. }
  31460. };
  31461. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31462. },{}],145:[function(require,module,exports){
  31463. /**
  31464. * Compiles a querystring
  31465. * Returns string representation of the object
  31466. *
  31467. * @param {Object}
  31468. * @api private
  31469. */
  31470. exports.encode = function (obj) {
  31471. var str = '';
  31472. for (var i in obj) {
  31473. if (obj.hasOwnProperty(i)) {
  31474. if (str.length) str += '&';
  31475. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  31476. }
  31477. }
  31478. return str;
  31479. };
  31480. /**
  31481. * Parses a simple querystring into an object
  31482. *
  31483. * @param {String} qs
  31484. * @api private
  31485. */
  31486. exports.decode = function(qs){
  31487. var qry = {};
  31488. var pairs = qs.split('&');
  31489. for (var i = 0, l = pairs.length; i < l; i++) {
  31490. var pair = pairs[i].split('=');
  31491. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  31492. }
  31493. return qry;
  31494. };
  31495. },{}],146:[function(require,module,exports){
  31496. /**
  31497. * Parses an URI
  31498. *
  31499. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  31500. * @api private
  31501. */
  31502. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  31503. var parts = [
  31504. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  31505. ];
  31506. module.exports = function parseuri(str) {
  31507. var src = str,
  31508. b = str.indexOf('['),
  31509. e = str.indexOf(']');
  31510. if (b != -1 && e != -1) {
  31511. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  31512. }
  31513. var m = re.exec(str || ''),
  31514. uri = {},
  31515. i = 14;
  31516. while (i--) {
  31517. uri[parts[i]] = m[i] || '';
  31518. }
  31519. if (b != -1 && e != -1) {
  31520. uri.source = src;
  31521. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  31522. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  31523. uri.ipv6uri = true;
  31524. }
  31525. return uri;
  31526. };
  31527. },{}],147:[function(require,module,exports){
  31528. /**
  31529. * Module dependencies.
  31530. */
  31531. var global = (function() { return this; })();
  31532. /**
  31533. * WebSocket constructor.
  31534. */
  31535. var WebSocket = global.WebSocket || global.MozWebSocket;
  31536. /**
  31537. * Module exports.
  31538. */
  31539. module.exports = WebSocket ? ws : null;
  31540. /**
  31541. * WebSocket constructor.
  31542. *
  31543. * The third `opts` options object gets ignored in web browsers, since it's
  31544. * non-standard, and throws a TypeError if passed to the constructor.
  31545. * See: https://github.com/einaros/ws/issues/227
  31546. *
  31547. * @param {String} uri
  31548. * @param {Array} protocols (optional)
  31549. * @param {Object) opts (optional)
  31550. * @api public
  31551. */
  31552. function ws(uri, protocols, opts) {
  31553. var instance;
  31554. if (protocols) {
  31555. instance = new WebSocket(uri, protocols);
  31556. } else {
  31557. instance = new WebSocket(uri);
  31558. }
  31559. return instance;
  31560. }
  31561. if (WebSocket) ws.prototype = WebSocket.prototype;
  31562. },{}],148:[function(require,module,exports){
  31563. (function (global){
  31564. /*
  31565. * Module requirements.
  31566. */
  31567. var isArray = require('isarray');
  31568. /**
  31569. * Module exports.
  31570. */
  31571. module.exports = hasBinary;
  31572. /**
  31573. * Checks for binary data.
  31574. *
  31575. * Right now only Buffer and ArrayBuffer are supported..
  31576. *
  31577. * @param {Object} anything
  31578. * @api public
  31579. */
  31580. function hasBinary(data) {
  31581. function _hasBinary(obj) {
  31582. if (!obj) return false;
  31583. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  31584. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  31585. (global.Blob && obj instanceof Blob) ||
  31586. (global.File && obj instanceof File)
  31587. ) {
  31588. return true;
  31589. }
  31590. if (isArray(obj)) {
  31591. for (var i = 0; i < obj.length; i++) {
  31592. if (_hasBinary(obj[i])) {
  31593. return true;
  31594. }
  31595. }
  31596. } else if (obj && 'object' == typeof obj) {
  31597. if (obj.toJSON) {
  31598. obj = obj.toJSON();
  31599. }
  31600. for (var key in obj) {
  31601. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  31602. return true;
  31603. }
  31604. }
  31605. }
  31606. return false;
  31607. }
  31608. return _hasBinary(data);
  31609. }
  31610. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31611. },{"isarray":149}],149:[function(require,module,exports){
  31612. arguments[4][140][0].apply(exports,arguments)
  31613. },{"dup":140}],150:[function(require,module,exports){
  31614. var indexOf = [].indexOf;
  31615. module.exports = function(arr, obj){
  31616. if (indexOf) return arr.indexOf(obj);
  31617. for (var i = 0; i < arr.length; ++i) {
  31618. if (arr[i] === obj) return i;
  31619. }
  31620. return -1;
  31621. };
  31622. },{}],151:[function(require,module,exports){
  31623. /**
  31624. * HOP ref.
  31625. */
  31626. var has = Object.prototype.hasOwnProperty;
  31627. /**
  31628. * Return own keys in `obj`.
  31629. *
  31630. * @param {Object} obj
  31631. * @return {Array}
  31632. * @api public
  31633. */
  31634. exports.keys = Object.keys || function(obj){
  31635. var keys = [];
  31636. for (var key in obj) {
  31637. if (has.call(obj, key)) {
  31638. keys.push(key);
  31639. }
  31640. }
  31641. return keys;
  31642. };
  31643. /**
  31644. * Return own values in `obj`.
  31645. *
  31646. * @param {Object} obj
  31647. * @return {Array}
  31648. * @api public
  31649. */
  31650. exports.values = function(obj){
  31651. var vals = [];
  31652. for (var key in obj) {
  31653. if (has.call(obj, key)) {
  31654. vals.push(obj[key]);
  31655. }
  31656. }
  31657. return vals;
  31658. };
  31659. /**
  31660. * Merge `b` into `a`.
  31661. *
  31662. * @param {Object} a
  31663. * @param {Object} b
  31664. * @return {Object} a
  31665. * @api public
  31666. */
  31667. exports.merge = function(a, b){
  31668. for (var key in b) {
  31669. if (has.call(b, key)) {
  31670. a[key] = b[key];
  31671. }
  31672. }
  31673. return a;
  31674. };
  31675. /**
  31676. * Return length of `obj`.
  31677. *
  31678. * @param {Object} obj
  31679. * @return {Number}
  31680. * @api public
  31681. */
  31682. exports.length = function(obj){
  31683. return exports.keys(obj).length;
  31684. };
  31685. /**
  31686. * Check if `obj` is empty.
  31687. *
  31688. * @param {Object} obj
  31689. * @return {Boolean}
  31690. * @api public
  31691. */
  31692. exports.isEmpty = function(obj){
  31693. return 0 == exports.length(obj);
  31694. };
  31695. },{}],152:[function(require,module,exports){
  31696. /**
  31697. * Parses an URI
  31698. *
  31699. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  31700. * @api private
  31701. */
  31702. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  31703. var parts = [
  31704. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  31705. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  31706. ];
  31707. module.exports = function parseuri(str) {
  31708. var m = re.exec(str || '')
  31709. , uri = {}
  31710. , i = 14;
  31711. while (i--) {
  31712. uri[parts[i]] = m[i] || '';
  31713. }
  31714. return uri;
  31715. };
  31716. },{}],153:[function(require,module,exports){
  31717. (function (global){
  31718. /*global Blob,File*/
  31719. /**
  31720. * Module requirements
  31721. */
  31722. var isArray = require('isarray');
  31723. var isBuf = require('./is-buffer');
  31724. /**
  31725. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  31726. * Anything with blobs or files should be fed through removeBlobs before coming
  31727. * here.
  31728. *
  31729. * @param {Object} packet - socket.io event packet
  31730. * @return {Object} with deconstructed packet and list of buffers
  31731. * @api public
  31732. */
  31733. exports.deconstructPacket = function(packet){
  31734. var buffers = [];
  31735. var packetData = packet.data;
  31736. function _deconstructPacket(data) {
  31737. if (!data) return data;
  31738. if (isBuf(data)) {
  31739. var placeholder = { _placeholder: true, num: buffers.length };
  31740. buffers.push(data);
  31741. return placeholder;
  31742. } else if (isArray(data)) {
  31743. var newData = new Array(data.length);
  31744. for (var i = 0; i < data.length; i++) {
  31745. newData[i] = _deconstructPacket(data[i]);
  31746. }
  31747. return newData;
  31748. } else if ('object' == typeof data && !(data instanceof Date)) {
  31749. var newData = {};
  31750. for (var key in data) {
  31751. newData[key] = _deconstructPacket(data[key]);
  31752. }
  31753. return newData;
  31754. }
  31755. return data;
  31756. }
  31757. var pack = packet;
  31758. pack.data = _deconstructPacket(packetData);
  31759. pack.attachments = buffers.length; // number of binary 'attachments'
  31760. return {packet: pack, buffers: buffers};
  31761. };
  31762. /**
  31763. * Reconstructs a binary packet from its placeholder packet and buffers
  31764. *
  31765. * @param {Object} packet - event packet with placeholders
  31766. * @param {Array} buffers - binary buffers to put in placeholder positions
  31767. * @return {Object} reconstructed packet
  31768. * @api public
  31769. */
  31770. exports.reconstructPacket = function(packet, buffers) {
  31771. var curPlaceHolder = 0;
  31772. function _reconstructPacket(data) {
  31773. if (data && data._placeholder) {
  31774. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  31775. return buf;
  31776. } else if (isArray(data)) {
  31777. for (var i = 0; i < data.length; i++) {
  31778. data[i] = _reconstructPacket(data[i]);
  31779. }
  31780. return data;
  31781. } else if (data && 'object' == typeof data) {
  31782. for (var key in data) {
  31783. data[key] = _reconstructPacket(data[key]);
  31784. }
  31785. return data;
  31786. }
  31787. return data;
  31788. }
  31789. packet.data = _reconstructPacket(packet.data);
  31790. packet.attachments = undefined; // no longer useful
  31791. return packet;
  31792. };
  31793. /**
  31794. * Asynchronously removes Blobs or Files from data via
  31795. * FileReader's readAsArrayBuffer method. Used before encoding
  31796. * data as msgpack. Calls callback with the blobless data.
  31797. *
  31798. * @param {Object} data
  31799. * @param {Function} callback
  31800. * @api private
  31801. */
  31802. exports.removeBlobs = function(data, callback) {
  31803. function _removeBlobs(obj, curKey, containingObject) {
  31804. if (!obj) return obj;
  31805. // convert any blob
  31806. if ((global.Blob && obj instanceof Blob) ||
  31807. (global.File && obj instanceof File)) {
  31808. pendingBlobs++;
  31809. // async filereader
  31810. var fileReader = new FileReader();
  31811. fileReader.onload = function() { // this.result == arraybuffer
  31812. if (containingObject) {
  31813. containingObject[curKey] = this.result;
  31814. }
  31815. else {
  31816. bloblessData = this.result;
  31817. }
  31818. // if nothing pending its callback time
  31819. if(! --pendingBlobs) {
  31820. callback(bloblessData);
  31821. }
  31822. };
  31823. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  31824. } else if (isArray(obj)) { // handle array
  31825. for (var i = 0; i < obj.length; i++) {
  31826. _removeBlobs(obj[i], i, obj);
  31827. }
  31828. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  31829. for (var key in obj) {
  31830. _removeBlobs(obj[key], key, obj);
  31831. }
  31832. }
  31833. }
  31834. var pendingBlobs = 0;
  31835. var bloblessData = data;
  31836. _removeBlobs(bloblessData);
  31837. if (!pendingBlobs) {
  31838. callback(bloblessData);
  31839. }
  31840. };
  31841. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31842. },{"./is-buffer":155,"isarray":156}],154:[function(require,module,exports){
  31843. /**
  31844. * Module dependencies.
  31845. */
  31846. var debug = require('debug')('socket.io-parser');
  31847. var json = require('json3');
  31848. var isArray = require('isarray');
  31849. var Emitter = require('component-emitter');
  31850. var binary = require('./binary');
  31851. var isBuf = require('./is-buffer');
  31852. /**
  31853. * Protocol version.
  31854. *
  31855. * @api public
  31856. */
  31857. exports.protocol = 4;
  31858. /**
  31859. * Packet types.
  31860. *
  31861. * @api public
  31862. */
  31863. exports.types = [
  31864. 'CONNECT',
  31865. 'DISCONNECT',
  31866. 'EVENT',
  31867. 'BINARY_EVENT',
  31868. 'ACK',
  31869. 'BINARY_ACK',
  31870. 'ERROR'
  31871. ];
  31872. /**
  31873. * Packet type `connect`.
  31874. *
  31875. * @api public
  31876. */
  31877. exports.CONNECT = 0;
  31878. /**
  31879. * Packet type `disconnect`.
  31880. *
  31881. * @api public
  31882. */
  31883. exports.DISCONNECT = 1;
  31884. /**
  31885. * Packet type `event`.
  31886. *
  31887. * @api public
  31888. */
  31889. exports.EVENT = 2;
  31890. /**
  31891. * Packet type `ack`.
  31892. *
  31893. * @api public
  31894. */
  31895. exports.ACK = 3;
  31896. /**
  31897. * Packet type `error`.
  31898. *
  31899. * @api public
  31900. */
  31901. exports.ERROR = 4;
  31902. /**
  31903. * Packet type 'binary event'
  31904. *
  31905. * @api public
  31906. */
  31907. exports.BINARY_EVENT = 5;
  31908. /**
  31909. * Packet type `binary ack`. For acks with binary arguments.
  31910. *
  31911. * @api public
  31912. */
  31913. exports.BINARY_ACK = 6;
  31914. /**
  31915. * Encoder constructor.
  31916. *
  31917. * @api public
  31918. */
  31919. exports.Encoder = Encoder;
  31920. /**
  31921. * Decoder constructor.
  31922. *
  31923. * @api public
  31924. */
  31925. exports.Decoder = Decoder;
  31926. /**
  31927. * A socket.io Encoder instance
  31928. *
  31929. * @api public
  31930. */
  31931. function Encoder() {}
  31932. /**
  31933. * Encode a packet as a single string if non-binary, or as a
  31934. * buffer sequence, depending on packet type.
  31935. *
  31936. * @param {Object} obj - packet object
  31937. * @param {Function} callback - function to handle encodings (likely engine.write)
  31938. * @return Calls callback with Array of encodings
  31939. * @api public
  31940. */
  31941. Encoder.prototype.encode = function(obj, callback){
  31942. debug('encoding packet %j', obj);
  31943. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  31944. encodeAsBinary(obj, callback);
  31945. }
  31946. else {
  31947. var encoding = encodeAsString(obj);
  31948. callback([encoding]);
  31949. }
  31950. };
  31951. /**
  31952. * Encode packet as string.
  31953. *
  31954. * @param {Object} packet
  31955. * @return {String} encoded
  31956. * @api private
  31957. */
  31958. function encodeAsString(obj) {
  31959. var str = '';
  31960. var nsp = false;
  31961. // first is type
  31962. str += obj.type;
  31963. // attachments if we have them
  31964. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  31965. str += obj.attachments;
  31966. str += '-';
  31967. }
  31968. // if we have a namespace other than `/`
  31969. // we append it followed by a comma `,`
  31970. if (obj.nsp && '/' != obj.nsp) {
  31971. nsp = true;
  31972. str += obj.nsp;
  31973. }
  31974. // immediately followed by the id
  31975. if (null != obj.id) {
  31976. if (nsp) {
  31977. str += ',';
  31978. nsp = false;
  31979. }
  31980. str += obj.id;
  31981. }
  31982. // json data
  31983. if (null != obj.data) {
  31984. if (nsp) str += ',';
  31985. str += json.stringify(obj.data);
  31986. }
  31987. debug('encoded %j as %s', obj, str);
  31988. return str;
  31989. }
  31990. /**
  31991. * Encode packet as 'buffer sequence' by removing blobs, and
  31992. * deconstructing packet into object with placeholders and
  31993. * a list of buffers.
  31994. *
  31995. * @param {Object} packet
  31996. * @return {Buffer} encoded
  31997. * @api private
  31998. */
  31999. function encodeAsBinary(obj, callback) {
  32000. function writeEncoding(bloblessData) {
  32001. var deconstruction = binary.deconstructPacket(bloblessData);
  32002. var pack = encodeAsString(deconstruction.packet);
  32003. var buffers = deconstruction.buffers;
  32004. buffers.unshift(pack); // add packet info to beginning of data list
  32005. callback(buffers); // write all the buffers
  32006. }
  32007. binary.removeBlobs(obj, writeEncoding);
  32008. }
  32009. /**
  32010. * A socket.io Decoder instance
  32011. *
  32012. * @return {Object} decoder
  32013. * @api public
  32014. */
  32015. function Decoder() {
  32016. this.reconstructor = null;
  32017. }
  32018. /**
  32019. * Mix in `Emitter` with Decoder.
  32020. */
  32021. Emitter(Decoder.prototype);
  32022. /**
  32023. * Decodes an ecoded packet string into packet JSON.
  32024. *
  32025. * @param {String} obj - encoded packet
  32026. * @return {Object} packet
  32027. * @api public
  32028. */
  32029. Decoder.prototype.add = function(obj) {
  32030. var packet;
  32031. if ('string' == typeof obj) {
  32032. packet = decodeString(obj);
  32033. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  32034. this.reconstructor = new BinaryReconstructor(packet);
  32035. // no attachments, labeled binary but no binary data to follow
  32036. if (this.reconstructor.reconPack.attachments === 0) {
  32037. this.emit('decoded', packet);
  32038. }
  32039. } else { // non-binary full packet
  32040. this.emit('decoded', packet);
  32041. }
  32042. }
  32043. else if (isBuf(obj) || obj.base64) { // raw binary data
  32044. if (!this.reconstructor) {
  32045. throw new Error('got binary data when not reconstructing a packet');
  32046. } else {
  32047. packet = this.reconstructor.takeBinaryData(obj);
  32048. if (packet) { // received final buffer
  32049. this.reconstructor = null;
  32050. this.emit('decoded', packet);
  32051. }
  32052. }
  32053. }
  32054. else {
  32055. throw new Error('Unknown type: ' + obj);
  32056. }
  32057. };
  32058. /**
  32059. * Decode a packet String (JSON data)
  32060. *
  32061. * @param {String} str
  32062. * @return {Object} packet
  32063. * @api private
  32064. */
  32065. function decodeString(str) {
  32066. var p = {};
  32067. var i = 0;
  32068. // look up type
  32069. p.type = Number(str.charAt(0));
  32070. if (null == exports.types[p.type]) return error();
  32071. // look up attachments if type binary
  32072. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  32073. var buf = '';
  32074. while (str.charAt(++i) != '-') {
  32075. buf += str.charAt(i);
  32076. if (i == str.length) break;
  32077. }
  32078. if (buf != Number(buf) || str.charAt(i) != '-') {
  32079. throw new Error('Illegal attachments');
  32080. }
  32081. p.attachments = Number(buf);
  32082. }
  32083. // look up namespace (if any)
  32084. if ('/' == str.charAt(i + 1)) {
  32085. p.nsp = '';
  32086. while (++i) {
  32087. var c = str.charAt(i);
  32088. if (',' == c) break;
  32089. p.nsp += c;
  32090. if (i == str.length) break;
  32091. }
  32092. } else {
  32093. p.nsp = '/';
  32094. }
  32095. // look up id
  32096. var next = str.charAt(i + 1);
  32097. if ('' !== next && Number(next) == next) {
  32098. p.id = '';
  32099. while (++i) {
  32100. var c = str.charAt(i);
  32101. if (null == c || Number(c) != c) {
  32102. --i;
  32103. break;
  32104. }
  32105. p.id += str.charAt(i);
  32106. if (i == str.length) break;
  32107. }
  32108. p.id = Number(p.id);
  32109. }
  32110. // look up json data
  32111. if (str.charAt(++i)) {
  32112. try {
  32113. p.data = json.parse(str.substr(i));
  32114. } catch(e){
  32115. return error();
  32116. }
  32117. }
  32118. debug('decoded %s as %j', str, p);
  32119. return p;
  32120. }
  32121. /**
  32122. * Deallocates a parser's resources
  32123. *
  32124. * @api public
  32125. */
  32126. Decoder.prototype.destroy = function() {
  32127. if (this.reconstructor) {
  32128. this.reconstructor.finishedReconstruction();
  32129. }
  32130. };
  32131. /**
  32132. * A manager of a binary event's 'buffer sequence'. Should
  32133. * be constructed whenever a packet of type BINARY_EVENT is
  32134. * decoded.
  32135. *
  32136. * @param {Object} packet
  32137. * @return {BinaryReconstructor} initialized reconstructor
  32138. * @api private
  32139. */
  32140. function BinaryReconstructor(packet) {
  32141. this.reconPack = packet;
  32142. this.buffers = [];
  32143. }
  32144. /**
  32145. * Method to be called when binary data received from connection
  32146. * after a BINARY_EVENT packet.
  32147. *
  32148. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  32149. * @return {null | Object} returns null if more binary data is expected or
  32150. * a reconstructed packet object if all buffers have been received.
  32151. * @api private
  32152. */
  32153. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  32154. this.buffers.push(binData);
  32155. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  32156. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  32157. this.finishedReconstruction();
  32158. return packet;
  32159. }
  32160. return null;
  32161. };
  32162. /**
  32163. * Cleans up binary packet reconstruction variables.
  32164. *
  32165. * @api private
  32166. */
  32167. BinaryReconstructor.prototype.finishedReconstruction = function() {
  32168. this.reconPack = null;
  32169. this.buffers = [];
  32170. };
  32171. function error(data){
  32172. return {
  32173. type: exports.ERROR,
  32174. data: 'parser error'
  32175. };
  32176. }
  32177. },{"./binary":153,"./is-buffer":155,"component-emitter":117,"debug":118,"isarray":156,"json3":157}],155:[function(require,module,exports){
  32178. (function (global){
  32179. module.exports = isBuf;
  32180. /**
  32181. * Returns true if obj is a buffer or an arraybuffer.
  32182. *
  32183. * @api private
  32184. */
  32185. function isBuf(obj) {
  32186. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  32187. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  32188. }
  32189. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  32190. },{}],156:[function(require,module,exports){
  32191. arguments[4][140][0].apply(exports,arguments)
  32192. },{"dup":140}],157:[function(require,module,exports){
  32193. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  32194. ;(function (window) {
  32195. // Convenience aliases.
  32196. var getClass = {}.toString, isProperty, forEach, undef;
  32197. // Detect the `define` function exposed by asynchronous module loaders. The
  32198. // strict `define` check is necessary for compatibility with `r.js`.
  32199. var isLoader = typeof define === "function" && define.amd;
  32200. // Detect native implementations.
  32201. var nativeJSON = typeof JSON == "object" && JSON;
  32202. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  32203. // available.
  32204. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  32205. if (JSON3 && nativeJSON) {
  32206. // Explicitly delegate to the native `stringify` and `parse`
  32207. // implementations in CommonJS environments.
  32208. JSON3.stringify = nativeJSON.stringify;
  32209. JSON3.parse = nativeJSON.parse;
  32210. } else {
  32211. // Export for web browsers, JavaScript engines, and asynchronous module
  32212. // loaders, using the global `JSON` object if available.
  32213. JSON3 = window.JSON = nativeJSON || {};
  32214. }
  32215. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  32216. var isExtended = new Date(-3509827334573292);
  32217. try {
  32218. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  32219. // results for certain dates in Opera >= 10.53.
  32220. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  32221. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  32222. // but clips the values returned by the date methods to the range of
  32223. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  32224. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  32225. } catch (exception) {}
  32226. // Internal: Determines whether the native `JSON.stringify` and `parse`
  32227. // implementations are spec-compliant. Based on work by Ken Snyder.
  32228. function has(name) {
  32229. if (has[name] !== undef) {
  32230. // Return cached feature test result.
  32231. return has[name];
  32232. }
  32233. var isSupported;
  32234. if (name == "bug-string-char-index") {
  32235. // IE <= 7 doesn't support accessing string characters using square
  32236. // bracket notation. IE 8 only supports this for primitives.
  32237. isSupported = "a"[0] != "a";
  32238. } else if (name == "json") {
  32239. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  32240. // supported.
  32241. isSupported = has("json-stringify") && has("json-parse");
  32242. } else {
  32243. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  32244. // Test `JSON.stringify`.
  32245. if (name == "json-stringify") {
  32246. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  32247. if (stringifySupported) {
  32248. // A test function object with a custom `toJSON` method.
  32249. (value = function () {
  32250. return 1;
  32251. }).toJSON = value;
  32252. try {
  32253. stringifySupported =
  32254. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  32255. // primitives as object literals.
  32256. stringify(0) === "0" &&
  32257. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  32258. // literals.
  32259. stringify(new Number()) === "0" &&
  32260. stringify(new String()) == '""' &&
  32261. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  32262. // does not define a canonical JSON representation (this applies to
  32263. // objects with `toJSON` properties as well, *unless* they are nested
  32264. // within an object or array).
  32265. stringify(getClass) === undef &&
  32266. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  32267. // FF 3.1b3 pass this test.
  32268. stringify(undef) === undef &&
  32269. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  32270. // respectively, if the value is omitted entirely.
  32271. stringify() === undef &&
  32272. // FF 3.1b1, 2 throw an error if the given value is not a number,
  32273. // string, array, object, Boolean, or `null` literal. This applies to
  32274. // objects with custom `toJSON` methods as well, unless they are nested
  32275. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  32276. // methods entirely.
  32277. stringify(value) === "1" &&
  32278. stringify([value]) == "[1]" &&
  32279. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  32280. // `"[null]"`.
  32281. stringify([undef]) == "[null]" &&
  32282. // YUI 3.0.0b1 fails to serialize `null` literals.
  32283. stringify(null) == "null" &&
  32284. // FF 3.1b1, 2 halts serialization if an array contains a function:
  32285. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  32286. // elides non-JSON values from objects and arrays, unless they
  32287. // define custom `toJSON` methods.
  32288. stringify([undef, getClass, null]) == "[null,null,null]" &&
  32289. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  32290. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  32291. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  32292. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  32293. stringify(null, value) === "1" &&
  32294. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  32295. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  32296. // serialize extended years.
  32297. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  32298. // The milliseconds are optional in ES 5, but required in 5.1.
  32299. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  32300. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  32301. // four-digit years instead of six-digit years. Credits: @Yaffle.
  32302. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  32303. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  32304. // values less than 1000. Credits: @Yaffle.
  32305. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  32306. } catch (exception) {
  32307. stringifySupported = false;
  32308. }
  32309. }
  32310. isSupported = stringifySupported;
  32311. }
  32312. // Test `JSON.parse`.
  32313. if (name == "json-parse") {
  32314. var parse = JSON3.parse;
  32315. if (typeof parse == "function") {
  32316. try {
  32317. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  32318. // Conforming implementations should also coerce the initial argument to
  32319. // a string prior to parsing.
  32320. if (parse("0") === 0 && !parse(false)) {
  32321. // Simple parsing test.
  32322. value = parse(serialized);
  32323. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  32324. if (parseSupported) {
  32325. try {
  32326. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  32327. parseSupported = !parse('"\t"');
  32328. } catch (exception) {}
  32329. if (parseSupported) {
  32330. try {
  32331. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  32332. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  32333. // certain octal literals.
  32334. parseSupported = parse("01") !== 1;
  32335. } catch (exception) {}
  32336. }
  32337. if (parseSupported) {
  32338. try {
  32339. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  32340. // points. These environments, along with FF 3.1b1 and 2,
  32341. // also allow trailing commas in JSON objects and arrays.
  32342. parseSupported = parse("1.") !== 1;
  32343. } catch (exception) {}
  32344. }
  32345. }
  32346. }
  32347. } catch (exception) {
  32348. parseSupported = false;
  32349. }
  32350. }
  32351. isSupported = parseSupported;
  32352. }
  32353. }
  32354. return has[name] = !!isSupported;
  32355. }
  32356. if (!has("json")) {
  32357. // Common `[[Class]]` name aliases.
  32358. var functionClass = "[object Function]";
  32359. var dateClass = "[object Date]";
  32360. var numberClass = "[object Number]";
  32361. var stringClass = "[object String]";
  32362. var arrayClass = "[object Array]";
  32363. var booleanClass = "[object Boolean]";
  32364. // Detect incomplete support for accessing string characters by index.
  32365. var charIndexBuggy = has("bug-string-char-index");
  32366. // Define additional utility methods if the `Date` methods are buggy.
  32367. if (!isExtended) {
  32368. var floor = Math.floor;
  32369. // A mapping between the months of the year and the number of days between
  32370. // January 1st and the first of the respective month.
  32371. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  32372. // Internal: Calculates the number of days between the Unix epoch and the
  32373. // first day of the given month.
  32374. var getDay = function (year, month) {
  32375. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  32376. };
  32377. }
  32378. // Internal: Determines if a property is a direct property of the given
  32379. // object. Delegates to the native `Object#hasOwnProperty` method.
  32380. if (!(isProperty = {}.hasOwnProperty)) {
  32381. isProperty = function (property) {
  32382. var members = {}, constructor;
  32383. if ((members.__proto__ = null, members.__proto__ = {
  32384. // The *proto* property cannot be set multiple times in recent
  32385. // versions of Firefox and SeaMonkey.
  32386. "toString": 1
  32387. }, members).toString != getClass) {
  32388. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  32389. // supports the mutable *proto* property.
  32390. isProperty = function (property) {
  32391. // Capture and break the object's prototype chain (see section 8.6.2
  32392. // of the ES 5.1 spec). The parenthesized expression prevents an
  32393. // unsafe transformation by the Closure Compiler.
  32394. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  32395. // Restore the original prototype chain.
  32396. this.__proto__ = original;
  32397. return result;
  32398. };
  32399. } else {
  32400. // Capture a reference to the top-level `Object` constructor.
  32401. constructor = members.constructor;
  32402. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  32403. // other environments.
  32404. isProperty = function (property) {
  32405. var parent = (this.constructor || constructor).prototype;
  32406. return property in this && !(property in parent && this[property] === parent[property]);
  32407. };
  32408. }
  32409. members = null;
  32410. return isProperty.call(this, property);
  32411. };
  32412. }
  32413. // Internal: A set of primitive types used by `isHostType`.
  32414. var PrimitiveTypes = {
  32415. 'boolean': 1,
  32416. 'number': 1,
  32417. 'string': 1,
  32418. 'undefined': 1
  32419. };
  32420. // Internal: Determines if the given object `property` value is a
  32421. // non-primitive.
  32422. var isHostType = function (object, property) {
  32423. var type = typeof object[property];
  32424. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  32425. };
  32426. // Internal: Normalizes the `for...in` iteration algorithm across
  32427. // environments. Each enumerated key is yielded to a `callback` function.
  32428. forEach = function (object, callback) {
  32429. var size = 0, Properties, members, property;
  32430. // Tests for bugs in the current environment's `for...in` algorithm. The
  32431. // `valueOf` property inherits the non-enumerable flag from
  32432. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  32433. (Properties = function () {
  32434. this.valueOf = 0;
  32435. }).prototype.valueOf = 0;
  32436. // Iterate over a new instance of the `Properties` class.
  32437. members = new Properties();
  32438. for (property in members) {
  32439. // Ignore all properties inherited from `Object.prototype`.
  32440. if (isProperty.call(members, property)) {
  32441. size++;
  32442. }
  32443. }
  32444. Properties = members = null;
  32445. // Normalize the iteration algorithm.
  32446. if (!size) {
  32447. // A list of non-enumerable properties inherited from `Object.prototype`.
  32448. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  32449. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  32450. // properties.
  32451. forEach = function (object, callback) {
  32452. var isFunction = getClass.call(object) == functionClass, property, length;
  32453. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  32454. for (property in object) {
  32455. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  32456. // certain conditions; IE does not.
  32457. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  32458. callback(property);
  32459. }
  32460. }
  32461. // Manually invoke the callback for each non-enumerable property.
  32462. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  32463. };
  32464. } else if (size == 2) {
  32465. // Safari <= 2.0.4 enumerates shadowed properties twice.
  32466. forEach = function (object, callback) {
  32467. // Create a set of iterated properties.
  32468. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  32469. for (property in object) {
  32470. // Store each property name to prevent double enumeration. The
  32471. // `prototype` property of functions is not enumerated due to cross-
  32472. // environment inconsistencies.
  32473. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  32474. callback(property);
  32475. }
  32476. }
  32477. };
  32478. } else {
  32479. // No bugs detected; use the standard `for...in` algorithm.
  32480. forEach = function (object, callback) {
  32481. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  32482. for (property in object) {
  32483. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  32484. callback(property);
  32485. }
  32486. }
  32487. // Manually invoke the callback for the `constructor` property due to
  32488. // cross-environment inconsistencies.
  32489. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  32490. callback(property);
  32491. }
  32492. };
  32493. }
  32494. return forEach(object, callback);
  32495. };
  32496. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  32497. // `filter` argument may specify either a function that alters how object and
  32498. // array members are serialized, or an array of strings and numbers that
  32499. // indicates which properties should be serialized. The optional `width`
  32500. // argument may be either a string or number that specifies the indentation
  32501. // level of the output.
  32502. if (!has("json-stringify")) {
  32503. // Internal: A map of control characters and their escaped equivalents.
  32504. var Escapes = {
  32505. 92: "\\\\",
  32506. 34: '\\"',
  32507. 8: "\\b",
  32508. 12: "\\f",
  32509. 10: "\\n",
  32510. 13: "\\r",
  32511. 9: "\\t"
  32512. };
  32513. // Internal: Converts `value` into a zero-padded string such that its
  32514. // length is at least equal to `width`. The `width` must be <= 6.
  32515. var leadingZeroes = "000000";
  32516. var toPaddedString = function (width, value) {
  32517. // The `|| 0` expression is necessary to work around a bug in
  32518. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  32519. return (leadingZeroes + (value || 0)).slice(-width);
  32520. };
  32521. // Internal: Double-quotes a string `value`, replacing all ASCII control
  32522. // characters (characters with code unit values between 0 and 31) with
  32523. // their escaped equivalents. This is an implementation of the
  32524. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  32525. var unicodePrefix = "\\u00";
  32526. var quote = function (value) {
  32527. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  32528. if (isLarge) {
  32529. symbols = value.split("");
  32530. }
  32531. for (; index < length; index++) {
  32532. var charCode = value.charCodeAt(index);
  32533. // If the character is a control character, append its Unicode or
  32534. // shorthand escape sequence; otherwise, append the character as-is.
  32535. switch (charCode) {
  32536. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  32537. result += Escapes[charCode];
  32538. break;
  32539. default:
  32540. if (charCode < 32) {
  32541. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  32542. break;
  32543. }
  32544. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  32545. }
  32546. }
  32547. return result + '"';
  32548. };
  32549. // Internal: Recursively serializes an object. Implements the
  32550. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  32551. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  32552. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  32553. try {
  32554. // Necessary for host object support.
  32555. value = object[property];
  32556. } catch (exception) {}
  32557. if (typeof value == "object" && value) {
  32558. className = getClass.call(value);
  32559. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  32560. if (value > -1 / 0 && value < 1 / 0) {
  32561. // Dates are serialized according to the `Date#toJSON` method
  32562. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  32563. // for the ISO 8601 date time string format.
  32564. if (getDay) {
  32565. // Manually compute the year, month, date, hours, minutes,
  32566. // seconds, and milliseconds if the `getUTC*` methods are
  32567. // buggy. Adapted from @Yaffle's `date-shim` project.
  32568. date = floor(value / 864e5);
  32569. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  32570. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  32571. date = 1 + date - getDay(year, month);
  32572. // The `time` value specifies the time within the day (see ES
  32573. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  32574. // to compute `A modulo B`, as the `%` operator does not
  32575. // correspond to the `modulo` operation for negative numbers.
  32576. time = (value % 864e5 + 864e5) % 864e5;
  32577. // The hours, minutes, seconds, and milliseconds are obtained by
  32578. // decomposing the time within the day. See section 15.9.1.10.
  32579. hours = floor(time / 36e5) % 24;
  32580. minutes = floor(time / 6e4) % 60;
  32581. seconds = floor(time / 1e3) % 60;
  32582. milliseconds = time % 1e3;
  32583. } else {
  32584. year = value.getUTCFullYear();
  32585. month = value.getUTCMonth();
  32586. date = value.getUTCDate();
  32587. hours = value.getUTCHours();
  32588. minutes = value.getUTCMinutes();
  32589. seconds = value.getUTCSeconds();
  32590. milliseconds = value.getUTCMilliseconds();
  32591. }
  32592. // Serialize extended years correctly.
  32593. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  32594. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  32595. // Months, dates, hours, minutes, and seconds should have two
  32596. // digits; milliseconds should have three.
  32597. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  32598. // Milliseconds are optional in ES 5.0, but required in 5.1.
  32599. "." + toPaddedString(3, milliseconds) + "Z";
  32600. } else {
  32601. value = null;
  32602. }
  32603. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  32604. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  32605. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  32606. // ignores all `toJSON` methods on these objects unless they are
  32607. // defined directly on an instance.
  32608. value = value.toJSON(property);
  32609. }
  32610. }
  32611. if (callback) {
  32612. // If a replacement function was provided, call it to obtain the value
  32613. // for serialization.
  32614. value = callback.call(object, property, value);
  32615. }
  32616. if (value === null) {
  32617. return "null";
  32618. }
  32619. className = getClass.call(value);
  32620. if (className == booleanClass) {
  32621. // Booleans are represented literally.
  32622. return "" + value;
  32623. } else if (className == numberClass) {
  32624. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  32625. // `"null"`.
  32626. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  32627. } else if (className == stringClass) {
  32628. // Strings are double-quoted and escaped.
  32629. return quote("" + value);
  32630. }
  32631. // Recursively serialize objects and arrays.
  32632. if (typeof value == "object") {
  32633. // Check for cyclic structures. This is a linear search; performance
  32634. // is inversely proportional to the number of unique nested objects.
  32635. for (length = stack.length; length--;) {
  32636. if (stack[length] === value) {
  32637. // Cyclic structures cannot be serialized by `JSON.stringify`.
  32638. throw TypeError();
  32639. }
  32640. }
  32641. // Add the object to the stack of traversed objects.
  32642. stack.push(value);
  32643. results = [];
  32644. // Save the current indentation level and indent one additional level.
  32645. prefix = indentation;
  32646. indentation += whitespace;
  32647. if (className == arrayClass) {
  32648. // Recursively serialize array elements.
  32649. for (index = 0, length = value.length; index < length; index++) {
  32650. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  32651. results.push(element === undef ? "null" : element);
  32652. }
  32653. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  32654. } else {
  32655. // Recursively serialize object members. Members are selected from
  32656. // either a user-specified list of property names, or the object
  32657. // itself.
  32658. forEach(properties || value, function (property) {
  32659. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  32660. if (element !== undef) {
  32661. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  32662. // is not the empty string, let `member` {quote(property) + ":"}
  32663. // be the concatenation of `member` and the `space` character."
  32664. // The "`space` character" refers to the literal space
  32665. // character, not the `space` {width} argument provided to
  32666. // `JSON.stringify`.
  32667. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  32668. }
  32669. });
  32670. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  32671. }
  32672. // Remove the object from the traversed object stack.
  32673. stack.pop();
  32674. return result;
  32675. }
  32676. };
  32677. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  32678. JSON3.stringify = function (source, filter, width) {
  32679. var whitespace, callback, properties, className;
  32680. if (typeof filter == "function" || typeof filter == "object" && filter) {
  32681. if ((className = getClass.call(filter)) == functionClass) {
  32682. callback = filter;
  32683. } else if (className == arrayClass) {
  32684. // Convert the property names array into a makeshift set.
  32685. properties = {};
  32686. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  32687. }
  32688. }
  32689. if (width) {
  32690. if ((className = getClass.call(width)) == numberClass) {
  32691. // Convert the `width` to an integer and create a string containing
  32692. // `width` number of space characters.
  32693. if ((width -= width % 1) > 0) {
  32694. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  32695. }
  32696. } else if (className == stringClass) {
  32697. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  32698. }
  32699. }
  32700. // Opera <= 7.54u2 discards the values associated with empty string keys
  32701. // (`""`) only if they are used directly within an object member list
  32702. // (e.g., `!("" in { "": 1})`).
  32703. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  32704. };
  32705. }
  32706. // Public: Parses a JSON source string.
  32707. if (!has("json-parse")) {
  32708. var fromCharCode = String.fromCharCode;
  32709. // Internal: A map of escaped control characters and their unescaped
  32710. // equivalents.
  32711. var Unescapes = {
  32712. 92: "\\",
  32713. 34: '"',
  32714. 47: "/",
  32715. 98: "\b",
  32716. 116: "\t",
  32717. 110: "\n",
  32718. 102: "\f",
  32719. 114: "\r"
  32720. };
  32721. // Internal: Stores the parser state.
  32722. var Index, Source;
  32723. // Internal: Resets the parser state and throws a `SyntaxError`.
  32724. var abort = function() {
  32725. Index = Source = null;
  32726. throw SyntaxError();
  32727. };
  32728. // Internal: Returns the next token, or `"$"` if the parser has reached
  32729. // the end of the source string. A token may be a string, number, `null`
  32730. // literal, or Boolean literal.
  32731. var lex = function () {
  32732. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  32733. while (Index < length) {
  32734. charCode = source.charCodeAt(Index);
  32735. switch (charCode) {
  32736. case 9: case 10: case 13: case 32:
  32737. // Skip whitespace tokens, including tabs, carriage returns, line
  32738. // feeds, and space characters.
  32739. Index++;
  32740. break;
  32741. case 123: case 125: case 91: case 93: case 58: case 44:
  32742. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  32743. // the current position.
  32744. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  32745. Index++;
  32746. return value;
  32747. case 34:
  32748. // `"` delimits a JSON string; advance to the next character and
  32749. // begin parsing the string. String tokens are prefixed with the
  32750. // sentinel `@` character to distinguish them from punctuators and
  32751. // end-of-string tokens.
  32752. for (value = "@", Index++; Index < length;) {
  32753. charCode = source.charCodeAt(Index);
  32754. if (charCode < 32) {
  32755. // Unescaped ASCII control characters (those with a code unit
  32756. // less than the space character) are not permitted.
  32757. abort();
  32758. } else if (charCode == 92) {
  32759. // A reverse solidus (`\`) marks the beginning of an escaped
  32760. // control character (including `"`, `\`, and `/`) or Unicode
  32761. // escape sequence.
  32762. charCode = source.charCodeAt(++Index);
  32763. switch (charCode) {
  32764. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  32765. // Revive escaped control characters.
  32766. value += Unescapes[charCode];
  32767. Index++;
  32768. break;
  32769. case 117:
  32770. // `\u` marks the beginning of a Unicode escape sequence.
  32771. // Advance to the first character and validate the
  32772. // four-digit code point.
  32773. begin = ++Index;
  32774. for (position = Index + 4; Index < position; Index++) {
  32775. charCode = source.charCodeAt(Index);
  32776. // A valid sequence comprises four hexdigits (case-
  32777. // insensitive) that form a single hexadecimal value.
  32778. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  32779. // Invalid Unicode escape sequence.
  32780. abort();
  32781. }
  32782. }
  32783. // Revive the escaped character.
  32784. value += fromCharCode("0x" + source.slice(begin, Index));
  32785. break;
  32786. default:
  32787. // Invalid escape sequence.
  32788. abort();
  32789. }
  32790. } else {
  32791. if (charCode == 34) {
  32792. // An unescaped double-quote character marks the end of the
  32793. // string.
  32794. break;
  32795. }
  32796. charCode = source.charCodeAt(Index);
  32797. begin = Index;
  32798. // Optimize for the common case where a string is valid.
  32799. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  32800. charCode = source.charCodeAt(++Index);
  32801. }
  32802. // Append the string as-is.
  32803. value += source.slice(begin, Index);
  32804. }
  32805. }
  32806. if (source.charCodeAt(Index) == 34) {
  32807. // Advance to the next character and return the revived string.
  32808. Index++;
  32809. return value;
  32810. }
  32811. // Unterminated string.
  32812. abort();
  32813. default:
  32814. // Parse numbers and literals.
  32815. begin = Index;
  32816. // Advance past the negative sign, if one is specified.
  32817. if (charCode == 45) {
  32818. isSigned = true;
  32819. charCode = source.charCodeAt(++Index);
  32820. }
  32821. // Parse an integer or floating-point value.
  32822. if (charCode >= 48 && charCode <= 57) {
  32823. // Leading zeroes are interpreted as octal literals.
  32824. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  32825. // Illegal octal literal.
  32826. abort();
  32827. }
  32828. isSigned = false;
  32829. // Parse the integer component.
  32830. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  32831. // Floats cannot contain a leading decimal point; however, this
  32832. // case is already accounted for by the parser.
  32833. if (source.charCodeAt(Index) == 46) {
  32834. position = ++Index;
  32835. // Parse the decimal component.
  32836. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  32837. if (position == Index) {
  32838. // Illegal trailing decimal.
  32839. abort();
  32840. }
  32841. Index = position;
  32842. }
  32843. // Parse exponents. The `e` denoting the exponent is
  32844. // case-insensitive.
  32845. charCode = source.charCodeAt(Index);
  32846. if (charCode == 101 || charCode == 69) {
  32847. charCode = source.charCodeAt(++Index);
  32848. // Skip past the sign following the exponent, if one is
  32849. // specified.
  32850. if (charCode == 43 || charCode == 45) {
  32851. Index++;
  32852. }
  32853. // Parse the exponential component.
  32854. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  32855. if (position == Index) {
  32856. // Illegal empty exponent.
  32857. abort();
  32858. }
  32859. Index = position;
  32860. }
  32861. // Coerce the parsed value to a JavaScript number.
  32862. return +source.slice(begin, Index);
  32863. }
  32864. // A negative sign may only precede numbers.
  32865. if (isSigned) {
  32866. abort();
  32867. }
  32868. // `true`, `false`, and `null` literals.
  32869. if (source.slice(Index, Index + 4) == "true") {
  32870. Index += 4;
  32871. return true;
  32872. } else if (source.slice(Index, Index + 5) == "false") {
  32873. Index += 5;
  32874. return false;
  32875. } else if (source.slice(Index, Index + 4) == "null") {
  32876. Index += 4;
  32877. return null;
  32878. }
  32879. // Unrecognized token.
  32880. abort();
  32881. }
  32882. }
  32883. // Return the sentinel `$` character if the parser has reached the end
  32884. // of the source string.
  32885. return "$";
  32886. };
  32887. // Internal: Parses a JSON `value` token.
  32888. var get = function (value) {
  32889. var results, hasMembers;
  32890. if (value == "$") {
  32891. // Unexpected end of input.
  32892. abort();
  32893. }
  32894. if (typeof value == "string") {
  32895. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  32896. // Remove the sentinel `@` character.
  32897. return value.slice(1);
  32898. }
  32899. // Parse object and array literals.
  32900. if (value == "[") {
  32901. // Parses a JSON array, returning a new JavaScript array.
  32902. results = [];
  32903. for (;; hasMembers || (hasMembers = true)) {
  32904. value = lex();
  32905. // A closing square bracket marks the end of the array literal.
  32906. if (value == "]") {
  32907. break;
  32908. }
  32909. // If the array literal contains elements, the current token
  32910. // should be a comma separating the previous element from the
  32911. // next.
  32912. if (hasMembers) {
  32913. if (value == ",") {
  32914. value = lex();
  32915. if (value == "]") {
  32916. // Unexpected trailing `,` in array literal.
  32917. abort();
  32918. }
  32919. } else {
  32920. // A `,` must separate each array element.
  32921. abort();
  32922. }
  32923. }
  32924. // Elisions and leading commas are not permitted.
  32925. if (value == ",") {
  32926. abort();
  32927. }
  32928. results.push(get(value));
  32929. }
  32930. return results;
  32931. } else if (value == "{") {
  32932. // Parses a JSON object, returning a new JavaScript object.
  32933. results = {};
  32934. for (;; hasMembers || (hasMembers = true)) {
  32935. value = lex();
  32936. // A closing curly brace marks the end of the object literal.
  32937. if (value == "}") {
  32938. break;
  32939. }
  32940. // If the object literal contains members, the current token
  32941. // should be a comma separator.
  32942. if (hasMembers) {
  32943. if (value == ",") {
  32944. value = lex();
  32945. if (value == "}") {
  32946. // Unexpected trailing `,` in object literal.
  32947. abort();
  32948. }
  32949. } else {
  32950. // A `,` must separate each object member.
  32951. abort();
  32952. }
  32953. }
  32954. // Leading commas are not permitted, object property names must be
  32955. // double-quoted strings, and a `:` must separate each property
  32956. // name and value.
  32957. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  32958. abort();
  32959. }
  32960. results[value.slice(1)] = get(lex());
  32961. }
  32962. return results;
  32963. }
  32964. // Unexpected token encountered.
  32965. abort();
  32966. }
  32967. return value;
  32968. };
  32969. // Internal: Updates a traversed object member.
  32970. var update = function(source, property, callback) {
  32971. var element = walk(source, property, callback);
  32972. if (element === undef) {
  32973. delete source[property];
  32974. } else {
  32975. source[property] = element;
  32976. }
  32977. };
  32978. // Internal: Recursively traverses a parsed JSON object, invoking the
  32979. // `callback` function for each value. This is an implementation of the
  32980. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  32981. var walk = function (source, property, callback) {
  32982. var value = source[property], length;
  32983. if (typeof value == "object" && value) {
  32984. // `forEach` can't be used to traverse an array in Opera <= 8.54
  32985. // because its `Object#hasOwnProperty` implementation returns `false`
  32986. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  32987. if (getClass.call(value) == arrayClass) {
  32988. for (length = value.length; length--;) {
  32989. update(value, length, callback);
  32990. }
  32991. } else {
  32992. forEach(value, function (property) {
  32993. update(value, property, callback);
  32994. });
  32995. }
  32996. }
  32997. return callback.call(source, property, value);
  32998. };
  32999. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  33000. JSON3.parse = function (source, callback) {
  33001. var result, value;
  33002. Index = 0;
  33003. Source = "" + source;
  33004. result = get(lex());
  33005. // If a JSON string contains multiple tokens, it is invalid.
  33006. if (lex() != "$") {
  33007. abort();
  33008. }
  33009. // Reset the parser state.
  33010. Index = Source = null;
  33011. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  33012. };
  33013. }
  33014. }
  33015. // Export for asynchronous module loaders.
  33016. if (isLoader) {
  33017. define(function () {
  33018. return JSON3;
  33019. });
  33020. }
  33021. }(this));
  33022. },{}],158:[function(require,module,exports){
  33023. module.exports = toArray
  33024. function toArray(list, index) {
  33025. var array = []
  33026. index = index || 0
  33027. for (var i = index || 0; i < list.length; i++) {
  33028. array[i - index] = list[i]
  33029. }
  33030. return array
  33031. }
  33032. },{}],159:[function(require,module,exports){
  33033. var MediaStreamType = {
  33034. VIDEO_TYPE: "Video",
  33035. AUDIO_TYPE: "Audio"
  33036. };
  33037. module.exports = MediaStreamType;
  33038. },{}],160:[function(require,module,exports){
  33039. var RTCEvents = {
  33040. RTC_READY: "rtc.ready",
  33041. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  33042. LASTN_CHANGED: "rtc.lastn_changed",
  33043. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  33044. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  33045. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  33046. AUDIO_MUTE: "rtc.audio_mute",
  33047. VIDEO_MUTE: "rtc.video_mute"
  33048. };
  33049. module.exports = RTCEvents;
  33050. },{}],161:[function(require,module,exports){
  33051. var Resolutions = {
  33052. "1080": {
  33053. width: 1920,
  33054. height: 1080,
  33055. order: 7
  33056. },
  33057. "fullhd": {
  33058. width: 1920,
  33059. height: 1080,
  33060. order: 7
  33061. },
  33062. "720": {
  33063. width: 1280,
  33064. height: 720,
  33065. order: 6
  33066. },
  33067. "hd": {
  33068. width: 1280,
  33069. height: 720,
  33070. order: 6
  33071. },
  33072. "960": {
  33073. width: 960,
  33074. height: 720,
  33075. order: 5
  33076. },
  33077. "640": {
  33078. width: 640,
  33079. height: 480,
  33080. order: 4
  33081. },
  33082. "vga": {
  33083. width: 640,
  33084. height: 480,
  33085. order: 4
  33086. },
  33087. "360": {
  33088. width: 640,
  33089. height: 360,
  33090. order: 3
  33091. },
  33092. "320": {
  33093. width: 320,
  33094. height: 240,
  33095. order: 2
  33096. },
  33097. "180": {
  33098. width: 320,
  33099. height: 180,
  33100. order: 1
  33101. }
  33102. };
  33103. module.exports = Resolutions;
  33104. },{}],162:[function(require,module,exports){
  33105. var StreamEventTypes = {
  33106. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  33107. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  33108. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  33109. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  33110. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  33111. };
  33112. module.exports = StreamEventTypes;
  33113. },{}],163:[function(require,module,exports){
  33114. var UIEvents = {
  33115. NICKNAME_CHANGED: "UI.nickname_changed",
  33116. SELECTED_ENDPOINT: "UI.selected_endpoint",
  33117. PINNED_ENDPOINT: "UI.pinned_endpoint",
  33118. LARGEVIDEO_INIT: "UI.largevideo_init"
  33119. };
  33120. module.exports = UIEvents;
  33121. },{}],164:[function(require,module,exports){
  33122. var AuthenticationEvents = {
  33123. /**
  33124. * Event callback arguments:
  33125. * function(authenticationEnabled, userIdentity)
  33126. * authenticationEnabled - indicates whether authentication has been enabled
  33127. * in this session
  33128. * userIdentity - if user has been logged in then it contains user name. If
  33129. * contains 'null' or 'undefined' then user is not logged in.
  33130. */
  33131. IDENTITY_UPDATED: "authentication.identity_updated"
  33132. };
  33133. module.exports = AuthenticationEvents;
  33134. },{}],165:[function(require,module,exports){
  33135. var CQEvents = {
  33136. LOCALSTATS_UPDATED: "cq.localstats_updated",
  33137. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  33138. STOP: "cq.stop"
  33139. };
  33140. module.exports = CQEvents;
  33141. },{}],166:[function(require,module,exports){
  33142. var DesktopSharingEventTypes = {
  33143. INIT: "ds.init",
  33144. SWITCHING_DONE: "ds.switching_done",
  33145. NEW_STREAM_CREATED: "ds.new_stream_created"
  33146. };
  33147. module.exports = DesktopSharingEventTypes;
  33148. },{}],167:[function(require,module,exports){
  33149. var Events = {
  33150. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  33151. };
  33152. module.exports = Events;
  33153. },{}],168:[function(require,module,exports){
  33154. module.exports = {
  33155. getLanguages : function () {
  33156. var languages = [];
  33157. for(var lang in this)
  33158. {
  33159. if(typeof this[lang] === "string")
  33160. languages.push(this[lang]);
  33161. }
  33162. return languages;
  33163. },
  33164. EN: "en",
  33165. BG: "bg",
  33166. DE: "de",
  33167. TR: "tr",
  33168. FR: "fr"
  33169. }
  33170. },{}],169:[function(require,module,exports){
  33171. var XMPPEvents = {
  33172. // Designates an event indicating that the connection to the XMPP server
  33173. // failed.
  33174. CONNECTION_FAILED: "xmpp.connection.failed",
  33175. // Designates an event indicating that the media (ICE) connection was
  33176. // interrupted. This should go to the RTC module.
  33177. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  33178. // Designates an event indicating that the media (ICE) connection was
  33179. // restored. This should go to the RTC module.
  33180. CONNECTION_RESTORED: "xmpp.connection.restored",
  33181. // Designates an event indicating that an offer (e.g. Jingle
  33182. // session-initiate) was received.
  33183. CALL_INCOMING: "xmpp.callincoming.jingle",
  33184. // Designates an event indicating that we were kicked from the XMPP MUC.
  33185. KICKED: "xmpp.kicked",
  33186. // Designates an event indicating that the userID for a specific JID has
  33187. // changed.
  33188. USER_ID_CHANGED: "xmpp.user_id_changed",
  33189. // Designates an event indicating that we have joined the XMPP MUC.
  33190. MUC_JOINED: "xmpp.muc_joined",
  33191. // Designates an event indicating that a participant joined the XMPP MUC.
  33192. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  33193. // Designates an event indicating that a participant left the XMPP MUC.
  33194. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  33195. // Designates an event indicating that the MUC role of a participant has
  33196. // changed.
  33197. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  33198. // Designates an event indicating that the XMPP MUC was destroyed.
  33199. MUC_DESTROYED: "xmpp.muc_destroyed",
  33200. // Designates an event indicating that the display name of a participant
  33201. // has changed.
  33202. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  33203. // Designates an event indicating that we received statistics from a
  33204. // participant in the MUC.
  33205. REMOTE_STATS: "xmpp.remote_stats",
  33206. // Designates an event indicating that our role in the XMPP MUC has changed.
  33207. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  33208. // Designates an event indicating that the subject of the XMPP MUC has
  33209. // changed.
  33210. SUBJECT_CHANGED: "xmpp.subject_changed",
  33211. // Designates an event indicating that an XMPP message in the MUC was
  33212. // received.
  33213. MESSAGE_RECEIVED: "xmpp.message_received",
  33214. // Designates an event indicating that we sent an XMPP message to the MUC.
  33215. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  33216. // Designates an event indicating that the video type (e.g. 'camera' or
  33217. // 'screen') for a participant has changed.
  33218. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  33219. // Designates an event indicating that a participant in the XMPP MUC has
  33220. // advertised that they have audio muted (or unmuted).
  33221. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  33222. // Designates an event indicating that a participant in the XMPP MUC has
  33223. // advertised that they have video muted (or unmuted).
  33224. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  33225. // Designates an event indicating that the focus has asked us to mute our
  33226. // audio.
  33227. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  33228. // Designates an event indicating that a moderator in the room changed the
  33229. // "start muted" settings for the conference.
  33230. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  33231. // Designates an event indicating that we should join the conference with
  33232. // audio and/or video muted.
  33233. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  33234. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  33235. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  33236. PASSWORD_REQUIRED: "xmpp.password_required",
  33237. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  33238. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  33239. ETHERPAD: "xmpp.etherpad",
  33240. DEVICE_AVAILABLE: "xmpp.device_available",
  33241. BRIDGE_DOWN: "xmpp.bridge_down",
  33242. PRESENCE_STATUS: "xmpp.presence_status",
  33243. RESERVATION_ERROR: "xmpp.room_reservation_error",
  33244. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  33245. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  33246. // TODO: only used in a hack, should probably be removed.
  33247. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  33248. // TODO: only used in a hack, should probably be removed.
  33249. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  33250. // TODO: only used in a hack, should probably be removed.
  33251. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  33252. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  33253. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  33254. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  33255. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  33256. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  33257. // xmpp is connected and obtained user media
  33258. READY_TO_JOIN: 'xmpp.ready_to_join'
  33259. };
  33260. module.exports = XMPPEvents;
  33261. },{}],170:[function(require,module,exports){
  33262. // Copyright Joyent, Inc. and other Node contributors.
  33263. //
  33264. // Permission is hereby granted, free of charge, to any person obtaining a
  33265. // copy of this software and associated documentation files (the
  33266. // "Software"), to deal in the Software without restriction, including
  33267. // without limitation the rights to use, copy, modify, merge, publish,
  33268. // distribute, sublicense, and/or sell copies of the Software, and to permit
  33269. // persons to whom the Software is furnished to do so, subject to the
  33270. // following conditions:
  33271. //
  33272. // The above copyright notice and this permission notice shall be included
  33273. // in all copies or substantial portions of the Software.
  33274. //
  33275. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  33276. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  33277. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  33278. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  33279. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  33280. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  33281. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  33282. function EventEmitter() {
  33283. this._events = this._events || {};
  33284. this._maxListeners = this._maxListeners || undefined;
  33285. }
  33286. module.exports = EventEmitter;
  33287. // Backwards-compat with node 0.10.x
  33288. EventEmitter.EventEmitter = EventEmitter;
  33289. EventEmitter.prototype._events = undefined;
  33290. EventEmitter.prototype._maxListeners = undefined;
  33291. // By default EventEmitters will print a warning if more than 10 listeners are
  33292. // added to it. This is a useful default which helps finding memory leaks.
  33293. EventEmitter.defaultMaxListeners = 10;
  33294. // Obviously not all Emitters should be limited to 10. This function allows
  33295. // that to be increased. Set to zero for unlimited.
  33296. EventEmitter.prototype.setMaxListeners = function(n) {
  33297. if (!isNumber(n) || n < 0 || isNaN(n))
  33298. throw TypeError('n must be a positive number');
  33299. this._maxListeners = n;
  33300. return this;
  33301. };
  33302. EventEmitter.prototype.emit = function(type) {
  33303. var er, handler, len, args, i, listeners;
  33304. if (!this._events)
  33305. this._events = {};
  33306. // If there is no 'error' event listener then throw.
  33307. if (type === 'error') {
  33308. if (!this._events.error ||
  33309. (isObject(this._events.error) && !this._events.error.length)) {
  33310. er = arguments[1];
  33311. if (er instanceof Error) {
  33312. throw er; // Unhandled 'error' event
  33313. }
  33314. throw TypeError('Uncaught, unspecified "error" event.');
  33315. }
  33316. }
  33317. handler = this._events[type];
  33318. if (isUndefined(handler))
  33319. return false;
  33320. if (isFunction(handler)) {
  33321. switch (arguments.length) {
  33322. // fast cases
  33323. case 1:
  33324. handler.call(this);
  33325. break;
  33326. case 2:
  33327. handler.call(this, arguments[1]);
  33328. break;
  33329. case 3:
  33330. handler.call(this, arguments[1], arguments[2]);
  33331. break;
  33332. // slower
  33333. default:
  33334. len = arguments.length;
  33335. args = new Array(len - 1);
  33336. for (i = 1; i < len; i++)
  33337. args[i - 1] = arguments[i];
  33338. handler.apply(this, args);
  33339. }
  33340. } else if (isObject(handler)) {
  33341. len = arguments.length;
  33342. args = new Array(len - 1);
  33343. for (i = 1; i < len; i++)
  33344. args[i - 1] = arguments[i];
  33345. listeners = handler.slice();
  33346. len = listeners.length;
  33347. for (i = 0; i < len; i++)
  33348. listeners[i].apply(this, args);
  33349. }
  33350. return true;
  33351. };
  33352. EventEmitter.prototype.addListener = function(type, listener) {
  33353. var m;
  33354. if (!isFunction(listener))
  33355. throw TypeError('listener must be a function');
  33356. if (!this._events)
  33357. this._events = {};
  33358. // To avoid recursion in the case that type === "newListener"! Before
  33359. // adding it to the listeners, first emit "newListener".
  33360. if (this._events.newListener)
  33361. this.emit('newListener', type,
  33362. isFunction(listener.listener) ?
  33363. listener.listener : listener);
  33364. if (!this._events[type])
  33365. // Optimize the case of one listener. Don't need the extra array object.
  33366. this._events[type] = listener;
  33367. else if (isObject(this._events[type]))
  33368. // If we've already got an array, just append.
  33369. this._events[type].push(listener);
  33370. else
  33371. // Adding the second element, need to change to array.
  33372. this._events[type] = [this._events[type], listener];
  33373. // Check for listener leak
  33374. if (isObject(this._events[type]) && !this._events[type].warned) {
  33375. var m;
  33376. if (!isUndefined(this._maxListeners)) {
  33377. m = this._maxListeners;
  33378. } else {
  33379. m = EventEmitter.defaultMaxListeners;
  33380. }
  33381. if (m && m > 0 && this._events[type].length > m) {
  33382. this._events[type].warned = true;
  33383. console.error('(node) warning: possible EventEmitter memory ' +
  33384. 'leak detected. %d listeners added. ' +
  33385. 'Use emitter.setMaxListeners() to increase limit.',
  33386. this._events[type].length);
  33387. if (typeof console.trace === 'function') {
  33388. // not supported in IE 10
  33389. console.trace();
  33390. }
  33391. }
  33392. }
  33393. return this;
  33394. };
  33395. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  33396. EventEmitter.prototype.once = function(type, listener) {
  33397. if (!isFunction(listener))
  33398. throw TypeError('listener must be a function');
  33399. var fired = false;
  33400. function g() {
  33401. this.removeListener(type, g);
  33402. if (!fired) {
  33403. fired = true;
  33404. listener.apply(this, arguments);
  33405. }
  33406. }
  33407. g.listener = listener;
  33408. this.on(type, g);
  33409. return this;
  33410. };
  33411. // emits a 'removeListener' event iff the listener was removed
  33412. EventEmitter.prototype.removeListener = function(type, listener) {
  33413. var list, position, length, i;
  33414. if (!isFunction(listener))
  33415. throw TypeError('listener must be a function');
  33416. if (!this._events || !this._events[type])
  33417. return this;
  33418. list = this._events[type];
  33419. length = list.length;
  33420. position = -1;
  33421. if (list === listener ||
  33422. (isFunction(list.listener) && list.listener === listener)) {
  33423. delete this._events[type];
  33424. if (this._events.removeListener)
  33425. this.emit('removeListener', type, listener);
  33426. } else if (isObject(list)) {
  33427. for (i = length; i-- > 0;) {
  33428. if (list[i] === listener ||
  33429. (list[i].listener && list[i].listener === listener)) {
  33430. position = i;
  33431. break;
  33432. }
  33433. }
  33434. if (position < 0)
  33435. return this;
  33436. if (list.length === 1) {
  33437. list.length = 0;
  33438. delete this._events[type];
  33439. } else {
  33440. list.splice(position, 1);
  33441. }
  33442. if (this._events.removeListener)
  33443. this.emit('removeListener', type, listener);
  33444. }
  33445. return this;
  33446. };
  33447. EventEmitter.prototype.removeAllListeners = function(type) {
  33448. var key, listeners;
  33449. if (!this._events)
  33450. return this;
  33451. // not listening for removeListener, no need to emit
  33452. if (!this._events.removeListener) {
  33453. if (arguments.length === 0)
  33454. this._events = {};
  33455. else if (this._events[type])
  33456. delete this._events[type];
  33457. return this;
  33458. }
  33459. // emit removeListener for all listeners on all events
  33460. if (arguments.length === 0) {
  33461. for (key in this._events) {
  33462. if (key === 'removeListener') continue;
  33463. this.removeAllListeners(key);
  33464. }
  33465. this.removeAllListeners('removeListener');
  33466. this._events = {};
  33467. return this;
  33468. }
  33469. listeners = this._events[type];
  33470. if (isFunction(listeners)) {
  33471. this.removeListener(type, listeners);
  33472. } else {
  33473. // LIFO order
  33474. while (listeners.length)
  33475. this.removeListener(type, listeners[listeners.length - 1]);
  33476. }
  33477. delete this._events[type];
  33478. return this;
  33479. };
  33480. EventEmitter.prototype.listeners = function(type) {
  33481. var ret;
  33482. if (!this._events || !this._events[type])
  33483. ret = [];
  33484. else if (isFunction(this._events[type]))
  33485. ret = [this._events[type]];
  33486. else
  33487. ret = this._events[type].slice();
  33488. return ret;
  33489. };
  33490. EventEmitter.listenerCount = function(emitter, type) {
  33491. var ret;
  33492. if (!emitter._events || !emitter._events[type])
  33493. ret = 0;
  33494. else if (isFunction(emitter._events[type]))
  33495. ret = 1;
  33496. else
  33497. ret = emitter._events[type].length;
  33498. return ret;
  33499. };
  33500. function isFunction(arg) {
  33501. return typeof arg === 'function';
  33502. }
  33503. function isNumber(arg) {
  33504. return typeof arg === 'number';
  33505. }
  33506. function isObject(arg) {
  33507. return typeof arg === 'object' && arg !== null;
  33508. }
  33509. function isUndefined(arg) {
  33510. return arg === void 0;
  33511. }
  33512. },{}],171:[function(require,module,exports){
  33513. // shim for using process in browser
  33514. var process = module.exports = {};
  33515. var queue = [];
  33516. var draining = false;
  33517. var currentQueue;
  33518. var queueIndex = -1;
  33519. function cleanUpNextTick() {
  33520. draining = false;
  33521. if (currentQueue.length) {
  33522. queue = currentQueue.concat(queue);
  33523. } else {
  33524. queueIndex = -1;
  33525. }
  33526. if (queue.length) {
  33527. drainQueue();
  33528. }
  33529. }
  33530. function drainQueue() {
  33531. if (draining) {
  33532. return;
  33533. }
  33534. var timeout = setTimeout(cleanUpNextTick);
  33535. draining = true;
  33536. var len = queue.length;
  33537. while(len) {
  33538. currentQueue = queue;
  33539. queue = [];
  33540. while (++queueIndex < len) {
  33541. currentQueue[queueIndex].run();
  33542. }
  33543. queueIndex = -1;
  33544. len = queue.length;
  33545. }
  33546. currentQueue = null;
  33547. draining = false;
  33548. clearTimeout(timeout);
  33549. }
  33550. process.nextTick = function (fun) {
  33551. var args = new Array(arguments.length - 1);
  33552. if (arguments.length > 1) {
  33553. for (var i = 1; i < arguments.length; i++) {
  33554. args[i - 1] = arguments[i];
  33555. }
  33556. }
  33557. queue.push(new Item(fun, args));
  33558. if (queue.length === 1 && !draining) {
  33559. setTimeout(drainQueue, 0);
  33560. }
  33561. };
  33562. // v8 likes predictible objects
  33563. function Item(fun, array) {
  33564. this.fun = fun;
  33565. this.array = array;
  33566. }
  33567. Item.prototype.run = function () {
  33568. this.fun.apply(null, this.array);
  33569. };
  33570. process.title = 'browser';
  33571. process.browser = true;
  33572. process.env = {};
  33573. process.argv = [];
  33574. process.version = ''; // empty string to avoid regexp issues
  33575. process.versions = {};
  33576. function noop() {}
  33577. process.on = noop;
  33578. process.addListener = noop;
  33579. process.once = noop;
  33580. process.off = noop;
  33581. process.removeListener = noop;
  33582. process.removeAllListeners = noop;
  33583. process.emit = noop;
  33584. process.binding = function (name) {
  33585. throw new Error('process.binding is not supported');
  33586. };
  33587. // TODO(shtylman)
  33588. process.cwd = function () { return '/' };
  33589. process.chdir = function (dir) {
  33590. throw new Error('process.chdir is not supported');
  33591. };
  33592. process.umask = function() { return 0; };
  33593. },{}]},{},[1])(1)
  33594. });